Last active
January 31, 2017 22:20
-
-
Save srdjan-m/5b7fd68c5b80a8c8a72c77ae3dfa43ec to your computer and use it in GitHub Desktop.
javascript: add or remove 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(el, className) { | |
'use strict'; | |
if (el.classList) { | |
return el.classList.contains(className); | |
} | |
return !!el.className.match(new RegExp('(\\s|^)' + className + '(\\s|$)')); | |
} | |
function addClass(el, className) { | |
'use strict'; | |
if (el.classList) { | |
el.classList.add(className); | |
} else if (!hasClass(el, className)) { | |
el.className += " " + className; | |
} | |
} | |
function removeClass(el, className) { | |
'use strict'; | |
if (el.classList) { | |
el.classList.remove(className); | |
} else if (hasClass(el, className)) { | |
var reg = new RegExp('(\\s|^)' + className + '(\\s|$)'); | |
el.className = el.className.replace(reg, ' '); | |
} | |
} |
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 el = document.getElementById('peace') | |
addClass(el, 'be-still') | |
// or | |
removeClass(el, 'be-still') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment