How to check if DOM element contains CSS class using JavaScript
Overview
We can use the classList property of the DOM element to check if the element contains a specific class.
Note: The
classListproperty contains the live collection of classes present in the DOM element.
Example
Explanation
In the HTML tab:
- We create a
divwithid=contentandclass=red.
In JavaScript tab:
-
Line 1: We use the
getElementByIdto get the element withcontentand store it in theelementvariable. -
Line 3: We access the
classListproperty of theelementand store it in a variable. -
Line 5: We use the
containsmethod of theclassListproperty to check if theelementhasredclass. In our case, theredclass is present, sotrueis returned. -
Line 8: We use the
containsmethod of theclassListproperty to check if theelementhasblueclass. In our case, theblueclass is not present, sofalseis returned. -
Line 11: We print the
classListvariable. This will print all the classes present in theelement.