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
- 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 a document.getElementById( ).
- Now check if the element has the class name main and also check if the class name myClass is present or not.
Example: In this example, we will implement the above approach.
HTML
<!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: