Home > Software engineering >  Detecting change in size of getElementsByClassName()
Detecting change in size of getElementsByClassName()

Time:09-15

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!

CodePudding user response:

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 elements and call observer.observe() for each element in your list of elements.

const elements = document.querySelectorAll(selector);

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

const options = {
  childList: true,
};

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

CodePudding user response:

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.

  • Related