.Slice() Method In jQuery

jQuery Slice() method gets a subset of the matched elements by giving a range of indices. Here is a jQuery.Slice() code example.

.slice( start, end[Optional] )
 

Description

 
This method selects a subset of the matched elements by giving a range of indices. In other words, it gives the set of DOM elements on the basis of its parameter (start, end).
 

Start

 
This is the first and mandatory parameter of the Slice method. This specifies from where to start to select the elements. The supplied index is zero-based. The Starting index can be a negative number; in other words, the elements are being selected from the end of the set, rather than the beginning.
 

End

 
This is an optional parameter. It specifies the range of the selection. This indicates where to stop the selection of elements, excluding end element. This also uses a 0-based position. If this parameter is not specified than all elements are selected from the starting index in the result.
 
Note
The Negative Indices is started from -1. This last element is denoted by index -1 and so on.
 
Let's see some small examples to understand it.
 
Here is my style,
  1. <style>  
  2.   .selected { color:red; }  
  3. </style>  
Here is my HTML,
  1. <body>  
  2.    <div>  
  3.    <ul>   
  4.       <li>Item 1</li>  
  5.       <li>Item 2</li>  
  6.       <li>Item 3</li>  
  7.      <li>Item 4</li>  
  8.      <li>Item 5</li>  
  9.    </ul>  
  10.    </div>  
  11. </body> 
Now, here is the script,
  1. <script language="javascript" type="text/javascript">  
  2.  $(document).ready(function () {  
  3.   $("li").slice(0, 1).addClass("selected"); });  
  4. <script>  
 
If I want only the first element to be selected then I use the slice method.

Then, my query will be,
  1. $("li").slice(0, 1).addClass("selected");   
Result

slice-method-in-jquery.jpg

If I want to make the background Black for items 3, 4 and 5 then:
  1. $('li').slice(2).css('background-color''pink');  
Result

li-in-jquery.jpg
 
Now only items 1 and 2 are selected.
  1. $('li').slice(0,2).css('background-color''red');  
Result

slice-in-jquery.jpg

Use of Negative Numbers


The -1 index specifies the last element in the list of elements. Therefore when using a negative index position, the start index must be smaller than the end index.

Example

To select the bottom 3 elements,
  1. $("li").slice(-3).addClass("selected");     
Result

example-of-slice-method-in-jquery.jpg

To select the top 2 elements,
  1. $("li").slice(-5,-3).addClass("selected");   
Result

Negative-index-in-slice-method.jpg