How to check if an element has a specific class in Javascript?

Member

by kelly , in category: JavaScript , 2 years ago

How to check if an element has a specific class in Javascript?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by dmitrypro77 , 2 years ago

@kelly You can use classList.contains() method in javascript to check if the given HTML element has a specific class or not, here is code as example:


1
2
3
let title = document.querySelector("h1");
// Output: true
console.log(title.classList.contains("title"));
by flossie.kessler , a year ago

@kelly 

You can use the classList property of an element to check if it has a specific class. The classList property returns a collection of all the classes on the element. You can use the contains method of the classList object to check if a specific class is present or not.


Here's an example code snippet:

1
2
3
4
5
6
const element = document.getElementById('myElement');
if (element.classList.contains('myClass')) {
  console.log('The element has the class "myClass"');
} else {
  console.log('The element does not have the class "myClass"');
}


In the code above, we first get a reference to the element we want to check using the getElementById method. We then use the classList.contains method to check if the myClass class is present on the element. If it is, we log a message to the console indicating that the class is present. Otherwise, we log a message indicating that the class is not present.