javascript - 如何确定动态创建的 DOM 元素是否已添加到 DOM 中?

标签 javascript dom

According to spec ,只有 BODYFRAMESET 元素提供要附加的“onload”事件,但我想知道何时将动态创建的 DOM 元素添加到 DOM在 JavaScript 中。

我目前使用的 super 朴素启发式方法有效,如下所示:

  • 遍历元素的 parentNode 属性,直到找到最终祖先(即 parentNode.parentNode.parentNode.etc 直到 parentNode 为 null)

  • 如果最终祖先具有已定义的非空 body 属性

    • 假设所讨论的元素是 dom 的一部分
  • 其他

    • 在 100 毫秒内再次重复这些步骤

我所追求的要么是确认我正在做的事情是足够的(同样,它在 IE7 和 FF3 中都有效),要么是一个更好的解决方案,无论出于何种原因,我已经完全忘记了;也许我应该检查其他属性,等等。


编辑:我想要一种与浏览器无关的方式来执行此操作,不幸的是,我不住在一个浏览器的世界中;这就是说,浏览器特定的信息是值得赞赏的,但请注意你知道它在哪个浏览器中确实工作。谢谢!

最佳答案

更新:对于任何对此感兴趣的人,这是我最终使用的实现:

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;
}

我想要这个的原因是提供一种为 DOM 元素合成 onload 事件的方法。这是该函数(虽然我使用的东西略有不同,因为我将它与 MochiKit 结合使用):

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

希望对某人有用。

注意:我最终使用此解决方案而不是 Darryl's answer 的原因是因为 getElementById 技术仅在您位于同一文档中时才有效;我在页面上有一些 iframe,页面之间以一些复杂的方式相互通信 - 当我尝试这个时,问题是它找不到元素,因为它是不同文档的一部分,而不是它正在执行的代码.

关于javascript - 如何确定动态创建的 DOM 元素是否已添加到 DOM 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/220188/

相关文章:

javascript - jQuery fadeIn() 和 fadeOut() 无延迟

javascript - 隐藏/显示 HTML 元素还是删除/插入它更快?

javascript - 如何获取 onclick 函数在 JavaScript 中被调用的位置

javascript - 如何防止 JQuery 中的鼠标光标变为 'selected text'?

javascript - 我想获取 md-autocomplete 的内部标记值,但我无法获取文本值,请在下面查找代码

javascript - 单击滑出输入字段

php - Laravel - 将 HTML Dom-Parser 响应保存到数据库

javascript - 不同 HTML 页面上的相同 DOM 元素

javascript - Socket.IO 服务器的奇怪行为

javascript - 如何在 safari 和 chrome 的选择框(下拉框)中设置高度或填充?