Categories
JavaScript Answers

How to Get Notified When an Element is Added to the Page with JavaScript?

Spread the love

The easiest way to watch for changes in the DOM is to use the MutationObserver API built into most browsers.

To use it, we can write:

const observerConfig = {
  attributes: true,
  childList: true,
  characterData: true
};

const observer = new MutationObserver((mutations) => {
  mutations.forEach((mutation) => {
    console.log(mutation.type);
  });
});
observer.observe(document.body, observerConfig);

setTimeout(() => {
  const div = document.createElement('div')
  document.body.appendChild(div)
}, 1500)

to watch for changes in the DOM with the MutationObserver constructor.

We pass in a callback with the mutations parameter to the constructor.

And we get the mutations that are applied to the DOM from there.

mutation.type has the type of mutation that’s done.

We should see 'chilidsList' and 'attributes' as values.

'childList‘ is the change in child nodes.

'attributes' is the change in attribute nodes.

We call observer with the root element to observer and the observerConfig to config how the mutation observer watches changes.

attributes set to true means we watch for attribute node changes.

childList set to true means we watch for child node changes.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *