How to create Custom User Selectors for jQuery

Custom Selectors

You can extend the core jQuery object. The following code snippet creates a custom selector that selects elements with a red background.


<!DOCTYPE html> 
<html>
    <head>
        <script src="http://java2s.com/style/jquery-1.8.0.min.js"> 
        </script>
        <script>
<!--from  w ww.  j av a  2 s.  co  m-->
            $(function(){ 
                $.expr[":"].redbg = function(element) {
                    return $(element).css("background-color") === "red"; 
                }; 
                var n = $(":redbg").length; 
                document.writeln(n);

            });
        </script> 
    </head> 
    <body>
        <div style="width:10; height:10; background-color:green;"></div> 
        <div style="width:10; height:10; background-color:red;"></div> 
        <div style="width:10; height:10; background-color:blue;"></div>

    </body> 
</html>

Click to view the demo





















Home »
  jQuery »
    jQuery Tutorial »




Basics
Selector
DOM
Event
Effect
Utilities