更新:对于任何对此感兴趣的人,这是我最终使用的实现:
function isInDOMTree(node) {
// If the farthest-back ancestor of our node has a "body"
// property (that node would be the document itself),
// we assume it is in the page's DOM tree.
return !!(findUltimateAncestor(node).body);
}
function findUltimateAncestor(node) {
// Walk up the DOM tree until we are at the top (parentNode
// will return null at that point).
// NOTE: this will return the same node that was passed in
// if it has no ancestors.
var ancestor = node;
while(ancestor.parentNode) {
ancestor = ancestor.parentNode;
}
return ancestor;
}
我想要这个的原因是提供一种合成方法onload
DOM 元素的事件。这是该函数(尽管我使用的函数略有不同,因为我将它与MochiKit http://www.mochikit.com/):
function executeOnLoad(node, func) {
// This function will check, every tenth of a second, to see if
// our element is a part of the DOM tree - as soon as we know
// that it is, we execute the provided function.
if(isInDOMTree(node)) {
func();
} else {
setTimeout(function() { executeOnLoad(node, func); }, 100);
}
}
例如,可以按如下方式使用此设置:
var mySpan = document.createElement("span");
mySpan.innerHTML = "Hello world!";
executeOnLoad(mySpan, function(node) {
alert('Added to DOM tree. ' + node.innerHTML);
});
// now, at some point later in code, this
// node would be appended to the document
document.body.appendChild(mySpan);
// sometime after this is executed, but no more than 100 ms after,
// the anonymous function I passed to executeOnLoad() would execute
希望这对某人有用。
注意:我最终选择这个解决方案而不是达里尔的回答 https://stackoverflow.com/questions/220188/how-can-i-determine-if-a-dynamically-created-dom-element-has-been-added-to-the-do/220224#220224是因为 getElementById 技术仅在您位于同一文档中时才有效;我在页面上有一些 iframe,并且页面以一些复杂的方式在彼此之间进行通信 - 当我尝试此操作时,问题是它找不到该元素,因为它是与其执行的代码不同的文档的一部分。