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>

<html>

<head>

<script src=”http://code.jquery.com/jquery-1.7.1.js”>

</script>

<script>

$(function(){

// 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”); 

});

</script>

</head>

<body>

<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> 

</body>

</html>

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 *