Home > Software design >  Use MutationObserver for multiple nodes
Use MutationObserver for multiple nodes

Time:10-11

I have a some elements in my HTML which are dynamically filled with text by an API. Now I want to check, if all elements have a value and then start a function. With the following code I'm able to observe only one element.

As expected for var targets = document.getElementsByClassName("creationDate"); I get the issue Failed to execute 'observe' on 'MutationObserver': parameter 1 is not of type 'Node'.

How can I check it for all elements with the class creationDate and if they all are not empty, start a function?

HTML:

<div id="rgMatches">
  <div >
    <div >
      <div >
        2022-09-24 16:10:00
      </div>
    </div>
    <div >
      <div >
        2022-09-24 16:05:23
      </div>
    </div>
    <div >
      <div >
        2022-09-24 16:05:22
      </div>
    </div>
    <div >
      <div >
        2022-09-24 16:05:27
      </div>
    </div>
    <div >
      <div >
      </div>
    </div>
    <div >
      <div >
      </div>
    </div>
    <div >
      <div >
      </div>
    </div>
  </div>
</div>

JS:

var delay = (function() {
var timer = 0;
return function(callback, ms) {
    clearTimeout(timer);
    timer = setTimeout(callback, ms);
  };
})();

var targets = document.getElementsByClassName("creationDate");
console.log(target);

var observer = new MutationObserver(function(mutations) {
    alert(targets.innerText);   
});

observer.observe(targets, {
    attributes:    true,
    childList:     true,
    characterData: true
});

CodePudding user response:

.observer() expects a Node as its first argument and you are passing it a collection.

Run a loop:

[...targets].forEach((target) => {
observer.observe(target, {
    attributes:    true,
    childList:     true,
    characterData: true
});

});

Also the way this is written seems to be incorrect:

var observer = new MutationObserver(function(mutations) {
    alert(targets.innerText);   
});

You are not making use of the mutations at all. You need to check what type of mutation ocurred and based on that do something. The first argument is an array of mutations

Looking at the docs, you might need something like this:

var observer = new MutationObserver(function(mutations) {
mutations.forEach((mutation) => {
....
if(mutation.type === 'childList'){
console.log(mutation.addedNodes);
}
...
});
});
  • Related