Create a Custom jQuery Selector

jQuery has a rich and powerful collection of selectors. jQuery being extensible, also allows you to add your own set of custom selectors with ease. Here’s an example of how to create your own custom selector that identifies all mailto: links on a page.

Note: You can find a full list of jQuery selectors on the jQuery site at http://api.jquery.com/category/selectors/

<html xmlns="http://www.w3.org/1999/xhtml" >
<
head>
<
title>Create jQuery Custom Selector from DevCurry.com</title>
<
style type="text/css">
div { height: 150px; width: 250px; border: 1px solid black; }
</style>
<
script type="text/javascript"
src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.min.js">
</
script>

<
script type="text/javascript">
$(function () {
$.extend($.expr[':'], {
mailToLink: function (obj) {
return obj.href.match(/^mailto\:/);
}
});

$("#btnFindMailTo").click(function () {
$("div a:mailToLink").css("color", "red");
});
});
</script>
</
head>
<
body>
<
p>List of Links:</p>
<
div>
<
a href="http://jquery.com">jquery</a><br />
<
a href="http://www.devcurry.com/">devcurry</a><br />
<
a href="http://www.dotnetcurry.com">dotnetcurry</a><br />
<
a href="mailto:fakeaddr@devcurry.com">fakeaddr@devcurry.com</a>
</
div>

<
input id="btnFindMailTo" type="button" value="Find mailto: links" />
</
body>
</
html>

In the code shown above, we have extended jQuery’s selector expressions under the jQuery.expr[':'] object (read more about sizzle) and have defined a custom selector called :mailToLink. We pass in the object, which is a collection of links, to this selector that looks for all anchor elements containing an href attribute that matches mailto:

jquery custom selector

Once we have created this selector :mailToLink, we can use it in a similar way shown below:

jquery custom selector

When you click the button, only the last link’s color is set to red, since that’s the only one with an href containing mailto:

OUTPUT

image

See a Live Demo


Read some more jQuery Tips here





About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

5 comments:

Anonymous said...

Very nice and simple.
Thanks, George.

salwar said...

Thanks for giving such a nice information...

sudhan form callezee said...

thank you this information gave me lot of ideas..

Paulo Jorge Dias said...

jQuery have any selector for xpath?
Thanks for your informative articles.
Paulo

Suprotim Agarwal said...

jQuery selectors earlier were made of Xpath + CSS3. But the latest jQuery library does not support Xpath.

Infact it is not needed anymore as the current CSS 3 selectors do the job!