Earlier we looked how to get an element with specific index in jQuery, but sometimes we want to get subset of the element indexes array. We can use slice() method for this.

jQuery slice()

The slice() method reduces the matched set of elements to a subset specified by a range of indices. This method accepts two integer values, start index and end index. This method will return the elements between the start and end index. The subset of elements includes the element at start index but excludes element at end index.

Here is the general syntax for using jQuery slice()

  • selector.slice(start, end)

start: This is a mandatory parameter which specifies the starting index at which the elements begin to be selected. The index numbers start at 0 . Using a negative number indicates an offset from the end of the matched set of elements.

end: This is an optional parameter which specifies the ending index at which the elements stop being selected. The range of selection continues until the end of the matched set if we omit the end index.

jQuery slice() example

Following example demonstrates the jQuery slice() usage.

in this example, we have used both positive and negative indices for the start and end parameters.

$( "div" ).slice( 0,2).addClass("highlight1");: This will select the div elements between the start index 0 and end index 2 and changes the color to green. The slice() method used in this line is same as slice(-6,-4);.

$( "div" ).slice( -3,-1 ).addClass("highlight"); This will select the div elements between the start index -3 and end index -1 and changes the color to yellow. The slice() method used in this line is same as slice(3,5);.

jquery-slice-example-411x450

The jQuery slice() method is very useful when you want to get a subset of elements from the matched set. That’s all for now, we will look into more jQuery methods in coming posts.

By admin

Leave a Reply

%d bloggers like this: