Explain Codes LogoExplain Codes Logo

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

javascript
classlist
dom-manipulation
best-practices
Anton ShumikhinbyAnton Shumikhin·Aug 9, 2024
TLDR

To add a class, you can utilize the .classList.add() method on your chosen DOM element. Have a look at the example below:

document.getElementById('id').classList.add('newClass');

Here, you need to replace 'id' with the ID of the element you want to target and 'newClass' with the class you want to add. Just remember, .classList is your best bet if you're dealing with multiple classes and don't want to overwrite the existing ones.

The pipeline of class manipulation

Adding, removing or toggling classes on DOM elements is as easy as attending a JavaScript conference, once you understand the concept properly.

The power of .classList

The .classList property comes with handy methods that makes manipulation a lot easier:

  • .add('className'): Like adding another Star Wars sequel to the franchise.
  • .remove('className'): Like erasing Jar Jar Binks from the Star Wars universe.
  • .toggle('className'): The Darth Vader of the group, it can switch sides depending on the situation.
  • .contains('className'): Checks if a particular Star Wars episode exists or not.

Dealing with pre-existing classes

Setting the className property of an element directly is akin to erasing the original Star Wars trilogy and pasting the prequels instead. It overwrites all existing classes:

element.className = 'newClass'; // Who needs the old trilogy when you can have Jar Jar, right?

Inserting in the DOM

Once you've crafted an element using document.createElement(), you still need to place it in the DOM:

let parentElement = document.getElementById('parentId'); parentElement.appendChild(newElement);

Just remember to add some content to your newly created element with Jeremy Clarkson's favorite punchline:

newElement.innerHTML = "Some say he isn't machine washable, and all his potted plants are called Steve...";

Enhancing reusability with functions

Creating a function to add classes – not only is it a programming best practice, but it's like ensuring all elements wear their seat belts while driving:

function addClass(elementId, className) { let element = document.getElementById(elementId); element.classList.add(className); }

Keep your classes intact

When using className for class assignment, one needs to remember: the old saying that with great power comes great responsibility holds true here. Improper usage can lead to existing classes being overwritten.

class attribute vs classList

Setting classes directly using the class attribute is tempting. However, classList provides a dynamic, flexible, and error-free way to manipulate classes.

Picking elements

When in doubt, go with document.querySelector() or document.getElementById(). They are like your personal GPS to navigate through the elements in your DOM.