检测DOM元素的父更改时间 [英] Detecting when a DOM element's parent changes

查看:134
本文介绍了检测DOM元素的父更改时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当元素的 parentElement 更改时,是否有DOM事件触发?如果没有,有没有办法优于轮询超时?



我知道什么时候 parentElement null 更改为某些定义的元素。也就是说,当DOM元素附加到文档树的某个地方时。



编辑



鉴于评论中的问题,以下是一个示例,显示如何使用 null创建元素 parentElement

  var element = document.createElement('div'); 

console.assert(element.parentElement == null);

只有在父项添加到DOM后才会设置:

  document.body.appendChild(element); 

console.assert(element.parentElement!= null);还要注意,使用jQuery创建的元素也将有一个 null
c $ c> parent when created:

  console.assert($('< div>< / div>') .get(0).parentElement == null); 


解决方案

Afaik没有这样的父监听者 p>

然而,我发现一个可能有帮助的黑客。至少值得一读,因为这个想法很聪明。



http://www.backalleycoder.com/2012/04/25/i-want-a-damnodeinserted/



他在插入过程中使用CSS @keyframes,并监听生成的动画事件,告诉他,该元素已插入。


Is there a DOM event that fires when an element's parentElement changes? If not, is there any way better than polling with a timeout?

I'm specifically interesting in knowing when the parentElement changes from null to some defined element. That is, when a DOM element is attached to the document tree somewhere.

EDIT

Given the questions in the comments, here is an example that shows how to create an element with a null parentElement:

var element = document.createElement('div');

console.assert(element.parentElement == null);

The parent is only set once it's added to the DOM:

document.body.appendChild(element);

console.assert(element.parentElement != null);

Note too that elements created using jQuery will also have a null parent when created:

console.assert($('<div></div>').get(0).parentElement == null);

解决方案

Afaik there's no such "parent listener".

Yet, I found a hack that might be helpful. At least it's worth reading, since the idea is clever.

http://www.backalleycoder.com/2012/04/25/i-want-a-damnodeinserted/

He uses CSS @keyframes during the insertion and listens for the resulting animation event which tells him, that the element got inserted.

这篇关于检测DOM元素的父更改时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆