如何检查从DOM检索的元素仍然存在于DOM中 [英] How to check an element retrieved from DOM is still present in DOM

查看:47
本文介绍了如何检查从DOM检索的元素仍然存在于DOM中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个DOM元素,作为事件的参数,例如click。

Let's say I got a DOM element, as a param of an event, for example click.

$(document).click(function() {
    myElement = $(this);
});

我如何稍后检查myElement是否仍在DOM中?
我不能使用.length或其他任何类似的东西,因为此时它仍然引用已保存的元素和DOM的状态,对吗?

How can I check later that myElement is still in the DOM? I can't use .length or any other things like that because it still refer to the saved element and the state of the DOM at this moment, right?

推荐答案

你可以检查元素父元素:

You can check element parent:

function isInDom(obj) {
    var root = obj.parents('html')[0] 
    return !!(root && root === document.documentElement);
}


if(isInDom(myElement)) {
     ...
}

这是工作小提琴: http:// jsfiddle。 net / vnxhQ / 7 /

这篇关于如何检查从DOM检索的元素仍然存在于DOM中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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