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
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).
To add to @Lonnie’s answer:
You have a few options:
<head>
plates
andlabels
do the following: (to fire acomplete
event)Also cleaned your code by using
classList.toggle
instead ofadd/remove
🙂