Last updated: Feb 29, 2024
Reading timeยท2 min
To add a class to an element in TypeScript:
classList.add()
method to add a class to the element.Here is the HTML for the examples.
<!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.
// ๐๏ธ 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
doesn't 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.
You can pass as many classes to the add()
method as necessary.
// ๐๏ธ 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'); }
I've also written an article on how to add CSS styles to an element.
Similarly, if you need to remove one or more classes, you can use the remove()
method.
// ๐๏ธ 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.
// ๐๏ธ 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 aren't present on the element they get ignored by the
remove()
method and no error is raised.
If you need to show/hide an element in TypeScript, check out the following article.
You can learn more about the related topics by checking out the following tutorials: