jQuery Traversal - prevUntil() Method

Example

Select all paragraphs and then reduce the selected content to only include the first and second paragraphs:

$("p").slice(0, 2).wrapInner(");

Try it yourself

Definition and Usage

slice() reduces the matched element collection to a subset within the specified index range.

Syntax

.slice(selector,end)
Parameter Description
selector

An integer value based on 0, indicating the position of the start selection element.

If negative, it indicates an offset from the end of the collection.

end

An integer value based on 0, indicating the position of the end selection element.

If negative, it indicates an offset from the end of the collection.

If omitted, the selection range will end at the end of the collection.

Detailed Explanation

If a jQuery object representing a collection of DOM elements is given, the .slice() method constructs a new jQuery object using a subset of the matched elements. The position of one of the elements in the applied index parameter set; if the end parameter is omitted, all elements after the index will be included in the result.

Consider this page with a simple list:

<ul>
  <li>list item 1</li>
  <li>list item 2</li>
  <li>list item 3</li>
  <li>list item 4</li>
  <li>list item 5</li>
</ul>

We can apply this method to the list item collection:

$('li').slice(2).css('background-color', 'red');

Try it yourself

The result of this call is that the background of items 3, 4, and 5 is set to red. Please note that the index parameter applied is based on zero and refers to the position of the elements in the jQuery object, not the DOM tree.

The end parameter allows us to further limit the selection range. For example:

$('li').slice(2, 4).css('background-color', 'red');

Try it yourself

Now, only items 3 and 4 will be selected. Again, the index is zero-based; the range extends to (but does not include) the specified index.

Negative exponents

jQuery's .slice() method mimics the .slice() method of JavaScript array objects. One of the features it mimics is the ability to pass negative numbers to the start or end parameters. If negative numbers are provided, they indicate a position from the end of the collection rather than from the beginning. For example:

$('li').slice(-2, -1).css('background-color', 'red');

Try it yourself

This time, only list item 4 will turn red because this item is the only one within the range between the second from the end (-2) and the first from the end (-1).