jQuery: the slice() method

jQuery provides a useful DOM method for selecting a subset within a matched wrapped set. This method is called slice() and accepts two parameters. The first is the numerical index (starting from 0) of the first element of the new subset, while the second is the number of elements that will be contained in the new subset (starting from the first element of the wrapped set, that is, from 1). So given the following DOM structure:

<ul id="test">



As we said earlier, the syntax of this method is:

set.slice(index, length);

The first item in our list has index 0. So to select a new subset starting from the first item and ending with the fourth, we can write:

$('#test li').slice(0, 4);

The second parameter starts from 1, not from 0, so we'll have:

A = 1
B = 2
C = 3
D = 4

Here's a practical example:

$('#run').click(function(e) {
    $('#test li').slice(1,4).addClass('test');

This will select the items B, C and D and apply a class to them. You can see a demo below.


Live demo

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.