I get an array of DOM objects using getElementsByClassName:
a = document.getElementsByClassName("foo");
At this point, suppose a.length is 3. Then, during some function call, I want to switch the attributes of some of these objects by changing their class names. For example, I modify the class name of a[0]:
a[0].className = "bar";
It seems that the object that was just called as a[0] is now removed from a. a.length is now 2.
I am wondering why this happened. I defined a for once, but later modifications to its elements seem to be affecting the memberships of a. Can someone explain this?
According to the specification the NodeList (a kind of magical array) you obtain is live.
NodeList and NamedNodeMap objects in the DOM are live; that is, changes to the underlying document structure are reflected in all relevant NodeList and NamedNodeMap objects.
For example, if a DOM user gets a NodeList object containing the children of an Element, then subsequently adds more children to that element (or removes children, or modifies them), those changes are automatically reflected in the NodeList, without further action on the user's part.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With