How to Use the jQuery slice() Method

This article explains the purpose, syntax, and behavior of the jQuery slice() method. You will learn how this method extracts a subset of matched elements from a larger jQuery collection using zero-based indices, how positive and negative parameters affect element selection, and how it differs from standard array operations while preserving the original DOM selection.

The jQuery slice() method reduces a set of matched elements to a subset specified by a range of indices. Similar to the native JavaScript Array.prototype.slice() method, it does not alter the original DOM structure or the original jQuery object; instead, it creates and returns a new jQuery object containing only the chosen elements.

Syntax and Parameters

The basic syntax for the method is:

$(selector).slice(start, [end])
  • start (required): A zero-based integer indicating where the extraction begins.
    • If start is positive (e.g., 2), selection begins at that index (the 3rd element).
    • If start is negative (e.g., -2), the position is measured backward from the end of the collection, targeting elements relative to the last item.
  • end (optional): A zero-based integer indicating where the extraction stops.
    • The element at the end index is excluded from the final selection.
    • If omitted, the subset includes all elements from the start position to the end of the collection.
    • If negative, it specifies an offset from the end of the matched set.

How It Works in Practice

Consider a list of six items:

<ul>
  <li>Item 0</li>
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
  <li>Item 4</li>
  <li>Item 5</li>
</ul>
  1. Selecting from an index to the end:

    $('li').slice(2);

    This returns elements from index 2 through index 5 (Item 2, Item 3, Item 4, Item 5).

  2. Selecting a specific range:

    $('li').slice(1, 4);

    This selects elements at index 1, 2, and 3 (Item 1, Item 2, Item 3). Index 4 is excluded.

  3. Using negative indices:

    $('li').slice(-3);

    This targets the last three items in the set (Item 3, Item 4, Item 5).

  4. Combining positive and negative indices:

    $('li').slice(1, -1);

    This starts at index 1 and stops one element before the end, omitting the first item (Item 0) and the last item (Item 5).

By returning a new jQuery object containing only the elements within the defined boundaries, the slice() method enables clean, efficient pagination, batch styling, and targeted DOM manipulation without needing explicit loops.