Webistrate - Draw Your Own Conclusions

jQuery: Creating Your Own Selector

Posted by Jamie Munro | January 16, 2012 | Tags:

Share

By default, the jQuery selectors are pretty advanced.  You can select items by classes, ids, attributes, the first, the last, etc…  But why stop there?  By simply extending jQuery, we can add our own custom selectors to further enhance how we use jQuery.

Let’s begin by looking at a basic, pre-existing, jQuery selector:

$(".myClass:first").toggle();

In the above code example, I am toggling the first element that jQuery finds with the class name of myClass.  Now, what if I want to find an element with the name of myClass that has a width of over 300 pixels?  It would be nice to do something like this:

$(".myClass:widthOver300").toggle();

This can be accomplished with a nice little jQuery extension as follows:

$.extend($.expr[":"], {
widthOver300: function (e)
{
return $(e).width() > 300;
}
});

With the above code added, if I re-run the previous example, all elements with the class name of myClass that have a width of more than 300 pixels will be toggled on or off.

Summary

By extending jQuery, you can add custom selectors to help make your code more readable and reusable.  Simply be sure to check jQuery first so that selector doesn’t already exist as you wouldn’t want to reinvent the wheel!

Share


Related Posts

Leave a Reply

You must be logged in to post a comment.

Buy one of my books