Detect added element to DOM with Mutation Observer

前端 未结 1 1291
不思量自难忘°
不思量自难忘° 2020-12-16 18:22

I\'m adding some element to DOM after drag event. I need to detect this element and the moment when this element was added. I use Mutation Observer but something is wrong, t

1条回答
  •  天命终不由人
    2020-12-16 19:06

    Here's a simple example of how you can use a MutationObserver to listen for when an element is added to the DOM.

    For brevity, I'm using jQuery syntax to build the node and insert it into the DOM.

    var myElement = $("
    hello world
    ")[0]; var observer = new MutationObserver(function(mutations) { if (document.contains(myElement)) { console.log("It's in the DOM!"); observer.disconnect(); } }); observer.observe(document, {attributes: false, childList: true, characterData: false, subtree:true}); $("body").append(myElement); // console.log: It's in the DOM!

    You don't need to iterate over each MutationRecord stored in mutations because you can perform the document.contains check directly upon myElement.

    0 讨论(0)
提交回复
热议问题