I have a function that gets called when you click a button. I'm checking to see if the clicked item has the class "itm-active". If it does, don't do anything. Else check for elements that have it and remve the class from them. Also change the text of the button one the class has been removed.
The issue comes in when I'm trying to change the text of the button. If I hardcode an item, in this case items[0], I am able to change the text of the button. If I try to do the same thing within the for loop, I'm getting the error "Uncaught TypeError: items[i] is undefined"
NOTE: If I comment out the line items[i].innerHTML = "test";. The line above it doesn't give any error. I left comments on the lines in question to make it easy to see.
Also I don't believe this to be off-by-one error, because if it was then I should get the same error with items[i].classList.remove("itm-active"); as well, but I don't.
Off-by-one error discussion here
function activeStatus (event) {
let activeItem = event.srcElement.classList.contains("itm-active");
if (activeItem) {
} else {
//Remove itm-active from other places
items = document.getElementsByClassName("itm-active");
items[0].innerHTML = "test"; //This works fine
for (let i = 0; i < items.length; i++) {
if (items[i].classList.contains("itm-active")) {
items[i].classList.remove("itm-active"); //This works fine
items[i].innerHTML = "test"; //Doesn't work for some reason
}
}
}
}
getElementsByClassNamereturns a live list of items, so if you remove the class from an item, it drops off the list, therefore if this code ever inside theif, it will fail for the last item. If it enters twice, it will fail for the second to last item. Etc.itm-activeclass that element gets removed from the list. Instead you can use document.querySelectorAll(".itm-active") to get a static NodeList of matching elements - that way the list won't change when you remove theitem-activeclass.