jQuery .slice()
Learn all about the jQuery function .slice().
Given a jQuery object that represents a set of DOM elements, the .slice()
method constructs a new jQuery object containing a subset of the elements specified by the start
and, optionally, end
argument. The supplied start
index identifies the position of one of the elements in the set; if end
is omitted, all elements after this one will be included in the result.
Consider a page with a simple list on it:
1
2
3
4
5
6
7
|
|
We can apply this method to the set of list items:
1
|
|
The result of this call is a red background for items 3, 4, and 5. Note that the supplied index is zero-based, and refers to the position of elements within the jQuery object, not within the DOM tree.
The end parameter allows us to limit the selected range even further. For example:
1
|
|
Now only items 3 and 4 are selected. The index is once again zero-based; the range extends up to but not including the specified index.
Negative Indices
The jQuery .slice()
method is patterned after the JavaScript .slice() method for arrays. One of the features that it mimics is the ability for negative numbers to be passed as either the start
or end
parameter. If a negative number is provided, this indicates a position starting from the end of the set, rather than the beginning. For example:
1
|
|
This time only list item 4 is turned red, since it is the only item in the range between two from the end (-2
) and one from the end (-1
).