Create custom selector using jQuery

Today i came to know one very advanced jQuery Concept.
jQuery has its selectors inbuilt. here you can create your own custom selector.
In below code i have given name ‘myCustomSelector’ to my custom selector.
All we need to do is to define it and to give an expression that returns true or false.

  • 5th Line : jQuery.extend is used to extend jQuery to create plugins but in this example it is used to extend jQuery’s ‘:’ expression.
  • 6th Line : a is an object which represents the current element.It is similar to this in other expressions.

Run demo
Have a look at code below.

[code:xml]
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
jQuery.extend(jQuery.expr[‘:’], {
myCustomSelector : function (a){
return jQuery(a).html() == ‘Akash’;
}
});
jQuery(document).ready(function() {
jQuery(‘td:myCustomSelector’).css(‘background-color’,’#ff0000′);
});
</script>
</head>
<table border="1">
<tbody>
<tr><td>Pritesh</td><td>Pradeep</td><td>Vidhi</td></tr>
<tr><td>Naresh</td><td>Akash</td><td>Nirav</td></tr>
<tr><td>Akash</td><td>Bharat</td><td>Rahul</td></tr>
</tbody>
</table>
</html>
[/code]