Created
July 10, 2018 04:03
-
-
Save FauziFerdiansyah/d81b1268cf085cf534ae75629d3627d3 to your computer and use it in GitHub Desktop.
Functions for add class and remove class with Pure javascript
This file contains 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 els = document.getElementsByClassName('current-class-name'); | |
removeClass(els, 'current-class-name'); | |
addClass(els, 'new-class-name'); | |
var el = document.getElementById('current-class-name'); | |
removeClass([el], 'current-class-name'); | |
addClass([el], 'new-class-name'); | |
function addClass(elements, className) { | |
for (var i = 0; i < elements.length; i++) { | |
var element = elements[i]; | |
if (element.classList) { | |
element.classList.add(className); | |
} else { | |
element.className += ' ' + className; | |
} | |
} | |
} | |
function removeClass(elements, className) { | |
for (var i = 0; i < elements.length; i++) { | |
var element = elements[i]; | |
if (element.classList) { | |
element.classList.remove(className); | |
} else { | |
element.className = element.className.replace(new RegExp('(^|\\b)' + className.split(' ').join('|') + '(\\b|$)', 'gi'), ' '); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment