Check if an Element contains a class using TypeScript

avatar

Borislav Hadzhiev

Thu Mar 31 20222 min read

banner

Photo by Yarden

Check if an Element contains a class using TypeScript #

To check if an element contains a class in TypeScript:

  1. Select the specific element.
  2. Use the classList.contains() method to check if the element contains the class.
  3. The method returns true if the class is contained in the element's class list.

Here is the HTML for the examples in this article.

index.html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <style> .salmon { background-color: salmon; } </style> </head> <body> <div id="box" class="salmon">Hello world</div> <script src="./src/index.ts"></script> </body> </html>

And here is the related TypeScript code.

src/index.ts
const box = document.getElementById('box'); if (box?.classList.contains('salmon')) { console.log('Element contains class'); } else { console.log('Element does NOT contain class'); }

We used the document.getElementById method to select the element.

The method returns a null value if an element with the provided id does not exist in the DOM, so we had to use the optional chaining (?.) operator to make sure the box variable does not store a null value.

The optional chaining (?.) operator short-circuits if the reference is nullish (null or undefined).

The classList.contains method returns a boolean value - true if the class is contained in the element's class list and false otherwise.

We could have also used a simple if statement that serves as a type guard.

index.ts
const box = document.getElementById('box'); if (box != null) { if (box.classList.contains('salmon')) { console.log('Element contains class'); } else { console.log('Element does NOT contain class'); } }

We explicitly check that the box variable does not store a null value before accessing its classList property.

Once we enter the if block, TypeScript knows that the type of the box variable is HTMLElement, not HTMLElement | null.

If you need to add classes to an element or remove classes from an element, use the classList.add and classList.remove methods.

src/index.ts
const box = document.getElementById('box'); box?.classList.add('class-1', 'class-2'); box?.classList.remove('class-2', 'class-3');

He classList.add() method adds one or more classes to an element.

If the class is already present on the element, it won't get added twice.

On the other hand, the classList.remove() method can be used to remove one or more classes from an element.

If any of the classes is not present on the element, the remove() method ignores the class and does not throw an error.

Use the search field on my Home Page to filter through my more than 1,000 articles.