Add a class to an Element using TypeScript

avatar

Borislav Hadzhiev

Last updated: Mar 31, 2022

banner

Photo from Unsplash

Add a class to an Element using TypeScript #

To add a class to an element in TypeScript:

  1. Select the element.
  2. Use the classList.add() method to add a class to the element.
  3. The method adds the provided class to the element if it isn't already present.

Here is the HTML for the examples in this article.

index.html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <style> .bg-yellow { background-color: yellow; } </style> </head> <body> <div id="box">Box 1</div> <script src="./src/index.ts"></script> </body> </html>

And here is the related TypeScript code.

src/index.ts
// 👇️ const box: HTMLElement | null const box = document.getElementById('box'); if (box != null) { // ✅ Add class box.classList.add('bg-yellow'); // ✅ Remove class // box.classList.remove('bg-yellow'); }

The document.getElementById method returns null if an element with the provided id does not exist in the DOM, so we make sure the box variable doesn't store a null value.

We used the classList.add() method to add a class to the element.

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

You can pass as many classes to the add() method as necessary.

src/index.ts
// 👇️ const box: HTMLElement | null const box = document.getElementById('box'); if (box != null) { // ✅ Add class box.classList.add( 'bg-yellow', 'second-class', 'third-class' ); // ✅ Remove class // box.classList.remove('bg-yellow'); }

Similarly, if you need to remove one or more classes, you can use the remove() method.

src/index.ts
// 👇️ const box: HTMLElement | null const box = document.getElementById('box'); if (box != null) { // ✅ Add class // box.classList.add('bg-yellow', 'second-class', 'third-class'); // ✅ Remove class box.classList.remove('bg-yellow'); }

We then used the classList.remove method to remove the bg-yellow class from the div element.

You can also pass as many classes to the remove() method as necessary.

src/index.ts
// 👇️ const box: HTMLElement | null const box = document.getElementById('box'); if (box != null) { // ✅ Add class // box.classList.add('bg-yellow', 'second-class', 'third-class'); // ✅ Remove class box.classList.remove( 'bg-yellow', 'second-class', 'third-class' ); }

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

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.