What is the "hasClass" function with plain JavaScript?

JavascriptDom

Javascript Problem Overview


How do you do jQuery’s hasClass with plain ol’ JavaScript? For example,

<body class="foo thatClass bar">

What’s the JavaScript way to ask if <body> has thatClass?

Javascript Solutions


Solution 1 - Javascript

Simply use classList.contains():

if (document.body.classList.contains('thatClass')) {
    // do some stuff
}

Other uses of classList:

document.body.classList.add('thisClass');
// $('body').addClass('thisClass');

document.body.classList.remove('thatClass');
// $('body').removeClass('thatClass');

document.body.classList.toggle('anotherClass');
// $('body').toggleClass('anotherClass');

Browser Support:

  • Chrome 8.0
  • Firefox 3.6
  • IE 10
  • Opera 11.50
  • Safari 5.1

classList Browser Support

Solution 2 - Javascript

You can check whether element.className matches /\bthatClass\b/.
\b matches a word break.

Or, you can use jQuery's own implementation:

var className = " " + selector + " ";
if ( (" " + element.className + " ").replace(/[\n\t]/g, " ").indexOf(" thatClass ") > -1 ) 

To answer your more general question, you can look at jQuery's source code on github or at the source for hasClass specifically in this source viewer.

Solution 3 - Javascript

The most effective one liner that

  • returns a boolean (as opposed to Orbling's answer)
  • Does not return a false positive when searching for thisClass on an element that has class="thisClass-suffix".
  • is compatible with every browser down to at least IE6

function hasClass( target, className ) {
	return new RegExp('(\\s|^)' + className + '(\\s|$)').test(target.className);
}

Solution 4 - Javascript

// 1. Use if for see that classes:

if (document.querySelector(".section-name").classList.contains("section-filter")) {
  alert("Grid section");
  // code...
}

<!--2. Add a class in the .html:-->

<div class="section-name section-filter">...</div>

Solution 5 - Javascript

The attribute that stores the classes in use is className.

So you can say:

if (document.body.className.match(/\bmyclass\b/)) {
    ....
}

If you want a location that shows you how jQuery does everything, I would suggest:

http://code.jquery.com/jquery-1.5.js

Solution 6 - Javascript

Element.matches()

Instead of $(element).hasClass('example') in jQuery, you can use element.matches('.example') in plain JavaScript:

if (element.matches('.example')) {
  // Element has example class ...
}

View Browser Compatibility

Solution 7 - Javascript

hasClass function:

HTMLElement.prototype.hasClass = function(cls) {
    var i;
    var classes = this.className.split(" ");
    for(i = 0; i < classes.length; i++) {
        if(classes[i] == cls) {
            return true;
        }
    }
    return false;
};

addClass function:

HTMLElement.prototype.addClass = function(add) {
    if (!this.hasClass(add)){
        this.className = (this.className + " " + add).trim();
    }
};

removeClass function:

HTMLElement.prototype.removeClass = function(remove) {
    var newClassName = "";
    var i;
    var classes = this.className.replace(/\s{2,}/g, ' ').split(" ");
    for(i = 0; i < classes.length; i++) {
        if(classes[i] !== remove) {
            newClassName += classes[i] + " ";
        }
    }
    this.className = newClassName.trim();
};

Solution 8 - Javascript

I use a simple/minimal solution, one line, cross browser, and works with legacy browsers as well:

/\bmyClass/.test(document.body.className) // notice the \b command for whole word 'myClass'

This method is great because does not require polyfills and if you use them for classList it's much better in terms of performance. At least for me.

Update: I made a tiny polyfill that's an all round solution I use now:

function hasClass(element,testClass){
  if ('classList' in element) { return element.classList.contains(testClass);
} else { return new Regexp(testClass).exec(element.className); } // this is better

//} else { return el.className.indexOf(testClass) != -1; } // this is faster but requires indexOf() polyfill
  return false;
}

For the other class manipulation, see the complete file here.

Solution 9 - Javascript

a good solution for this is to work with classList and contains.

i did it like this:

... for ( var i = 0; i < container.length; i++ ) {
		if ( container[i].classList.contains('half_width') ) { ...

So you need your element and check the list of the classes. If one of the classes is the same as the one you search for it will return true if not it will return false!

Solution 10 - Javascript

Use something like:

Array.prototype.indexOf.call(myHTMLSelector.classList, 'the-class');

Solution 11 - Javascript

if (document.body.className.split(/\s+/).indexOf("thatClass") !== -1) {
    // has "thatClass"
}

Solution 12 - Javascript

This 'hasClass' function works in IE8+, FireFox and Chrome:

hasClass = function(el, cls) {
    var regexp = new RegExp('(\\s|^)' + cls + '(\\s|$)'),
        target = (typeof el.className === 'undefined') ? window.event.srcElement : el;
    return target.className.match(regexp);
}

[Updated Jan'2021] A better way:

hasClass = (el, cls) => {
  [...el.classList].includes(cls); //cls without dot
};

Solution 13 - Javascript

Well all of the above answers are pretty good but here is a small simple function I whipped up. It works pretty well.

function hasClass(el, cn){
    var classes = el.classList;
    for(var j = 0; j < classes.length; j++){
        if(classes[j] == cn){
            return true;
        }
    }
}

Solution 14 - Javascript

What do you think about this approach?

<body class="thatClass anotherClass"> </body>

var bodyClasses = document.querySelector('body').className;
var myClass = new RegExp("thatClass");
var trueOrFalse = myClass.test( bodyClasses );

https://jsfiddle.net/5sv30bhe/

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKyle CureauView Question on Stackoverflow
Solution 1 - JavascriptDamienView Answer on Stackoverflow
Solution 2 - JavascriptSLaksView Answer on Stackoverflow
Solution 3 - JavascriptraverenView Answer on Stackoverflow
Solution 4 - Javascriptaz-stiveView Answer on Stackoverflow
Solution 5 - JavascriptOrblingView Answer on Stackoverflow
Solution 6 - JavascriptGrant MillerView Answer on Stackoverflow
Solution 7 - JavascriptGawinView Answer on Stackoverflow
Solution 8 - JavascriptthednpView Answer on Stackoverflow
Solution 9 - JavascriptBastian FießingerView Answer on Stackoverflow
Solution 10 - JavascriptAlejandro NanezView Answer on Stackoverflow
Solution 11 - JavascriptAlexandr KarbivnichiyView Answer on Stackoverflow
Solution 12 - JavascriptmanufoselaView Answer on Stackoverflow
Solution 13 - Javascriptj0hnstewView Answer on Stackoverflow
Solution 14 - JavascriptMarian07View Answer on Stackoverflow