Borislav Hadzhiev
Thu Mar 31 2022·2 min read
Photo by Yarden
To check if an element contains a class in TypeScript:
classList.contains()
method to check if the element contains the
class.true
if the class is contained in the element's class
list.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 id="box" class="salmon">Hello world</div> <script src="./src/index.ts"></script> </body> </html>
And here is the related TypeScript code.
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.
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.
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.
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.
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.
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.