Today the project encountered to get the first few and the last few elements, looked up the data found this slice () method is very practical, waste a kung fu finally understand how to use.
Slice (start[,end]): Start Type:Integer
the position at which to start selecting a subset. The first element is 0. If it is a negative number, you can start with the tail of the collection.
end (optional) Type:Integer
End Pick Your own location, if not specified, it is the end of itself. If the provided jquery represents a set of DOM elements, the slice () method constructs a new jquery object from a subset of the matching elements. The provided start index identifies the position of the element in a set, and if End is omitted, all elements after the element are included in the result. For example:<ul>
<li>List Item 1</li>
<li>List Item 2</li>
<li>List Item 3</li>
<li>List Item 4</li>
<li>List Item 5</li>
</ul>
1.$(' Li '). Slice (2). CSS (' Background-color ', ' Red ');
The result of the above code is that the background color of item 3,4,5 is changed to red. Note that the index is counted starting at 0 and represents the position of the element in the JQuery object.
2.$(' Li '). Slice (2, 4). CSS (' Background-color ', ' Red ');
The result of the above code is that only the 3rd and 4th item list items will be selected. The index is still counted starting at 0, but the element specified by the end parameter is not included in the selected element.
3. Negative index
The . Slice () method of jquery is modeled after the. Slice () method of the JavaScript array. One of the functions is to allow the negative start and end parameters to be passed in . If a negative number is passed, the subscript position starts at the end rather than from the starting position. For example:
$(' Li '). Slice (-2, -1). CSS (' Background-color ', ' Red ');
As a result, only item 4 becomes red, because it is the only list item that satisfies the criteria, that is,the element that is selected is the element that starts from the penultimate element (-2) to the last element(-1 ) (excluding this element).
$(' Li '). Slice (-2). CSS (' Background-color ', ' Red ');
4th, 5 items are red, That is, the selected element is the element between the beginning of the penultimate element and the last element, which contains this element.