How can I add a class to a DOM element in JavaScript?

This answer was written/accepted a long time ago. Since then better, more comprehensive answers with examples have been submitted. You can find them by scrolling down. Below is the original accepted answer preserved for posterity.


new_row.className = "aClassName";

Here's more information on MDN: className


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).

Tags:

Javascript

Dom