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 the h1 contains the class name main.
HTML
<!DOCTYPE html><html> <body> <h1 id="main" class="main">Welcome To GFG</h1></body> </html> |
- 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.
Javascript
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");} |
Complete code:
HTML
<!DOCTYPE html><html> <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:



.png)