Using jQuery Selectors

jQuery Selectors are a powerful feature of the framework that is essentially one of the main reasons that you’d want to use it in the first place. Those who are already familiar with how CSS3 selectors work will feel right at home with the concept of selectors. Today’s modern browsers at best support “most” of the CSS3 specification (with Firefox 3 & Safari), while others use only limited features of it. What’s so nice about jQuery is that the browser doesn’t need to support the CSS3 specification for you to use them within the framework itself. Those familiar with XPath will also be happy to know that simple XPath selectors are also supported via a plugin for jQuery if preferred. Here are some examples to demonstrate the power of selectors:

Style alternate table rows

$("table#mytable tbody tr:even").addClass("alt");

Add text based on a link’s file extention

$("a[href$=.pdf]").append(" (pdf download)");

Style links to external sites


Keep in mind that these are one line of code each that would otherwise take somewhere between 5 and 10 lines of javascript. As an added benefit, they also will execute as soon as the document object model is ready since the “$” shortcut function performs this for us behind the scenes. It is essentially waiting for the earliest time that the script is able to run, when all markup has been loaded (but not images or flash videos) so that we’re not having to wait for larger files to load before hand.

jQuery also has custom selectors which act like shortcuts for some common tasks. For example, you can find all buttons with $(:button), find all checkboxes with $(:checkbox), etc. If you would like to learn more, there is a jQuery selector documentation on their website as well.

Show Comments