Instance
Select all paragraphs, and then reduce the selection to include only the first and second paragraphs:
$ ("P") .slice(0, 2) . Wrapinner ("");
Try it yourself.
Definition and usage
Slice () reduces the set of matching elements to a subset of the specified exponential range.
Grammar
. Slice (selector,end)
| Parameters |
Description |
| Selector |
An integer value based on 0 that indicates where to start selecting the element.
If it is a negative number, it indicates the offset from the end of the collection. |
| End |
An integer value based on 0 that indicates where to end the selection of the element.
If it is a negative number, it indicates the offset from the end of the collection.
If omitted, the selection ends at the end of the collection. |
Detailed description
Given a jquery object that represents a collection of DOM elements, the. Slice () method constructs a new jquery object with a subset of the matching elements. The position of one of the elements in the applied index parameter collection, and if the end argument is omitted, all elements after index are included in the result.
Consider this page with a simple list:
<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>
We can apply this method to the list item collection:
$ (' li ') .slice(2) . css (' background-color ', ' red ');
Try it yourself.
The result of this call is that the background of items 3, 4, and 5 is set to red. Note that the applied index parameter is based on 0 and refers to the location of the elements in the JQuery object, not the DOM tree.
The end parameter allows us to further restrict the selection range. Like what:
$ (' li ') .slice(2, 4) . css (' background-color ', ' red ');
Try it yourself.
Now, only items 3 and 4 will be selected. Again, index is based on zero, and the range extends to (but does not contain) the specified index.
Negative exponent
The. Slice () method of JQuery mimics the. Slice () method of a JavaScript array object. One of the characteristics it mimics is the ability to pass negative numbers to the start or end parameters. If a negative number is provided, it indicates a position starting at the end of the collection, not from the beginning. For example:
$ (' li ') .slice(-2, -1) . css (' background-color ', ' red ');
Try it yourself.
This time, only the list item 4 will turn red, because the item is the only item in the range between two (-2) counting from the end and one (-1) counting from the end.
JQuery traversal-slice () method