Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
180 views
in Technique[技术] by (71.8m points)

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

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 native Javascript's node manipulators? There are probably several different ways to add HTML elements to the page dynamically, so I'm not sure what event or events I should be listening on.

The specific example is that that an anchor tag is being added to the page by a third-party Javascript code (that I cannot modify or easily glean). I want to change the link's text.

I am hoping there is something better than a setTimeout() loop on $(SOME ELEMENT).length > 0. (part of which I saw in How can I determine if a dynamically-created DOM element has been added to the DOM? but it's from 2008)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...