How can I remove all elements except the first one using jQuery?

To remove all elements except the first one, use the remove() method with the slice() method in jQuery. The slice(1) method selects all elements starting from index 1 (the second element), leaving the first element untouched.

Example

You can try to run the following code to remove all elements except for first one using jQuery ?

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $(".button1").click(function(){
                $("span").remove();
            });
            
            $(".button2").click(function(){
                $('span').slice(1).remove();
            });
        });
    </script>
</head>
<body>
    <button class="button2">Remove all, except first element</button>
    <button class="button1">Remove all the elements</button>

    <span>
        <p>This is demo text - First span element.</p>
        <p>This is demo text.</p>
    </span>
    <span>
        <p>This is demo text - Second span element.</p>
        <p>This is demo text.</p>
    </span>
    <span>
        <p>This is demo text - Third span element.</p>
        <p>This is demo text.</p>
    </span>
</body>
</html>

In the above example ?

  • The $('span').slice(1).remove() selects all span elements starting from index 1 and removes them
  • The first button removes all elements except the first span
  • The second button removes all span elements for comparison

Conclusion

Using jQuery's slice(1).remove() method is an efficient way to remove all elements except the first one from a selected set. This technique works with any jQuery selector and preserves the first element while removing all subsequent ones.

Updated on: 2026-03-13T19:00:46+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements