How can I add a class to a DOM element in JavaScript?
Solution 1:
new_row.className = "aClassName";
Here's more information on MDN: className
Solution 2:
Use the .classList.add()
method:
const element = document.querySelector('div.foo');
element.classList.add('bar');
console.log(element.className);
<div class="foo"></div>
This method is better than overwriting the className
property, because it doesn't remove other classes and doesn't add the class if the element already has it.
You can also toggle or remove classes using element.classList
(see the MDN documentation).