jQuery – Custom Filters

Hello
Sometimes we may need to collect html elements with certain filter which jQuery doesn’t provide. At that time we can simple create custom filters in jQuery. I found such a nice blog – Creating Custom Filters in jQuery. Let’s look how to create custom filters in jQuery.

<script>
    $.expr[':'].placeholder = function(elem) {
        return $(elem).attr('placeholder') !== undefined;
    };
    
    $(document).ready(function() {
        console.log($(':placeholder').length);
    });
</script>


A filter is nothing but a function that accepts as an argument the current DOM element to process and needs to return true to keep it in the collection, and false to discard it.

“:” is a property of jQuery’s “expr” attribute. And it containing jQuery’s native filters and you can use it to add your own filter at runtime. Inside the function definition, we just have a single statement that checks if the current element has the placeholder attribute set, and if so, it returns true to keep the element.

For more on creating custom filters in jQuery please go to: http://aurelio.audero.it/blog/2013/09/05/how-to-create-custom-filters-in-jquery/

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s