**Note:** If this value is negative, it indicates an offset from the end of the set (e.g., `-2` selects the last two elements). | | `stop` | *Integer* | **Optional.** Specifies where to stop selecting elements. The selection goes up to, but does not include, this index. If omitted, the selection continues to the end of the set.
**Note:** If this value is negative, it indicates an offset from the end of the set. | --- ### Code Examples #### 1. Basic Usage: Selecting from a Start Index to the End This example selects all `
` elements starting from index position 2 (the third paragraph) to the end of the collection. ```javascript // Selects the 3rd paragraph and all subsequent paragraphs $("p").slice(2).css("background-color", "yellow"); ``` #### 2. Using Both Start and Stop Parameters This example selects `
` elements starting from index 1 (the second paragraph) up to, but not including, index 3 (the fourth paragraph). This targets indices 1 and 2. ```javascript // Selects the 2nd and 3rd paragraphs $("p").slice(1, 3).css("background-color", "lightblue"); ``` #### 3. Using a Negative Start Index Using a negative number allows you to select elements starting from the end of the collection. ```javascript // Selects the last two
elements in the document $("p").slice(-2).css("background-color", "lightgreen"); ``` #### 4. Using Negative Indices for Both Start and Stop You can combine negative indices to target a specific range relative to the end of the collection. ```javascript // Selects the 3rd to last and 2nd to last
elements // (Excludes the very last element at index -1) $("p").slice(-3, -1).css("background-color", "pink"); ``` --- ### Key Considerations * **End Index is Exclusive:** Remember that the `stop` parameter is exclusive. For example, `.slice(0, 3)` will select elements at index `0`, `1`, and `2`, but not `3`. * **No DOM Modification:** The `slice()` method does not alter the DOM tree; it only filters the jQuery object collection in memory so you can apply subsequent actions (like CSS changes or animations) to the filtered subset. * **Chaining:** Like most jQuery methods, `slice()` returns a jQuery object, allowing you to chain other jQuery methods immediately after it.
YouTip