getElementsByTagName gotcha: the “live NodeList”
Maybe this is isn’t new for most people but it certainly confused the hell out of me.
I am working on a dynamic script loader. The basic concept is this:
- Get all script tags in the document
- Loop over them and find the one with the string “?load=” in its
srcattribute - Extract a list of scripts to include from the
srcattribute - Insert new script tags in the DOM
Here’s a rough outline of the code:
scriptTags = document.getElementsByTagName("script");
for(i=0;i<scriptTags.length;i++) {
if(scriptTags[i].src) {
if(scriptTags[i].src.indexOf("?load=") != -1) {
// extract list of script files from src attribute
for(j=0;j<scriptFiles.length;j++) {
// add new script tag to the DOM
}
}
}
}
This worked very well but I noticed that the code was looping more times than expected. I realised that the length of the scriptTags array was increasing when new script tags were added to the DOM. OK, this sounds sort of logical but I was under the impression that getElementsByTagName returned a snapshot of the DOM rather than a reference to a dynamic array of elements.
I googled getElementsByTagName and the Mozilla DOM documentation says this:
elements = element.getElementsByTagName(tagName)elements is a live NodeList of found elements in the order they appear in the tree.
The next step is to check how mootools handles this. Its advanced DOM selectors definitely use getElementsByTagName but also apply ID and class filters so my guess is that the result is probably a snapshot rather than a live NodeList.
Anyway, it’s time for lunch… I’ll write an update when I know more.

November 23rd, 2006 at 8:46 pm
salut, désolée si je t’écris ceci comme un ‘comment’ mais j’ai pas trouvé une adresse e-mail sur le site. je voulais juste savoir si je peux utiliser ton image de leeds (http://www.1pixelout.net/wp-content/leedsintheworld.gif) sur un site pour notre groupe de l’université de amnesty international? merci en avance,
Cecilia