jQuery: selectors tutorial

This tutorial on jQuery selectors is made up of two parts: the first one is a visual introduction to jQuery selectors using a YouTube video tutorial by ThinkVitamin. The second part, instead, is a more in depth analysis of how jQuery selectors actually work. If you're ready, we can get started.


How jQuery selectors work

jQuery selectors work thanks to the Sizzle selector engine which automatically converts string-based expressions into their DOM equivalent. A jQuery selector is simply an expression that is passed to the $() (or jQuery) wrapper method, converted into a DOM selection and returned as a set of one or more elements (called the wrapped set because of the presence of the jQuery wrapper method). The first thing you have to bear in mind is that the returned set is made up of jQuery element objects, not DOM objects. For example, this won't work:


It doesn't work because we're still within the global jQuery namespace. To make it work, we have to get out of the wrapped set:


The above bracketed syntax returns a DOM element, not a jQuery element so that the core DOM method getElementsByTagName() works as expected.

The jQuery wrapper method is smart enough to detect if the arguments passed to it are plain strings or DOM expressions. In the latter case, jQuery encapsulates the DOM expression within its namespace:


Another thing to consider is the context where the selection of elements takes place. By default, jQuery starts its chain from the document object if no context has been provided. This can be very expensive in terms of performance, especially on large documents. Instead, if you specify a context as the second parameter of the wrapper method, performance improves greatly, because jQuery starts its chain only from that given context:

$('p', '#test').addClass('test');

Finally, since the selector syntax is exactly the same as the CSS syntax and the expressions are evaluated in the same way, you should pay a special attention to the specificity of your selectors. For example, if in your CSS you have specified some styles with a greater specificity, attempting to reset them using jQuery selectors may fail if your selector specificity is lower than the CSS selectors specificity.

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.