Detect changes in the DOM

后端 未结 7 2505
温柔的废话
温柔的废话 2020-11-21 05:45

I want to execute a function when some div or input are added to the html. Is this possible?

For example, a text input is added, then the function should be called.<

7条回答
  •  生来不讨喜
    2020-11-21 05:45

    The following example was adapted from Mozilla Hacks' blog post and is using MutationObserver.

    // Select the node that will be observed for mutations
    var targetNode = document.getElementById('some-id');
    
    // Options for the observer (which mutations to observe)
    var config = { attributes: true, childList: true };
    
    // Callback function to execute when mutations are observed
    var callback = function(mutationsList) {
        for(var mutation of mutationsList) {
            if (mutation.type == 'childList') {
                console.log('A child node has been added or removed.');
            }
            else if (mutation.type == 'attributes') {
                console.log('The ' + mutation.attributeName + ' attribute was modified.');
            }
        }
    };
    
    // Create an observer instance linked to the callback function
    var observer = new MutationObserver(callback);
    
    // Start observing the target node for configured mutations
    observer.observe(targetNode, config);
    
    // Later, you can stop observing
    observer.disconnect();
    

    Browser support: Chrome 18+, Firefox 14+, IE 11+, Safari 6+

提交回复
热议问题