Why changing variable equal to a HTML collection changes the original values of the collection? Why changing variable equal to a HTML collection changes the original values of the collection?
There's a different behaviour that I see that I can't really understand exactly why this happens. Originally, after making a variable equal to another, it will only copy the value of one variable to another, but if I change the value of a variable after that, the other variable won't be affected, right? As in:
let a = 3
let b = 5
b = a
//here the variable b, that was 5 will become the same as the variable a, becoming 3.
a = 10
//now, if I change the value in a to 10, b will still have the value of 3.
That's pretty basic JavaScript, I know. But knowing that, I can't understand why it's different when it comes to HTMLcollection.
Here is the situation:
const allLi = document.getElementsByTagName('li');
for (let xis of allLi) {
xis.classList.toggle('highlight');
}
Here I got a HTMLcollection and assigned it to the variable allLi, and then I used a for of loop to modify it, thus changing the original values in the HTMLcollection, that reefer to the class values of the li elements.
My question is: why in this case if I change a variable through the loop I'm able to modify the original values in the HTMLcollection? Why it's different of when I declare a new value to a in the previous example and the other variable keeps unchanged?
Thank you very much.
from Stackoverflow
Comments
Post a Comment