Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save FauziFerdiansyah/d81b1268cf085cf534ae75629d3627d3 to your computer and use it in GitHub Desktop.
Save FauziFerdiansyah/d81b1268cf085cf534ae75629d3627d3 to your computer and use it in GitHub Desktop.
Functions for add class and remove class with Pure javascript
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