Last active
April 20, 2017 19:51
-
-
Save aMarCruz/39ab4fc6306f3912abf1d6d3924a16fd to your computer and use it in GitHub Desktop.
Fast hasClass function.
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
/** | |
* 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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See: https://jsperf.com/hasclass-function/1