Chapter 2. Selector Expressions

You got me lookin' up high

You got me searchin' down low

—Devo,

"Jerkin' Back 'n' Forth"

Borrowing from CSS 1-3 and basic XPath, and then adding its own, jQuery offers a powerful set of selector expressions for matching a set of elements in a document. In this chapter, we'll examine every selector expression that jQuery makes available in turn.

The following selectors are based on the CSS 1-3, as outlined by the W3C. For more information about the specifications, visit http://www.w3.org/Style/CSS/#specs.

All elements that are the nth child of their parent.

Because jQuery's implementation of :nth-child(n) is strictly derived from the CSS specification, the value of n is 1-based, meaning that the counting starts at 1. For all other selector expressions, however, jQuery follows JavaScript's "0-based" counting. Therefore, given a single <ul> containing two <li>s, $('li:nth-child(1)') selects the first <li> while $('li:nth(1)') selects the second.

Because the two look so similar, the :nth-child(n) pseudo-class is easily confused with :nth(n), even though, as we have just seen, the two can result in dramatically different matched elements. With :nth-child(n), all children are counted, regardless of what they are, and the specified element is selected only if it matches the selector attached to the pseudo-class. With :nth(n) only the selector attached to the pseudo-class is counted, not limited to children of any other element, and the nth one is selected. To demonstrate this distinction, let's examine the results of a few selector expressions given the following HTML:

$('p:nth(1)') selects the second <p>, because numbering for :nth(n) starts with 0.

$('p:nth-child(1)') selects nothing, because there is no <p> element that is the first child of its parent.

$('p:nth(2)') selects the third <p>.

$('p:nth-child(2)') selects the first <p>, because it is the second child of its parent.

In addition to taking an integer, :nth-child(n) can take even or odd. This makes it especially useful for table-row striping solutions when more than one table appears in a document. Again, given the HTML snippet above:

$('p:nth-child(even)') selects the first and third <p>, because they are children 2 and 4 (both even numbers) of their parent.