jQuery | slice() with Examples

The slice() is an inbuilt method in jQuery which is used to select a subset of elements based on its index. The subset is a set that may be a part of a large set.
Syntax:

$(selector).slice(para1, para2)

Parameter: It accepts two parameters which are specified below-

  • para1: It specifies that where to start the selection of the elements.
  • para2: It is optional and it specifies where to stop the selection of the elements.

Return Value: It returns the subset of the selected element.

jQuery code to show the working of slice() method:

filter_none

edit
close

play_arrow

link
brightness_4
code

<html>
   
<head>
    <script 
    </script>
    <!-- jQuery code to show the working of this method -->
    <script>
        $(document).ready(function() {
            $("p").slice(1, 4).css("background-color", "lightgreen");
        });
    </script>
    <style>
        body {
            width: 500px;
            height: 200px;
            padding: 20px;
            border: 2px solid green;
        }
    </style>
</head>
   
<body>
   
    <h1>Welcome to GeeksforGeeks !</h1>
   
    <p>This is at index 0.</p>
    <p>This is at index 1.</p>
    <p>This is at index 2.</p>
    <p>Tnhis is at index 3.</p>
   
</body>
   
</html>

chevron_right


Output:
In this code, all paragraph element from index 1 to 3 get highlighted.



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.