how to check if an element has a class in javascript

To check if an element has a particular class in JavaScript, you can use the classList property of the element. The classList property is an object that represents the class attribute of an element. It has methods that allow you to add, remove or check if a class exists on the element.

You can use the contains() method of the classList property to check if an element has a specific class. Here's an example:

index.tsx
// get the element
const element = document.querySelector('#my-element');

// check if the element has the class 'my-class'
if (element.classList.contains('my-class')) {
  // do something if the element has the class
} else {
  // do something else if the element doesn't have the class
}
289 chars
10 lines

In the example above, we first get the element using querySelector(). Then, we use the classList.contains() method to check if the element has the class my-class. If the element has the class, we perform a certain action, otherwise, we do something else.

gistlibby LogSnag