Created
June 10, 2013 13:00
-
-
Save stephanie-walter/5748524 to your computer and use it in GitHub Desktop.
Toggle class in Raw JS that works with document.getElementsByClassName
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
var changeClass = function (r,className1,className2) { | |
var regex = new RegExp("(?:^|\\s+)" + className1 + "(?:\\s+|$)"); | |
if( regex.test(r.className) ) { | |
r.className = r.className.replace(regex,' '+className2+' '); | |
}else{ | |
r.className = r.className.replace(new RegExp("(?:^|\\s+)" + className2 + "(?:\\s+|$)"),' '+className1+' '); | |
} | |
return r.className; | |
}; | |
var elementTest = document.getElementsByClassName('test'); | |
for (var i=0;i<elementTest.length;i++){ | |
elementTest[i].addEventListener('click',function(e){ | |
changeClass(this,'alert','success'); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment