The reason is because querySelectorAll
method returns a static list. Any changes made to the document after the querySelectorAll
is used (like removeChild
in this case) will not be reflected in the list of nodes returned. Hence elToStyle[elToStyle.length - 1]
would still point to the node that was removed.
Whereas, getElementsByClassName
on the other hand returns a live list of nodes. This implies that elToStyle[elToStyle.length - 1]
would always point to the last .div
irrespective of any changes were done to the document after the node list was prepared or not.
Below is the extract from the official documentation available here
The NodeList object returned by the querySelectorAll() method must be static, not live ([DOM-LEVEL-3-CORE], section 1.1.1). Subsequent changes to the structure of the underlying document must not be reflected in the NodeList object. This means that the object will instead contain a list of matching Element nodes that were in the document at the time the list was created.
Note: You can see this by doing a console.log(elToStyle);
both before and after the removeChild
.