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.
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.
<title>jQuery Traversing slice</title>
border: 3px solid black;
<h2>jQuery slice() demo</h2>
<div>My index is 0, also -6 from last</div>
<div>My index is 1, also -5 from last</div>
<div>My index is 2, also -4 from last</div>
<div>My index is 3, also -3 from last</div>
<div>My index is 4, also -2 from last</div>
<div>My index is 5, also -1 from last</div>
$( "div" ).slice( 0,2).addClass("highlight1");
$( "div" ).slice( -3,-1 ).addClass("highlight");
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
$( "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
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.