Last active
May 8, 2018 02:43
-
-
Save alvarezmauro/9b09fe001e93e77dc131732d6ed1932d to your computer and use it in GitHub Desktop.
JS - Add a Class to HTML elements
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
/****************************************************************************************************** | |
* @function addClass | |
* @desc Add a Class to HTML elements | |
* @param (elements) - String selector (eg: '#iddiv' or '.classdiv') | |
* or DOM elements (eg: document.querySelectorAll('.classdiv') ) | |
* @param (myClass) - String calss name you whant to add (eg: 'newClass') | |
******************************************************************************************************/ | |
function addClass(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]; | |
} | |
// add class to all chosen elements | |
for (var i=0; i<elements.length; i++) { | |
// if class is not already found | |
if ( (' '+elements[i].className+' ').indexOf(' '+myClass+' ') < 0 ) { | |
// add class | |
elements[i].className += ' ' + myClass; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment