Categories
JavaScript Answers jQuery

How to Select All Elements But the First Element with the Given Selector with jQuery?

Spread the love

Sometimes, we want to select all elements but the first element with the given selector with jQuery.

In this article, we’ll look at how to select all elements but the first element with the given selector with jQuery.

Select All Elements But the First Element with the Given Selector with jQuery

To select all elements but the first element with the given selector with jQuery, we can call the slice method with 1 to return all the elements but the first one that’s selected.

For instance, if we have:

<div>
  foo
</div>
<div>
  bar
</div>
<div>
  baz
</div>

and we want to get all the divs but the first, we write:

const els = [...$('div').slice(1)];
console.log(els)

We call $('div') to select all the divs.

Then we call slice(1) to return all the selected divs except the first one.

Finally, we use the spread operator to spread the object with the selected elements into an array.

Therefore, els is an array with the 2nd and 3rd div according to the console log.

Conclusion

To select all elements but the first element with the given selector with jQuery, we can call the slice method with 1 to return all the elements but the first one that’s selected.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *