Categories
JavaScript Answers

How to Select All Child Elements Except the First with JavaScript?

Spread the love

To select all child elements except the first with JavaScript, we can use jQuery with the not pseudo-selector to select all elements except the first element.

For instance, if we have the following HTML:

<ul>  
  <li>First item</li>  
  <li>Second item</li>  
  <li>Third item</li>  
</ul>

and we want to select the last 2 li elements, then we can write:

$("li:not(:first-child)").addClass("something");

to get all the li’s that isn’t the first child of the ul element with li:not(:first-child) .

Then we can call addClass on all the selected elements to add the 'something' class to it.

We can also use the gt pseudo-selector to do the same thing.

For instance, we can write:

$("li:gt(0)").addClass("something");

gt(0) means we select every li but the first child.

We can also use the not method to do the same selection with:

$("li").not(':first').addClass("something");

not(‘:first’) also excludes the first child.

Conclusion

To select all child elements except the first with JavaScript, we can use jQuery with the not pseudo-selector to select all elements except the first element.

By John Au-Yeung

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

Leave a Reply

Your email address will not be published.