Last active
April 28, 2017 08:11
-
-
Save 5iDS/d825c6fc998c39283c4882dc418fe805 to your computer and use it in GitHub Desktop.
Vanilla JS function to add class on DOM 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(elements, myClass) { | |
// if there are no elements, we're done | |
if (!elements) { return; } | |
// if we have a selector, get the chosen elements | |
if (typeof(elements) === 'string') { | |
elements = document.querySelectorAll(elements); | |
} | |
// if we have a single DOM element, make it an array to simplify behavior | |
else if (elements.tagName) { 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