skip to Main Content

I’m trying to make a a JS forEach loop that is supposed to run after the DOM is fully loaded, but for some reason it won’t run on code but when I put the same loop on console it runs fine.

window.onload = (event) => {

    var checkboxes = document.getElementsByName("plates")
    var labelPlate = document.getElementsByName("labelPlate")

    checkboxes.forEach((i, index) => {
        if (i.checked) {

            labelPlate[index].classList.add("active")
        } else {
            labelPlate[index].classList.remove("active")
        }
    })
};

Loop is supposed to run.

2

Answers


  1. The reason the code works in the console and not when embedded into your page directly, is likely because the elements you’re searching for are being dynamically added to the page after the load event occurs.

    In the console, you’re manually waiting long enough for those elements be in the DOM before running that code, but when the code is included in the page itself, the code is searching for those elements before they’ve made it into the DOM.

    You need to modify your code, so that it fires after the dynamic elements are added (which occurs AFTER when the base html document is initially loaded).

    Login or Signup to reply.
  2. To add to @Lonnie’s answer:

    You need to modify your code, so that it fires after the dynamic elements are added (which occurs AFTER when the base html document is initially loaded).

    You have a few options:

    • Load your script at the end of the document in case it’s static instead of <head>
    • Wait for a successful event from your framework (since you haven’t mentioned any such thing here, I’ll give you a framework agnostic answer)
      • At the end of the part of your code that generates your plates and labels do the following: (to fire a complete event)
        const myCompleteEvent = new Event("plates-loaded");
        document.dispatchEvent(myCompleteEvent);
        
      • Use it like so:
        document.addEventListener("plates-loaded", () => {
           const checkboxes = document.getElementsByName("plates");
           const labelPlate = document.getElementsByName("labelPlate");
        
           checkboxes.forEach((c, i) => {
             labelPlate[i].classList.toggle("active", c.checked);
           });
        });
        

    Also cleaned your code by using classList.toggle instead of add/remove 🙂

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search