Now, that might not sound quite so straight forward but let's step back and remember one fundamental aspect of jQuery: a jQuery set is really just an array and the array is ordered in the same order each element is found in the DOM. Take this list for instance:
<ul class="colors"> <li>Red</li> <li>Orange</li> <li>Yellow</li> <li>Green</li> <li>Blue</li> <li>Indigo</li> <li>Violet</li> </ul>
We can create a set of those list items using:
Now, that by itself doesn't do anything at all, but we can visualize the set as an array with "Red" at position zero, "Orange" at position one, "Yellow" at position two and so on. This makes figuring out slice a piece of cake. Let's see how it might work in practice:
Will hide "Yellow" and "Green" (We start at position 2 and end just before position 4).
Another fun trick is using a negative number for the start position. When a negative number is passed in the slice starts from the end of the array instead of the beginning. This would mean that
will hide "Blue", "Indigo" and "Violet". Now obviously these examples aren't exactly real world practice but they help illustrate the point. Good places to use this is in dealing with paging for circular carousels (a discussion for another day), in page pagination (hiding everything but the first three paragraphs of a post with a "read more" link) and more.
There is even another nice pro-tips about jQuery's slice: it's non-destructive on existing variables:
var colors = $('ul.colors'); colors.slice(1,4).hide();
If we run console.log(colors), the entire set is still there, "Red" through "Violet".
So there you have it - the jQuery slice() method; another invaluable tool in the front-end developers toolkit.