Skip to content

Instantly share code, notes, and snippets.

@jjmu15
Created January 27, 2014 10:08
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save jjmu15/8646098 to your computer and use it in GitHub Desktop.
Save jjmu15/8646098 to your computer and use it in GitHub Desktop.
has class function - vanilla JS. Check if element has specified class
// hasClass, takes two params: element and classname
function hasClass(el, cls) {
return el.className && new RegExp("(\\s|^)" + cls + "(\\s|$)").test(el.className);
}
/* use like below */
// Check if an element has class "foo"
if (hasClass(element, "foo")) {
// Show an alert message if it does
alert("Element has the class!");
}
@andfinally
Copy link

Thanks, just what I wanted!

@Billy-
Copy link

Billy- commented Nov 27, 2014

Using regex is a bit performance heavy for this simple task, which may easily end up being used many times in loops! What's wrong with return el.className.indexOf(cls) != -1;?

@ignacioiglesias
Copy link

Billy, I think that wouldn't work on <span class="foo-baz foo-bar">…</span> when cls is foo

@kellyjoe256
Copy link

I think this would work best

if (!el.className) {
    return false;
} else {
    var newElementClass = ' ' + el.className + ' ';
    var newClassName = ' ' + cls + ' ';
    return newElementClass.indexOf(newClassName) !== -1;
}

@FezVrasta
Copy link

FezVrasta commented Jul 15, 2016

What about element.classList.includes(classToFind)?

You may need a polyfill for includes or:

element.classList.indexOf(classToFind) !== -1

@andfinally
Copy link

Fez, I think that should be element.className.includes(classToFind) and you'd have to polyfill for IE. The second suggestion looks simpler, if you're not worried about the issue @ignacioiglesias mentioned.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment