O'Reilly logo

jQuery Pocket Reference by David Flanagan

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Selection Methods

In addition to the selector grammar supported by $(), jQuery defines a number of selection methods. Most of the jQuery methods we’ve seen so far in this chapter perform some action on the selected elements. The selection methods are different: they alter the set of selected elements by refining it, augmenting it, or just using it as a starting point for a new selection.

This section describes these selection methods. You’ll notice that many of the methods provide the same functionality as the selector grammar itself.

The simplest way to refine a selection is by its position within the selection. first() returns the jQuery object that contains only the first selected element, and last() returns the jQuery object that contains only the last element. More generally, the eq() method returns a jQuery object that contains only the single selected element at the specified index. (In jQuery 1.4, negative indexes are allowed and count from the end of the selection.) Note that these methods return a jQuery object with a single element. This is different than regular array indexing, which returns a single element with no jQuery object wrapped around it:

var paras = $("p");
paras.first()         // Select only the first <p> tag
paras.last()          // Select only the last <p>
paras.eq(1)           // Select the second <p>
paras.eq(-2)          // Select the second to last <p>
paras[1]              // The second <p> tag, itself

The general method for refining a selection by position is slice(). The jQuery slice() method works ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required