Question

I just read this article about NodeLists:

http://www.nczonline.net/blog/2010/09/28/why-is-getelementsbytagname-faster-that-queryselectorall/

If I understand correctly getElementsByTag name is live and querySelectorAll is not. Then could someone please explain to my why pNotLive has the title 'stackoverflow'? :

var pLive = document.getElementsByTagName( 'p' )[3];
var pNotLive = document.querySelectorAll( 'p' )[3];

pLive.title = "stackoverflow"
console.log( pNotLive.title ); // stackoverflow

//you can run this snippet in your console to verify
Was it helpful?

Solution

As your link explains, the getElementsByTagName method returns a collection that is automatically updated when the DOM changes. So if you call the method, and then a new element is added to the DOM, your collection will automatically be updated with the new element.

Where as, if you use querySelectorAll, you will be given a static list of DOM elements, that will NOT be updated automatically.

I believe the reason for the behaviour you have used in your example is because the list is static, and not the elements themselves. So the static approach just means the list will not change, so adding/removing elements will not change your list. But when you call for the title attribute, your list is simply pointing to the element, and that element is different from when you created the list.

In short, it is more of a list of references (to the DOM nodes), than a list of data objects (with the fixed data).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top