The jQuery slice() method can be used to select a subset of elements based on a specified set of indexes. The group index starts from index 0 and you have to specify the start index to select elements.
Syntax
The syntax of this method is given below:-
Description of the Parameters
The description of these parameters is given below.
Parameter Name | Description |
---|---|
selector | Specify the element to select and get a subset of elements based on the index. You can use the element tag name, class name, or id to select. It is a required field. |
startIndex | Each element starts with an index 0. You have to specify the start index of the elements to select. It is a required field. |
endIndex | You have to specify the end index to select the subset of element from the specified boundary. It is an optional field. |
jQuery slice() Method to Select a Subset of Elements With Start Index
If you want to select all the subset of elements after the specified index, you have to use the method as given below. The below example contains the list elements to select its subset using slice(). The functions take parameter as 2 to select all the elements start from index 2.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<script> $(document).ready(function(){ $('.mybtn').click(function(){ $("ul li").slice(2).css("color","orange"); }); }); </script> <ul> <li>0 index</li> <li>1st index</li> <li>2nd index</li> <li>3rd index</li> </ul> <button type="button" class="mybtn">Click to Select</button> |
Output
- 0 index
- 1st index
- 2nd index
- 3rd index
You have to click the button given above to select the list element. It selects the list elements at index position 2 and 3 and further. After selection, it applies the orange color to the text of list elements.
Select a Subset of Elements With Start and End Index Set
If you want to select the subset of elements within the given set of indexes, you have to use the jQuery slice() method as given below. The below example contains the method with the start and end index as the parameter.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<script> $(document).ready(function(){ $('.mysetbtn').click(function(){ $("ul li").slice(2,5).css("color","yellow"); }); }); </script> <ul> <li>0 index</li> <li>1st index</li> <li>2nd index</li> <li>3rd index</li> <li>4th index</li> <li>5th index</li> <li>6th index</li> </ul> <button type="button" class="mysetbtn">Click to Select</button> |
Output
- 0 index
- 1st index
- 2nd index
- 3rd index
- 4th index
- 5th index
- 6th index
When you click the button given above, it selects the elements located from index 2 to index 5. It applies the yellow color to the selected elements within the specified range.
You may also like to read
I hope you like this tutorial on jQuery slice() method. If you have any queries regarding the tutorial, please comment below.
References