我可以知道元素是否在文档中?

Rat*_*ata 1 javascript

var myElement = document.querySelector('div.example');// <div..></div>
/*
 * A lot time after, codes executed, whatever
 */
if( myElement.isInDocument )
{
     // Do something
}
Run Code Online (Sandbox Code Playgroud)

有没有一种简单的方法可以知道'myElement'是否还在文档中?

Nie*_*sol 6

由于文档中的每个元素都是文档的子元素,因此请检查您的元素是否为:

function isInDocument(e) {
    while( e.parentNode) e = e.parentNode;
    return e === document;
}
Run Code Online (Sandbox Code Playgroud)


Dav*_*ret 5

从Mozilla

function isInPage(node) {
  return (node === document.body) ? false : document.body.contains(node);
}
Run Code Online (Sandbox Code Playgroud)

  • ...这个功能在我的一生中都在哪里? (2认同)