Created
May 13, 2014 10:32
-
-
Save jamielovelace/4f630f1195c274b9df3d to your computer and use it in GitHub Desktop.
Vanilla JS - Add Class / Remove Class / Has Class
This file contains hidden or 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
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