Skip to content

Instantly share code, notes, and snippets.

@jamielovelace
Created May 13, 2014 10:32
Show Gist options
  • Save jamielovelace/4f630f1195c274b9df3d to your computer and use it in GitHub Desktop.
Save jamielovelace/4f630f1195c274b9df3d to your computer and use it in GitHub Desktop.
Vanilla JS - Add Class / Remove Class / Has Class
function hasClass(ele,cls) {
return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
}
function addClass(ele,cls) {
if (!hasClass(ele,cls)) ele.className += " "+cls;
}
function removeClass(ele,cls) {
if (hasClass(ele,cls)) {
var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
ele.className=ele.className.replace(reg,' ');
}
}
// Example
var myElement = document.getElementById('foo');
addClass(myElement, 'foo-class');
removeClass(myElement, 'foo-class');
if (hasClass(myElement, 'foo-class')) {
return true;
} else {
return false
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment