How to get all elements by class name and the change class name for each with JavaScript?

Sometimes, we want to get all elements by class name and the change class name for each with JavaScript.

In this article, we’ll look at how to get all elements by class name and the change class name for each with JavaScript.

How to get all elements by class name and the change class name for each with JavaScript?

To get all elements by class name and the change class name for each with JavaScript, we can select them all with document.querySelectorAll.

Then we spread the selected elements into an array with the spread operator and use the for-of loop to loop through them and change the class name for each element.

For instance, we write:

<div class='foo'>
  foo
</div>
<div class='foo'>
  foo
</div>
<div class='foo'>
  foo
</div>

to add 3 elements with class foo.

Then we write:

const els = document.querySelectorAll('.foo')
for (const el of [...els]) {
  el.className = "bar";
}

We select all the elements with:

const els = document.querySelectorAll('.foo')

Then we spread els into an array and loop through them with a for-of loop.

And in the body, we set el.className to 'bar' to change the class of each to bar.

Conclusion

To get all elements by class name and the change class name for each with JavaScript, we can select them all with document.querySelectorAll.

Then we spread the selected elements into an array with the spread operator and use the for-of loop to loop through them and change the class name for each element.