Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would I ever want a static NodeList/HTMLCollection over a "live" NodeList if I don't need the granularity of CSS Selectors in the resulting list?

I generally hear that because live NodeLists are "bad" (see this Zakas article) and that informed the decision for querySelectorAll to return a static HTMLCollection. Why do people think live NodeLists are a bad thing? Code examples would probably help me understand this best.

If, whenever I care to use the value of a cached collection of Nodes for any computation that collection happens to not be a stale snapshot, I can't really see that as a "bad" thing.

I understand exactly how much more useful it is to select elements with a CSS Selector string, but if I can only reliably run code against that collection right after acquiring it, it seems to be quite a bit less useful than a live NodeList.

like image 604
bodine Avatar asked Sep 15 '25 14:09

bodine


1 Answers

Live nodelists are not bad, but their behaviour can be confusing if you're not used to it. Especially if you think of them as arrays (they're not arrays)

Consider a classic example of doubling the number of divs in a page. Here are three attempts at this:

// Example 1 (doesn't work)
for(var i = 0; i < document.querySelectorAll("div").length ; i++){
    document.body.appendChild(document.createElement("div"));
}

// Example 2 (works)
var divs = document.querySelectorAll("div");
for(var i = 0; i < divs.length ; i++){
    document.body.appendChild(document.createElement("div"));
}

// Example 3 (doesn't work)
var divs = document.getElementsByTagName("div");
for(var i = 0; i < divs.length; i++){
    document.body.appendChild(document.createElement("div"));
}

Example 1 is clearly an infinite loop. Each iteration, it rechecks the number of divs in the page.

Example 2 works as expected because the nodelist is already cached (of course it would be better to simply cache the length).

Example 3 looks like example 2. Many people would expect it to work the same way, as the nodelist is cached. But as the nodelist is live, it is actually another infinite loop. This catches some people out.

Also, if a function returns a static nodelist, you can requery the DOM each time you need it. This is arguably simpler than converting your live list to static.

like image 116
ColBeseder Avatar answered Sep 17 '25 05:09

ColBeseder