Reputation:
Ok, so i was playing around with static || live nodelists, trying to test the concept, i have tried different scenarios but there are two scenarios that caught my attention:
var toBeLogged = document.getElementsByTagName('p');
console.log(toBeLogged.length); // Returns 1 to the console
var newEl = document.createElement('p');
document.body.appendChild(newEl);
console.log(toBeLogged.length); // Returns 2 to the console
which makes sense since the getElementsBy... is a live node collection so it's obviously going to return the updated value when asking for the value again after the update.
but the scenario number two with a small change makes the "Live" nodelist act as a static:
var toBeLogged = document.getElementsByTagName('p').length;
console.log(toBeLogged); // Returns 1 to the console
var newEl = document.createElement('p');
document.body.appendChild(newEl);
console.log(toBeLogged); // Returns 1 also to the console
so my question is : why the variable created to represent the length property of a live nodelist is not returning a live value as in the value of the variable representing directly the nodelist without adding properties.
i am trying to describe things accurately as much as i can. Thanks in advance. appreciate your time spent on it.
Upvotes: 0
Views: 213
Reputation: 1748
document.getElementsByTagName('p').length
returns immutable primitive value, it can't be changed, it can be replaced only. .length
return new primitive values every time you access it, while document.getElementsByTagName('p')
returns same object every time.
Upvotes: 0