Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

dom
css
javascript
contains css

How to check if DOM element contains CSS class using JavaScript

Programming Bytes

Overview

We can use the classList property of the DOM element to check if the element contains a specific class.

Note: The classList property contains the live collection of classes present in the DOM element.

Example

Console
Check if the DOM element contains a class

Explanation

In the HTML tab:

  • We create a div with id=content and class=red.

In JavaScript tab:

  • Line 1: We use the getElementById to get the element with content and store it in the element variable.

  • Line 3: We access the classList property of the element and store it in a variable.

  • Line 5: We use the contains method of the classList property to check if the element has red class. In our case, the red class is present, so true is returned.

  • Line 8: We use the contains method of the classList property to check if the element has blue class. In our case, the blue class is not present, so false is returned.

  • Line 11: We print the classList variable. This will print all the classes present in the element.

RELATED TAGS

dom
css
javascript
contains css
RELATED COURSES

View all Courses

Keep Exploring