jQuery in Action
Selecting elements for manipulation
27
<td>Dynamic</td>
<td>1972</td>
</tr>
<tr>
<td>C++</td>
<td>Static</td>
<td>1983</td>
</tr>
</tbody>
</table>
Let's say we want to get all of the table cells that contained the names of program-
ming languages. Because they are all the first cells in their row, we can use
ming languages. Because they are all the first cells in their row, we can use
table#languages tbody td:first-child
We can also easily use
table#languages tbody td:nth-child(1)
But the first syntax would be considered pithier and more elegant.
To grab the language type cells, we change the selector to use
:nth-child(2)
,
and for the year they were invented, we use
:nth-child(3)
or
:last-child
. If we
want the absolute last table cell (the one containing the text 1983), we'd use
td:last
.
Also, whereas
td:eq(2)
returns the cell containing the text 1995,
td:nth-child(2)
returns all of the cells giving programming language types. Again, remember
that
that
:eq
is 0-based, but
:nth-child
is 1-based.
Before we move on, head back over to the Selectors Lab, and try selecting
entries two and four from the list. Then, try to find three different ways to select
the cell containing the text 1972 in the table. Also, try and get a feel for the dif-
ference between the
the cell containing the text 1972 in the table. Also, try and get a feel for the dif-
ference between the
nth-child
selectors and the absolute position selectors.
Even though the
CSS
selectors we've examined so far are incredibly powerful,
let's discuss ways of squeezing even more power out of jQuery's selectors.
2.1.4 Using custom jQuery selectors
The
CSS
selectors give us a great deal of power and flexibility to match the
desired
DOM
elements, but sometimes we'll want to select elements based on a
characteristic that the
CSS
specification did not anticipate.
For example, we might want to select all check boxes that have been checked
by the user. Because trying to match by attribute will only check the initial state
of the control as specified in the
of the control as specified in the
HTML
markup, jQuery offers a custom selector,
:checked
, that filters the set of matched elements to those that are in checked
state. For example, whereas the
input
selector selects all
<input>
elements, the