How can I determine if a dynamically-created DOM element has been added to the DOM?

后端 未结 11 1007
滥情空心
滥情空心 2020-12-02 20:07

According to spec, only the BODY and FRAMESET elements provide an \"onload\" event to attach to, but I would like to know when a dynamically-create

11条回答
  •  囚心锁ツ
    2020-12-02 20:57

    A MutationObserver is what you should use to detect when an element has been added to the DOM. MutationObservers are now widely supported across all modern browsers (Chrome 26+, Firefox 14+, IE11, Edge, Opera 15+, etc).

    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!

    The observer event handler will trigger whenever any node is added or removed from the document. Inside the handler, we then perform a contains check to determine if myElement is now in the document.

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

    To improve performance, replace document with the specific element that will contain myElement in the DOM.

提交回复
热议问题