Skip to content

Instantly share code, notes, and snippets.

@aMarCruz
Last active April 20, 2017 19:51
Show Gist options
  • Save aMarCruz/39ab4fc6306f3912abf1d6d3924a16fd to your computer and use it in GitHub Desktop.
Save aMarCruz/39ab4fc6306f3912abf1d6d3924a16fd to your computer and use it in GitHub Desktop.
Fast hasClass function.
/**
* Detect is an element contains a class name.
*
* @param {Element} el - HTML element
* @param {string} name - Class name
* @returns {boolean} `true` if the element contains the class name.
*/
function hasClass(el, name) {
let classes = name && el && el.className
if (classes) {
if (typeof s != 'string') {
s = el.getAttribute('class') || '' // may be SVG
}
for (let n = 0; ~(n = classes.indexOf(name, n)); n++) {
if (!n || /\s/.test(classes[n - 1])) {
n += name.length
if (n === classes.length || /\s/.test(classes[n])) {
return true
}
}
}
}
return false
}
@aMarCruz
Copy link
Author

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