Thursday, September 4, 2025
HomeLanguagesJavascriptHow to check the given element has the specified class in JavaScript...

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.

Implementation: Now let’s implement the given method. 

  • Here we will create a simple HTML page and add an h1 element having the class name main and id name main. Our task is to find that h1 contains the class name main.
  • Now create a script tag and write the javascript code. Create a variable named elem and store the h1 element by using document.getElementById( )
  • Now check if the element has the class name main and also checking if the class name myClass present or not.

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

HTML




<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>


Output:

Found the class name
Not found the class name
Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32264 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6629 POSTS0 COMMENTS
Nicole Veronica
11799 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11859 POSTS0 COMMENTS
Shaida Kate Naidoo
6749 POSTS0 COMMENTS
Ted Musemwa
7025 POSTS0 COMMENTS
Thapelo Manthata
6698 POSTS0 COMMENTS
Umr Jansen
6718 POSTS0 COMMENTS