Web Tools Table Maker3schools TranslateImage CompressorFavicon Icon GeneratorCrop & Resize Image
Apu
Apu December 02, 2022 › #class #dynamically

Add class to all children except first child

In this article, I will talk about how to add a class name to all child elements except the first child.

So, for this you can use the :not() selector with the combination of :first-child pseudo class.

<style> 
 .element{color:red}
</style>
<ol>
  <li>One</li>
  <li>Two</li>
  <li>Three</li>
</ol>
<script>
 const liList = document.querySelectorAll('ol  li:not(:first-child)');
 
 liList.forEach((e)=>{
    e.classList.add('element')
  })
</script>
  1. In the above example, I have selected all li elements except the first using the querySelectorAll() method and stored in a variable liList as a NodeList.
  2. Then using the forEach() method, I add the class name element to all li elements.
save
listen
AI Answer
Write Your Answer
loading
back
View All