Determining if a HTML element has been added to the DOM dynamically

前端 未结 4 531
执笔经年
执笔经年 2020-12-05 00:24

Is there a way in Javascript or jQuery to find out when a HTML element has been added to the DOM dynamically, either through jQuery.append() or one of the nativ

4条回答
  •  再見小時候
    2020-12-05 00:54

    You can use Mutation Observers for this purpose - at least if you do not need to support IE/Opera.

    Here's a short example (taken from html5rocks.com) on how they are used:

    var insertedNodes = [];
    var observer = new WebKitMutationObserver(function(mutations) {
        mutations.forEach(function(mutation) {
            for(var i = 0; i < mutation.addedNodes.length; i++)
                insertedNodes.push(mutation.addedNodes[i]);
        })
    });
    observer.observe(document, {
        childList: true
    });
    console.log(insertedNodes);
    

    Note the Webkit prefix. You need to use the browser-specific prefix. In Firefox it would be Moz instead.

提交回复
热议问题