Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
211 views
in Technique[技术] by (71.8m points)

javascript - How to listen for a "div created" event?

I need to know when a div element is added to the page. Anytime, anywhere, as a child at any depth of the document tree.

const { body } = document;
const config = { childList: true, subtree: true };
const callback = function (mutationsList, observer) {
  for (const mutation of mutationsList) {
    if (mutation.type === 'childList') {
      console.log('A child node has been added or removed.');
      mutation.addedNodes.forEach((node) => console.log(node));
    }
  }
};
const observer = new MutationObserver(callback);
observer.observe(body, config);

I run this code via an extension immediately upon page navigation. As Google search results are loading, this doesn't log the creation of any of them. Only a handful of divs in the header and footer, and a couple scripts. I need to be notified as soon as any and every div element appears on the page.

question from:https://stackoverflow.com/questions/65911249/how-to-listen-for-a-div-created-event

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
observer.observe(body, config);

This was wrong, it has to be:

observer.observe(document, config);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...