Skip to content

Instantly share code, notes, and snippets.

@greg-raven
Created September 3, 2022 11:54
Show Gist options
  • Select an option

  • Save greg-raven/3480d4d2961b77e5a4fcd90ac6ba7d5b to your computer and use it in GitHub Desktop.

Select an option

Save greg-raven/3480d4d2961b77e5a4fcd90ac6ba7d5b to your computer and use it in GitHub Desktop.

Revisions

  1. Greg Raven created this gist Sep 3, 2022.
    25 changes: 25 additions & 0 deletions addClass.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,25 @@
    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;
    }
    }
    }