In this tutorial we show you Javascript Check If Element Contains a Class Name Example. Javascript is the most important language all time and we are using the js for fronend as well, Now a days more then javascript framworks are available for easy develping the websites but the major point javascribe never die because the framworks are buid from javascript.
Here we have adde 2 examples to check if an element contains a class in div or other element. We have used pure JavaScript not jQuery, for easy way to check if an element contains a class. let see the best examples here.
Example 1: using ID
We can check the element contains class two or multiple ways, First we are using giving id the existing div where we want to check if class name is contains or not.
<div class="test-class" id="testId">Item</div>
The above div have id testId and we check the test-class exits or not in this div.. lets see how
const element= document.getElementById('testId');
element.classList.contains('test-class'); // true
Here we get the element using to getElementById methods of javascript then we use classList contains methods of javascript for contains class name.
Example 2: using Class Name
We can use the class for same as above… here we have added a second-class class name here.
<div class="secondary second-class">Item</div>
Now we use the querySelector for getting the targeted class using the class name and then we check is the div is contains the class name. Let see…
const targetEle = document.querySelector('.second-class');
targetEle.classList.contains('second-class'); // true
Next:
Alternatively, if you work with older browsers and don’t want to use polyfills to fix them, using indexOf is correct, but you have to tweak it a little:
Alternatively, if you work with older browsers and don’t want to use polyfills to fix them, using indexOf is correct, but you have to tweak it a little:
function hasClass(element, className) {
return (' ' + element.className + ' ').indexOf(' ' + className+ ' ') > -1;
}
If you are using the loop then how you can get the class name contain div.
As this does not work together with the switch statement, you could achieve the same effect with this code:
let test = document.getElementById("test"),
classes = ['class1', 'class2', 'class3', 'class4'];
test.innerHTML = "";
for(var i = 0, j = classes.length; i < j; i++) {
if(hasClass(test, classes[i])) {
test.innerHTML = "I have " + classes[i];
break;
}
}
1 thought on “Javascript Check If Element Contains Class Name Example”