Skip to content

Instantly share code, notes, and snippets.

@alvarezmauro
Last active May 8, 2018 02:44
Show Gist options
  • Save alvarezmauro/8f5bd75c81911ea9e2fd1d0a75f42e06 to your computer and use it in GitHub Desktop.
Save alvarezmauro/8f5bd75c81911ea9e2fd1d0a75f42e06 to your computer and use it in GitHub Desktop.
JS - Remove class from HTML elements
/******************************************************************************************************
* @function removeClass
* @param (elements) - String selector (eg: '#iddiv' or '.classdiv')
* or DOM elements (eg: document.querySelectorAll('.classdiv') )
* @param (myClass) - String calss name you whant to remove (eg: 'newClass')
******************************************************************************************************/
function removeClass(elements, myClass) {
// if there are no elements, we're done
if (!elements) {
return;
}
// if the class name is not a string, throw an error
if(typeof myClass !== 'string'){
throw new Error(myClass + ' is not a string');
return;
}
// if we have a selector, get the chosen elements
if (typeof(elements) === 'string') {
elements = document.querySelectorAll(elements);
}
else if (elements.tagName) { // if we have a single DOM element, make it an array to simplify behavior
elements=[elements];
}
// create pattern to find class name
var reg = new RegExp('(^| )'+myClass+'($| )','g');
// remove class from all chosen elements
for (var i=0; i<elements.length; i++) {
elements[i].className = elements[i].className.replace(reg,' ');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment