19

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

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Adam Halasz
  • 57,421
  • 66
  • 149
  • 213
  • You can use some regex for the complete class name. For the regex you can refer to this http://stackoverflow.com/questions/2232934/whole-word-match-in-javascript – nandu Jun 09 '12 at 11:27
  • 1
    possible duplicate of [Test if an element contains a class?](http://stackoverflow.com/questions/5898656/test-if-an-element-contains-a-class) -- please use the search before you ask a new question. – Felix Kling Jun 09 '12 at 11:35

6 Answers6

38
function hasClass( elem, klass ) {
     return (" " + elem.className + " " ).indexOf( " "+klass+" " ) > -1;
}
Esailija
  • 138,174
  • 23
  • 272
  • 326
  • 3
    Pretty sure jQuery's version normalizes the space separators in the `.className` value first. This could fail if a tab or some other space character was used to separate the classes. – the system Mar 04 '13 at 18:06
26

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.

ZER0
  • 24,846
  • 5
  • 51
  • 54
1

this 2018 use ES6

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

How to use

hasClass(document.querySelector('div.active'), 'active'); // true
Gor
  • 1,385
  • 12
  • 7
0

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.

Steve
  • 2,207
  • 6
  • 24
  • 35
  • 1
    Did you, by any chance, copied this from jQuery? what does `this` refer to? where is `rclass` defined? – Salman A Jun 09 '12 at 11:29
  • I mention in my comment quite clearly that yes, it comes from jQuery. You raise a good point about rclass, I didn't notice it, I'll update the answer – Steve Jun 09 '12 at 11:43
0

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.

Endre Simo
  • 11,330
  • 2
  • 40
  • 49
-1

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