Skip to content

Instantly share code, notes, and snippets.

@ludder

ludder/classList.js

Created Dec 6, 2012
Embed
What would you like to do?
Backwards compatible classList functions
/**
* Check element has a certain classname
* We cannot use classList yet because of browser support
* @param {Object} ele DOM element
* @param {String} cls Classname
* @return {Boolean} True is classname is found
*/
function hasClass(ele,cls) {
if (ele === null || cls === '') return false;
return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
}
/**
* Remove class from element
* @param {Object} ele DOM element
* @param {String} cls Classname
*/
function removeClass(ele,cls) {
if (hasClass(ele,cls)) {
var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
ele.className=ele.className.replace(reg,' ');
}
}
/**
* Toggle classname
* @param {Object} elem DOM element
* @param {String} cl Classname to toggle
* @return {Object} Same DOM element with/without given classname
*/
function toggleClass(elem, cl) {
if (elem.className.indexOf(cl) != -1) {
elem.className = elem.className.replace(cl, '');
} else {
elem.className += ' ' + cl;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.