Skip to content Skip to sidebar Skip to footer

What Is The Best Way To Check If Element Has A Class?

The problem If the element has multiple classes then it will not match with the regular property value checking, so I'm looking for the best way to check if the object has a partic

Solution 1:

functionhasClass( elem, klass ) {
     return (" " + elem.className + " " ).indexOf( " "+klass+" " ) > -1;
}

Solution 2:

In modern browsers, you can use classList:

if (element.classList.contains("hello")) {
   //do something
}  

In the browser that doesn't implement classList but exposes the DOM's prototype, you can use the shim showed in the link.

Otherwise, you can use the same shim's code to have a generic function without manipulate the prototype.

Solution 3:

this 2018 use ES6

consthasClass = (el, className) => el.classList.contains(className);

How to use

hasClass(document.querySelector('div.active'), 'active'); // true

Solution 4:

You ask for pure javascript, so this is how jQuery implement it:

    hasClass: function( selector ) {
        var className = " " + selector + " ",
            i = 0,
            l = this.length;
        for ( ; i < l; i++ ) {
            if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) {
                returntrue;
            }
        }
        returnfalse;
    },

rclass is a regular expression of [\n\t\r], to ensure that alternative methods of delimiting class names are not an issue. this would be jQuery's reference to the object(s) and in a sense it makes the code more complicated than required, but it should make sense without knowing the details of it.

Solution 5:

This should work for you:

var a = [];
functiongetElementsByClassName(classname, node)  {
    if(!node) node = document.getElementsByTagName("body")[0];

    var re = newRegExp('\\b' + classname + '\\b');
    var els = node.getElementsByTagName("*");
    for(var i=0, j=els.length; i<j; i++)
        if(re.test(els[i].className)) a.push(els[i]);
        return a;
}

getElementsByClassName('wrapper');
for (var i=0; i< a.length; i++) {
    console.log(a[i].className);
}

This code will traverse the DOM and search for classes defined as parameter in the main function.Then it will test each founded class elements with a regexp pattern. If it founds will push to an array, and will output the results.

Post a Comment for "What Is The Best Way To Check If Element Has A Class?"