Categories
JavaScript Answers

How to Use the Mutation Observer for Watching the Creation of New Elements?

Spread the love

To use the mutation observer for watching the creation of new elements, we can use the MutationObserver constructor to watch the element that contains the element that will be added.

For instance, if we have the following HTML:

<div id='foo'>
  click me
</div>

and we want to watch for an element with ID bar to be added, then we can write:

const foo = document.querySelector('#foo')
foo.addEventListener('click', () => {
  const bar = document.createElement('div')
  bar.id = 'bar'
  foo.appendChild(bar)
})

const obs = new MutationObserver((mutations, observer) => {
  for (const m of mutations) {
    for (const n of m.addedNodes) {
      if (n.id === "bar") {
        console.log("bar was added!");
      }
    }
  }
});

obs.observe(foo, {
  childList: true
});

We select the div with document.querySelector .

Then we call foo.addEventListener to add a click listener to the foo element.

In the click listener callback, we call document.createElement to create a div and append it into the div with ID foo with appendChild .

bar.id is set to 'bar' so the new div’s ID is bar .

Next, we create a new MutationObserver instance with a callback that loops through all the mutations and in it, we loop through all the nodes that are added, which are stored in m.addedNodes .

Inside the inner loop, we check for an element that’s added with ID bar .

If it’s true , then we log 'bar was added!' .

Therefore, when we click on the foo div, we’ll see the message logged.

By John Au-Yeung

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

Leave a Reply

Your email address will not be published.