- Instant help with your JavaScript coding problems

Add class to element if it does not already exists with JavaScript

Question:
How to add class to element if it does not already exists with JavaScript?
Answer:
const element = document.getElementById('my-element-id');
element.classList.add('new-class');
Description:

If you want to add a CSS class to an existing HTML element, but only if it doesn't already exist, you can, fortunately, do this easily using vanilla JavaScript.

To be honest, you don't need any extra code for this, because the add method of the classList property already works like this. The official definition is:

The add() method of the DOMTokenList interface adds the given tokens to the list, omitting any that are already present.

Reference:
DOMTokenList.add
The add() method of the DOMTokenList interface adds the given tokens to the list, omitting any that are already present.
JavaScript:
add(token0);
TypeScript:
add(...tokens: string[]): void;
Examples:
myElement.classList.add("my-class-1", "my-class-2");
Share "How to add class to element if it does not already exists with JavaScript?"