Skip to content

Instantly share code, notes, and snippets.

@aMarCruz

aMarCruz/hasclass.js

Last active Apr 20, 2017
Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

@aMarCruz aMarCruz commented Apr 20, 2017

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