How to observe an HTMLCollection?

Viewed 208

A little curious since I know that HTMLCollections update themselves automatically, I tried observing them by using a Proxy as shown below


let imagesCollection = document.images;

let io = new Proxy(imagesCollection, {
    set: (target, prop, value, reciever) => {
        // do stuff
        // apply default behaviour
        return Reflect.set(target, prop, value);
    }
});

// test the block by adding new elements

document.body.insertAdjacentHTML("beforeend", "<img>");
document.body.insertAdjacentHTML("beforeend", "<img class='img'>");
document.body.insertAdjacentHTML(
    "beforeend",
    "<img class='img' src='https://picsum.photos/200/300'>"
);


but when trying to add dynamically some images, nothing happen ...

So my questions are :

  • Is that even possible ?
  • If yes, Am I doing it wrong ?
1 Answers

If I understand correctly, proxies intercept operations with proxies, not with targets:

let target = {};

let proxy = new Proxy(target, {
    set: (target, prop, value, reciever) => {
        console.log(prop, value);
        return Reflect.set(target, prop, value);
    }
});

target.foo = 'I am not intercepted.';
proxy.bar = 'I am intercepted.';

So in your case, operations with io are intercepted, while operations with imagesCollection or document.images are not.

So mutation observer is a better option.

Related