简体   繁体   中英

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 particular class in the element's className property.

Example

// element's classname is 'hello world helloworld'
var element = document.getElementById('element');

// this obviously fails
if(element.className == 'hello'){ ... }

// this is not good if the className is just 'helloworld' because it will match
if(element.className.indexOf('hello') != -1){ ... }  

So what would be the best way to do this?

just pure javascript please

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

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.

this 2018 use ES6

const hasClass = (el, className) => el.classList.contains(className);

How to use

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

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 ) {
                return true;
            }
        }
        return false;
    },

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.

This should work for you:

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

    var re = new RegExp('\\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.

First, split the className by using the " " character, then check the index of the class you want to find.

function hasClass(element, clazz) {
    return element.className.split(" ").indexOf(clazz) > -1;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM