jQuery Selectors and Selection Methods

Throughout this chapter, we’ve been using the jQuery selection function, $(), with simple CSS selectors. It is now time to study the jQuery selector grammar in depth, along with a number of methods for refining and augmenting the set of selected elements.

jQuery Selectors

jQuery supports a fairly complete subset of the selector grammar defined by the CSS3 Selectors draft standard, with the addition of some nonstandard but very useful pseudoclasses. Basic CSS selectors were described in Selecting Elements with CSS Selectors. We repeat that material here, and add explanations for more advanced selectors as well. Bear in mind that this section documents jQuery selectors. Many, but not all, of these selectors can also be used in CSS stylesheets.

The selector grammar has three layers. You’ve undoubtedly seen the simplest kind of selectors before. “#test” selects an element with an id attribute of “test”. “blockquote” selects all <blockquote> elements in the document, and “div.note” selects all <div> elements with a class attribute of “note”. Simple selectors can be combined into “selector combinations” such as “div.note>p” and “blockquote i” by separating them with a combinator character. And simple selectors and selector combinations can be grouped into comma-separated lists. These selector groups are the most general kind of selector that we pass to $(). Before explaining selector combinations and selector groups, we must explain the syntax of simple ...

Get JavaScript: The Definitive Guide, 6th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.