Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an event listener to check if childElements have been added to an elements

I have a puppeteer project in which I'm waiting for some form of information on an Element. For example, in the header, I'm waiting for some new child Nodes.

<div id="outside">
</div>

and then after some time

<div id="outside">
   <div id='inside'>
   </div>
</div>

is there a way for me to add an event listener to check when the HTML has been changed?

something like

page.addListener('#outside', () => {
   console.log('event fired');
}
like image 682
Broccoli Soup Avatar asked Sep 18 '25 13:09

Broccoli Soup


1 Answers

You can try with MutationObserver

// Options for the observer (which mutations to observe)
const config = { attributes: true, childList: true, subtree: true };

// Callback function to execute when mutations are observed
const callback = function(mutationsList, observer) {
  for(let mutation of mutationsList) {
    if (mutation.type === 'childList') {
      console.log('A child node has been added or removed.');
    }
    else if (mutation.type === 'attributes') {
      console.log('The ' + mutation.attributeName + ' attribute was modified.');
    }
  }
};

// Create an observer instance linked to the callback function
const observer = new MutationObserver(callback);
const targetNode = document.querySelector('#outside');

// Start observing the target node for configured mutations
observer.observe(targetNode, config);

targetNode.insertAdjacentHTML('beforeend', "<div id='inside'>Child</div>"); // Add child
targetNode.classList.add('.child'); // Modify attribute
document.querySelector('#inside').style.marginLeft = '15px';
<div id="outside">Parent
</div>
like image 190
Mamun Avatar answered Sep 20 '25 05:09

Mamun