如何检查从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 /