The Power of jQuery Selectors: Custom User Selectors

If the current built-in selectors aren’t enough, you can extend jQuery with your own custom-made selectors. To do so, you must extend the core jQuery object. The following code snippet creates a custom selector that selects elements with a green background:

<!DOCTYPE html>



<script src=””>




// Define custom filter by extending $.expr[“:”]

$.expr[“:”].greenbg = function(element) {

return $(element).css(“background-color”) === “green”;


var n = $(“:greenbg”).length;

console.log(“There are ” + n + “green divs”); 





<div style=”width:10; height:10; background-color:green;”></div> 

<div style=”width:10; height:10; background-color:black;”></div> 

<div style=”width:10; height:10; background-color:blue;”></div> 



Code snippet is from custom-filters.txt

The capacity to create your own ad-hoc selectors is a welcome feature, because you’re not limited to the built-in selector domain.

Source: Otero Cesar, Rob Larsen (2012), Professional jQuery, John Wiley & Sons, Inc

Leave a Reply

Your email address will not be published. Required fields are marked *