jQuery in Action
Selecting elements for manipulation
25
For example, consider
a:first
This format of selector matches the first
<a>
element on the page.
What about picking every other element?
p:odd
This selector matches every odd paragraph element. As we might expect, we can
also specify that evenly ordered elements be selected with
also specify that evenly ordered elements be selected with
p:even
Another form
li:last-child
chooses the last child of parent elements. In this example, the last
<li>
child of
each
<ul>
element is matched.
There are a whole slew of these selectors, and they can provide surprisingly
elegant solutions to sometimes tough problems. See table 2.2 for a list of these
positional selectors.
positional selectors.
Table 2.2 The more advanced positional selectors supported by jQuery: selecting elements based
on their position in the DOM
on their position in the DOM
Selector
Description
:first
The first match of the page. li a:first returns the first link also under
a list item.
:last
The last match of the page. li a:last returns the last link also under
a list item.
:first-child
The first child element. li:first-child returns the first item
of each list.
:last-child
The last child element. li:last-child returns the last item
of each list.
:only-child
Returns all elements that have no siblings.
:nth-child(n)
The nth child element. li:nth-child(2) returns the second list item of
each list.
each list.
:nth-child(even|odd)
Even or odd children. li:nth-child(even) returns the even children
of each list.
of each list.
continued on next page