Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTMLCollection change event with JavaScript

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.

like image 767
ryandlf Avatar asked Dec 09 '25 03:12

ryandlf


1 Answers

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.

like image 152
Jan Turoň Avatar answered Dec 11 '25 16:12

Jan Turoň



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!