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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
<!doctype html> <html> <head> <title>jQuery Traversing slice</title> <style> .highlight{ background: yellow; } .highlight1{ background: green; } div{ display: block; border: 3px solid black; color: black; padding: 5px; margin: 25px; width:250px; } </style> <script src="https://code.jquery.com/jquery-2.1.1.js"></script> </head> <body> <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> <script> $( "div" ).slice( 0,2).addClass("highlight1"); $( "div" ).slice( -3,-1 ).addClass("highlight"); </script> </body> </html> |
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);
.
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.