How to create custom selectors in jQuery?

jQuery's selectors engine is one powerful piece of DOM parsing tool. It allows to easily select HTML objects based on the tag name, ID, class, or any other attribute we want. Using jQuery selectors we can significantly speed up development and make our life easier.

One of the interesting things about jQuery is the fact, we can write our own, fully customized selectors. Example below shows how can we archive that by extending standard class. In my example, I create my own custom selector, to select all elements with font color set as "red" or "blue".

$.extend($.expr[':'], {
    redOrBlue: function(o) {
        return ($(o).css("color") == "red") 
               || ($(o).css("color") == "blue");
    }
});

And this is my code in action:

Code
//add border to all elements with font color set as "red" or "blue"
$(function() {
    $('div:redOrBlue').css("border", "2px solid #000");
});
<div style="color:red;">this text is red</div>
<div style="color:blue;">this text is blue</div>
<div style="color:green;">this text is green</div>
<div style="color:#00f;">this text is also blue, 
but color is defined with HEX</div>
Preview
this text is red
this text is blue
this text is green
this text is also blue, but color is defined with HEX

As you can see above, custom selector found all elements with "red" or "blue" color and added border to it.

Conclusion

Custom selectors are useful when we want to look for very specific elements. Every time when there is a need to find elements based on few CSS properties and i.e. their innerHTML and we need to repeat this action many times, we should consider using custom selectors.

Did you like my article? Share it!
Share/Bookmark

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <csharp>, <css>, <html>, <javascript>, <vb>, <vbnet>, <xml>. Beside the tag style "<foo>" it is also possible to use "[foo]".

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters (without spaces) shown in the image.
served by y.co.uk