Created
January 27, 2014 10:08
-
-
Save jjmu15/8646098 to your computer and use it in GitHub Desktop.
has class function - vanilla JS. Check if element has specified class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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!"); | |
} |
What about element.classList.includes(classToFind)
?
You may need a polyfill for includes
or:
element.classList.indexOf(classToFind) !== -1
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
I think this would work best