Borislav Hadzhiev
Thu Mar 31 2022·2 min read
Photo by Nick Torontali
To add a class to the body element in TypeScript, call the classList.add()
method on the body object, e.g. document.body.classList.add('my-class')
. The
add()
method adds one or more classes to the list, omitting any that are
already present.
Here is the HTML for the examples in this article.
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <style> .salmon { background-color: salmon; } </style> </head> <body> <div>Hello world</div> <script src="./src/index.ts"></script> </body> </html>
And here is the related TypeScript code.
// ✅ Add class to body element document.body.classList.add('salmon'); // ✅ Remove class from body element // document.body.classList.remove('salmon');
We used the classList.add() method to add a class on the body object.
We can access the body element on the document
object.
body
element, it won't get added twice.You can pass as many classes to the add()
method as necessary.
// ✅ Add class to body element document.body.classList.add( 'salmon', 'second-class', 'third-class' ); // ✅ Remove class from body element // document.body.classList.remove('salmon');
Similarly, if you need to remove one or more classes, you can use the remove()
method.
// ✅ Add class to body element document.body.classList.add( 'salmon', 'second-class', 'third-class' ); // ✅ Remove class from body element document.body.classList.remove( 'salmon', '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.
You might have seen examples online that reassign the className
property on
the body element.
document.body.className += 'salmon';
This approach works, however when using it we don't take advantage of some of
the built in functionality the classList.add()
method provides.
document.body.className += 'salmon'; document.body.className += 'salmon';
This would lead to very confusing behavior if you have to toggle a class or remove it.
You can also add a class to the body element when an event occurs, e.g. a button is clicked.
Here is the HTML for the next example.
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <style> .salmon { background-color: salmon; } </style> </head> <body> <div>Hello world</div> <button id="btn">Click me</button> <script src="./src/index.ts"></script> </body> </html>
And here is the related JavaScript code.
const btn = document.getElementById('btn'); btn?.addEventListener('click', function onClick() { if (document.body.classList.contains('salmon')) { document.body.classList.remove('salmon'); } else { document.body.classList.add('salmon'); } });
We added a click
event listener to the button element.
Each time the button is clicked the onClick
function is invoked.
Our if
condition checks whether the salmon
class is contained on the body
element and removes it if it is, otherwise the class is added to the body
element.