简体   繁体   中英

MutationObserver for new created element?

How to MutationObserver for new created element? When I create a new element, mutatonObserver does not work. I need to register if the giant box has changed style...

<button onclick="myFunction()">Create</button>
<button onclick="myFunctionStyle()">Change style</button>
var observerm = new MutationObserver(function(mutationsm) {
    mutationsm.forEach(function(mutationRecord) {
        alert('style changed!');
    });    
});

var targetm = document.getElementById("Box");
observerm.observe(targetm, { attributes : true, attributeFilter : ['style'] });


function myFunction() {
  var newdiv = document.createElement("DIV");
  newdiv.innerHTML = "Box";
  newdiv.id = "Box";
  newdiv.style.width = "100px";
  newdiv.style.height = "50px";
  newdiv.style.backgroundColor = "red";
  
  document.body.appendChild(newdiv);
}

function myFunctionStyle() {
  document.getElementById("Box").style.backgroundColor = "blue";
}

Since the newly added elements are appended to the document.body , that's the element you need to attach another MutationObserver to.

new MutationObserver(() => {
  console.log('mutation on document body');
  // rest of the code you need when an element is appended
})
  .observe(document.body, { childList: true })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM