14

If I'm assuming correctly, an HTMLCollection is dynamic.

In which changes automatically, as items, are added or removed from the document.

Is there a way to detect a change in the size of an HTMLCollection using an event handler? Besides using a timer to constantly poll the collection of course.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
ryandlf
  • 27,155
  • 37
  • 106
  • 162
  • What browsers do you need to support? – Johan Feb 27 '14 at 08:20
  • 1
    I don't think there's such an event, but MutationObserver might be helpful, https://developer.mozilla.org/en/docs/Web/API/MutationObserver – Andrew Feb 27 '14 at 08:21
  • @Andrew Just what I had in mind as well. The problem is that it doesn't work in IE – Johan Feb 27 '14 at 08:23
  • Cross browser. Naturally. And unfortunately lol. – ryandlf Feb 27 '14 at 08:28
  • I guess with all my assuming I should have assumed that if there were such an event, mutation observers would be common practice and widely adopted by now. – ryandlf Feb 27 '14 at 08:30
  • duplicate of https://stackoverflow.com/questions/3219758/detect-changes-in-the-dom – a.gulcan Oct 23 '21 at 21:02
  • 1
    Does this answer your question? [Detect changes in the DOM](https://stackoverflow.com/questions/3219758/detect-changes-in-the-dom) – mtk Oct 25 '21 at 01:16

1 Answers1

2

Just to avoid confusion, dynamic means that something is modified during the runtime. HTMLCollection is live, which means it is dynamic plus it can be changed not just by the client script, but also by browser algorithms as declared here. These algorithms can be intercepted by MutationObserver (which is cross-browser today) explained by the test code below:

function addItem() {
    var li = document.createElement("li");
    li.innerHTML = "item";
    list.appendChild(li);
}

var data = list.children;

function watch(data) {
    console.log(data);
}

var observer = new MutationObserver(watch);
observer.observe(list, {childList: true});
<ul id="list"></ul>
<button onclick="addItem()">Add item</button>
<button onclick="console.log(data.length)">Test</button>

Here the data is the live HTMLCollection created during the load phase (before DOMContentLoaded fires), but modified by the browser algorithms anytime the Add Item button is pressed (it can be verified by Test button). The algorithms are intercepted by observer object which calls the watch callback with MutationRecord as its argument. This can be expensive, so the options need to be set carefully and the observer should be disconnected when not needed.

Jan Turoň
  • 31,451
  • 23
  • 125
  • 169