Add a class to an Element using TypeScript

avatar

Borislav Hadzhiev

Thu Mar 31 20222 min read

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.

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