javascripttogglegetelementsbyclassname

Selecting all elements by specific class name and using toggle to change the class name


Desired Outcome

I want to be able to dynamicly select all the elements with the classname of "input" and change said class name to "input-dm" utilizing toggle. This is for a toggle button which changes the webpage from light mode theme to darkmode theme. I am utilizing toggle because I would like the option to be toggle on and off at the users whim. Any help and being pointed in the right direction would be greatly apprecaited. Thank for your time.

Current Outcome

This is what I currently have which works. It's long and drawn out and I know there has to be an easier and more dynamic way to do this. Also in this version I identify the element by the id. However, I would rather utilize the class to identify the element as the classes are the same while as the ID should be unique.

<script type="text/javascript" src="/js/jquery-3.7.1.min.js"></script>
function darkmode() {
     document.getElementById("lastname").classList.toggle("input-darkmode");
     document.getElementById("firstname").classList.toggle("input-darkmode");
     document.getElementById("middle").classList.toggle("input-darkmode");
     document.getElementById("date").classList.toggle("input-darkmode");
     document.getElementById("email").classList.toggle("input-darkmode");
     document.getElementById("phone").classList.toggle("input-darkmode");
     document.getElementById("travel-start-date").classList.toggle("input-darkmode");
     document.getElementById("travel-end-date").classList.toggle("input-darkmode");
     document.getElementById("travel_loc").classList.toggle("input-darkmode");
}

Checkbox Calling the function

Dark Mode:&nbsp;<label class="switch"><input onclick="darkmode()" type="checkbox" checked><span class="slider round"></span></label>

Below are some failed attempts that unfortunely it did not work.

document.getElementByClassName("input").classList.toggle("input-darkmode");
var elements = document.getElementsByClassName('input');
for(var i = 0; i < elements.length; i++){
     ([elements]).classlist.toggle("input-darkmode");
}

Solution

  • (As requested by OP.)

    In your last sample code block, that should be

    elements[i].classList.toggle("input-darkmode")