Skip to Main Content
jQuery Pocket Reference
book

jQuery Pocket Reference

by David Flanagan
December 2010
Intermediate to advanced content levelIntermediate to advanced
160 pages
3h 31m
English
O'Reilly Media, Inc.
Content preview from jQuery Pocket Reference

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

jQuery and JavaScript Phrasebook

jQuery and JavaScript Phrasebook

Brad Dayley
Beyond jQuery

Beyond jQuery

Ray Nicholus
Head First jQuery

Head First jQuery

Ryan Benedetti, Ronan Cranley

Publisher Resources

ISBN: 9781449398958Supplemental ContentErrata Page