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.
Post new comment