Open In App

How to check the given element has the specified class in JavaScript ?

Sometimes we need to check the element has the class name ‘X’ ( Any specific name ). To check if the element contains a specific class name, we can use the contains method of the classList object.

Syntax:

element.classList.contains("class-name");

It returns a Boolean value. If the element contains the class name it returns true otherwise it returns false.



Approach

Example: In this example, we will implement the above approach.




<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,
    initial-scale=1.0">
    <title>Document</title>
</head>
 
<body>
    <h1 id="main" class="main">Welcome To GFG</h1>
 
    <script>
        let elem = document.getElementById("main");
 
        let isMainPresent = elem.classList.contains("main");
 
        if (isMainPresent) {
            console.log("Found the class name");
        } else {
            console.log("Not found the class name");
        }
 
        let isMyclassPresent =
            elem.classList.contains("myClass")
 
        if (isMyclassPresent) {
            console.log("Found the class name");
        } else {
            console.log("Not found the class name");
        }
    </script>
</body>
 
</html>

Output:




Article Tags :