Categories
JavaScript Answers

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

Spread the love

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.

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 *