Skip to content

Instantly share code, notes, and snippets.

@stephanie-walter
Created June 10, 2013 13:00
Show Gist options
  • Save stephanie-walter/5748524 to your computer and use it in GitHub Desktop.
Save stephanie-walter/5748524 to your computer and use it in GitHub Desktop.
Toggle class in Raw JS that works with document.getElementsByClassName
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