Sometimes, we want to use setAttribute
to set multiple classes on an element with JavaScript.
In this article, we’ll look at how to use setAttribute
to set multiple classes on an element with JavaScript.
How to use setAttribute to set multiple classes on an element with JavaScript?
To use setAttribute
to set multiple classes on an element with JavaScript, we can call setAttribute
with all the class names separated by a space each.
For instance, we write:
<div>
</div>
to add a div.
Then we write:
const element = document.querySelector('div')
element.setAttribute("class", "class1 class2");
to select the div with querySelector
.
Then we call setAttribute
with 'class'
and 'class1 class2'
to set the class attribute of the div to class1 class2
.
Conclusion
To use setAttribute
to set multiple classes on an element with JavaScript, we can call setAttribute
with all the class names separated by a space each.