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:
Once we have created this selector :mailToLink, we can use it in a similar way shown below:
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
See a Live Demo
Read some more jQuery Tips here
Tweet
5 comments:
Very nice and simple.
Thanks, George.
Thanks for giving such a nice information...
thank you this information gave me lot of ideas..
jQuery have any selector for xpath?
Thanks for your informative articles.
Paulo
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!
Post a Comment