Categories
JavaScript Answers

How to check if an element contains a class in JavaScript?

Spread the love

Sometimes, we want to check if an element contains a class in JavaScript.

In this article, we’ll look at how to check if an element contains a class in JavaScript.

How to check if an element contains a class in JavaScript?

To check if an element contains a class in JavaScript, we use the classList.contains method.

For instance, we write

const hasClass = element.classList.contains("class");

to call element.classList.contains with 'class' to check if element has the class class.

It’ll return true if it’s added and false otherwise.

Conclusion

To check if an element contains a class in JavaScript, we use the classList.contains method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *