The slice method
The slice
method selects a group of elements from those found. For example, you can select elements from the third to the sixth. The count of elements is started from zero. The first parameter of the method is the number from which to take elements (inclusive), and the second is the number up to which (not inclusive). Both parameters can be both positive and negative. In the second case, the count is started from the end, -1
will be the last element, -2
will be the penultimate element, and so on.
Syntax
.slice(from where, to where);
Example
Let's find all the paragraphs, select from the found paragraphs the numbers 1
, 2
and 3
(numbering starts from zero, we don't touch the zero one) and add the text '!'
to the end of them using the append
method:
<p>text0</p>
<p>text1</p>
<p>text2</p>
<p>text3</p>
<p>text4</p>
$('p').slice(1, 4).append();
HTML the code will look like this:
<p>text0</p>
<p>text1!</p>
<p>text2!</p>
<p>text3!</p>
<p>text4</p>