Detecting change in size of getElementsByClassName()

Viewed 49

I am trying to develop a Chrome extension which replaces certain HTML in a list of elements that updates itself with time, but I can't find the right way to do it.

I have tried the following:

console.log("Getting nodes...")
var f = document.getElementsByClassName("myClassName")

function watch(data) {
    alert("Changed!!")
}

var observer = new MutationObserver(watch);
observer.observe(f.childList, {childList: true});

But I get the following error:

Uncaught TypeError: Failed to execute 'observe' on 'MutationObserver': parameter 1 is not of type 'Node'.

Am I missing something? Perhaps there's a better way? Any help will be much appreciated!

2 Answers

Use a forEach on your list, and call observe for each node.

Array.from(elements).forEach(element => observer.observe(element, {childList: true}) )

The childList parameter is for children of each node, and not for a list of nodes.

Select your elements with Document.querySelectorAll() if possible. Unlinke getElementsByClassName, querySelectorAll returns a snapshot of elements instead of live list which makes your result more predictable.

Either way, loop over the elements and call observer.observe() for each element in your list.

const elements = document.querySelectorAll('.parent');

const observer = new MutationObserver(() => {
  alert('Changed!');
});

const options = {
  childList: true,
};

for (const element of elements) {
  observer.observe(element, options);
}
Related