I saw this tweet yesterday and was reminded , once again, of how misunderstood the return value of a DOM method like document.getElementsByTagName is. Normally, it doesn’t matter that folks don’t really understand the return value fully, because most of the time the code just works. Where it breaks is interesting, so it’s worth taking a look at it in a little bit of depth.
Typically people do things like this:
var anchors = document.getElementsByTagName('a');
for (var i = 0; i < anchors.length; i++) {
anchors[i].addEventListener("click", beAwesome, false)
}
Common pattern. Get a list of the anchors on the page, loop through and add an event to each.
If asked, I’d be willing to bet most people would assume that the list they’re interacting with is an Array. It’s got a length and you can index it- that’s got to be an Array, right?
Surprise! 🙂
Continue reading “The JavaScript NodeList and You. Watch Where You Point That Thing, Soldier” →