jQuery slice() Method

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.

jQuery slice() Method

Syntax

The syntax of this method is given below:-

Syntax
$(selector).slice(startIndex, endIndex)

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

Test it Live

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

Test it Live

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