jQuery-besök - prevUntil() metod

Exempel

Välj alla avsnitt och缩减所选内容以仅包含第一和第二个段落:

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

Try it yourself

Definition and usage

slice() reduces the matching 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 it is 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 it is 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 with a subset of matching 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.

Think about 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 element 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 exponent

The .slice() method of jQuery 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, not 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 counting from the end (-2) and counting from the end (-1).