To check if an element has a specific class in JavaScript, you can use the classList
property of the element and call the contains()
method on it.
This method takes the class name as a parameter and returns true
if the element has the class, and false
if it does not.
Here is an example:
const element = document.querySelector('#some-element');
if (element.classList.contains('some-class')) {
// Do something if the element has the class
} else {
// Do something else if the element does not have the class
}
Code language: JavaScript (javascript)
Note that the classList
property is not supported in Internet Explorer 9 and earlier versions. But hopefully you aren’t supporting those browsers anymore!
Example
Let’s say we have a button on our page with the ID toggle-button
` that we want to use to toggle a class on another element.
When the button is clicked, we want to check if the element has the class active
. If it does, we want to remove the class, and if it doesn’t, we want to add the class.
const button = document.querySelector('#toggle-button');
const element = document.querySelector('#some-element');
button.addEventListener('click', () => {
if (element.classList.contains('active')) {
element.classList.remove('active');
} else {
element.classList.add('active');
}
});
Code language: JavaScript (javascript)
In this example, we use the classList
property and the contains()
method to check if the element
has the active
class. Depending on the result of the check, we either remove the class or add it to the element.
This is a simple example, but it illustrates how you can use this approach in a real-world scenario.
Leave a Reply