How to select elements and add class to them in JavaScript?

Sometimes, we want to select elements and add class to them in JavaScript.

In this article, we’ll look at how to select elements and add class to them in JavaScript.

How to select elements and add class to them in JavaScript?

To select elements and add class to them in JavaScript, we can use querySelectorAll and a for-of loop.

For instance, we write:

<ul>
  <li class="even"></li>
  <li class="odd"></li>
  <li class="even"></li>
</ul>

to add a list.

Then we select all the li’s and add a class to them by writing:

const list = document.querySelectorAll("li.even, li.odd");
for (const li of list) {
  li.classList.add('cf');
}

We select all the li’s with querySelectorAll.

And then we loop through them with a for-of loop.

In the loop, we call li.classList.add to add the 'cf' class to each li element.

Conclusion

To select elements and add class to them in JavaScript, we can use querySelectorAll and a for-of loop.