Site Admin
Site Admin Founder of MeaningArticles
1015 Views

Javascript Check If Element Contains Class Name

Hello Dev.

Javascript is the most essential language all time and we're the use of the js for fronend as well, Now a days more then javascript framworks are to be had for smooth develping the websites however the essential factor javascript never die due to the fact the framworks are buid from javascript. So javascript work a great manner to clean and velocity operating code. in case you search test if an detail includes a category in div you then are touchdown a great vicinity. right here we're describe you how to select the div that have the magnificence name. right here we are using simple JavaScript no longer jQuery, for clean way to check if an detail contains a class. let see the quality examples right 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:

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

i'm hoping it assist you to, thanks for visit my article if you like my article then proportion together with your friend and social platform.