Quantcast
Viewing all articles
Browse latest Browse all 5

Write your own selectors

jQuery has loads of built-in selectors for selecting elements by ID, class, tag, attribute and many more. But what do you do when you need to select elements based upon something else and jQuery doesn’t have a selector?

Well, one answer would be to add classes to the elements from the start and use those to select them, but it turns out that it’s not hard to extend jQuery to add new selectors.

The best way to demonstrate is with an example.

$.extend($.expr[':'], {
    over100pixels: function(a) {
        return $(a).height() > 100;
    }
});

$('.box:over100pixels').click(function() {
    alert('The element you clicked is over 100 pixels high');
});

The first block of code creates a custom selector which finds any element that is more than 100 pixels tall. The second block just uses it to add a click handler to all those elements.

I won’t go into any more detail here but you can imagine how powerful this is and if you search google for “custom jquery selector” you’ll find loads of great examples.


Viewing all articles
Browse latest Browse all 5

Trending Articles