Start the selection of <p> elements from the <p> element with index number 2:
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("p").slice(2).css("background-color", "yellow"); });/*from w w w . j ava 2s. co m*/ </script> </head> <body> <p>This is a test (index 0).</p> <p>CSS (index 1).</p> <p>I am from java2s.com (index 2).</p> <p>This is another test (index 3).</p> </body> </html>
The slice()
method gets a subset of elements based on index.
$(selector).slice(start,stop)
Parameter | Optional | Description |
---|---|---|
start | Required. | where to start the selection of elements. The index numbers start at 0. a negative number will select elements from the end of the selected elements. |
stop | Optional. | where to end the selection of elements. If omitted, the selection continues until the end of the set. The index numbers start at 0. a negative number will select elements from the end of the selected elements. |