如何使用 javascript 查找元素是否存在于 DOM 中或者它是虚拟的(刚刚由 createElement 创建)

发布于 2024-08-30 01:27:29 字数 384 浏览 2 评论 0原文

我正在寻找一种方法来查找 javascript 中引用的元素是否已插入到文档中。

让我们用下面的代码来说明一个例子:

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

// Element has not been inserted in the document, i.e. not present

document.getElementByTagName('body')[0].appendChild(elem);

// Element can now be found in the DOM tree

Jquery 有 :visible 选择器,但是当我需要找到不可见元素已放置在文档中的某个位置时,它不会给出准确的结果。

I'm looking for a way to find if element referenced in javascript has been inserted in the document.

Lets illustrate a case with following code:

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

// Element has not been inserted in the document, i.e. not present

document.getElementByTagName('body')[0].appendChild(elem);

// Element can now be found in the DOM tree

Jquery has :visible selector, but it won't give accurate result when I need to find that invisible element has been placed somewhere in the document.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

花心好男孩 2024-09-06 01:27:30

您还可以使用 jQuery.contains

jQuery.contains( document, YOUR_ELEMENT)

You can also use jQuery.contains:

jQuery.contains( document, YOUR_ELEMENT)
梦境 2024-09-06 01:27:30

使用 compareDocumentPosition 来查看该元素是否包含在 document. PPK 具有浏览器兼容性详细信息,并且 John Resig<​​/a> 有一个适用于 IE 的版本。

Use compareDocumentPosition to see if the element is contained inside document. PPK has browser compatibility details and John Resig has a version for IE.

不顾 2024-09-06 01:27:30
function isInDocument(query){
  return document.querySelectorAll(query).length != 0;
}
// isInDocument("#elemid") 
function isInDocument(query){
  return document.querySelectorAll(query).length != 0;
}
// isInDocument("#elemid") 
时光暖心i 2024-09-06 01:27:29

这是一种更简单的方法,使用标准 Node.contains DOM API 进行签入一个元素当前位于 DOM 中:

document.body.contains(MY_ElEMENT);

跨浏览器注意:IE 中的文档对象没有 contains() 方法 - 为了确保跨浏览器兼容性,请使用 <代码> document.body.contains() 相反。 (如果您要检查链接、脚本等元素,则为 document.head.contains


 

使用特定document引用与节点级ownerDocument的注意事项:

有人提出了使用MY_ELEMENT.ownerDocument.contains(MY_ELEMENT ) 检查文档中是否存在节点。虽然这可以产生预期的结果(尽管在 99% 的情况下比必要的更加冗长),但它也可能导致意想不到的结果,具体取决于用例。让我们谈谈原因:

如果您正在处理当前驻留在单独文档中的节点,例如使用 document.implementation.createHTMLDocument() 生成的节点,则 > 文档或 HTML 导入文档,并使用节点的 ownerDocument 属性来检查您认为的主要、视觉呈现的文档中是否存在code>,你将身处一个受伤的世界。

节点属性 ownerDocument 只是一个指向节点所在当前文档任何的指针。几乎 contains 的每个用例都涉及检查 contains >特定节点存在的文档。您无法保证 ownerDocument 与您要检查的文档相同 - 只有您知道这一点。 ownerDocument 的危险在于,有人可能会引入多种方法来引用、导入或生成驻留在其他文档中的节点。如果他们这样做,并且您编写的代码依赖于 ownerDocument 的相对推断,您的代码可能会崩溃。为了确保您的代码始终产生预期的结果,您应该只与您想要检查的特定引用 文档进行比较,而不是信任诸如ownerDocument之类的相对推论。

Here's an easier method that uses the standard Node.contains DOM API to check in an element is currently in the DOM:

document.body.contains(MY_ElEMENT);

CROSS-BROWSER NOTE: the document object in IE does not have a contains() method - to ensure cross-browser compatibility, use document.body.contains() instead. (or document.head.contains if you're checking for elements like link, script, etc)

 


 

Notes on using a specific document reference vs Node-level ownerDocument:

Someone raised the idea of using MY_ELEMENT.ownerDocument.contains(MY_ELEMENT) to check for a node's presence in the document. While this can produce the intended result (albeit, with more verbosity than necessary in 99% of cases), it can also lead to unexpected results, depending on use-case. Let's talk about why:

If you are dealing with a node that currently resides in an separate document, like one generated with document.implementation.createHTMLDocument(), an <iframe> document, or an HTML Import document, and use the node's ownerDocument property to check for presence in what you think will be your main, visually rendered document, you will be in a world of hurt.

The node property ownerDocument is simply a pointer to whatever current document the node resides in. Almost every use-case of contains involves checking a specific document for a node's presence. You have 0 guarantee that ownerDocument is the same document you want to check - only you know that. The danger of ownerDocument is that someone may introduce any number of ways to reference, import, or generate nodes that reside in other documents. If they do so, and you have written your code to rely on ownerDocument's relative inference, your code may break. To ensure your code always produces expected results, you should only compare against the specifically referenced document you intend to check, not trust relative inferences like ownerDocument.

过去的过去 2024-09-06 01:27:29

这样做:

var elem = document.createElement('div');
elem.setAttribute('id', 'my_new_div');

if (document.getElementById('my_new_div')) { } //element exists in the document.

Do this:

var elem = document.createElement('div');
elem.setAttribute('id', 'my_new_div');

if (document.getElementById('my_new_div')) { } //element exists in the document.
流星番茄 2024-09-06 01:27:29

最安全的方法是直接测试该元素是否包含在文档中:

function isInDocument(el) {
    var html = document.body.parentNode;
    while (el) {
        if (el === html) {
            return true;
        }
        el = el.parentNode;
    }
    return false;
}

var elem = document.createElement('div');
alert(isInDocument(elem));
document.body.appendChild(elem);
alert(isInDocument(elem));

The safest way is to test directly whether the element is contained in the document:

function isInDocument(el) {
    var html = document.body.parentNode;
    while (el) {
        if (el === html) {
            return true;
        }
        el = el.parentNode;
    }
    return false;
}

var elem = document.createElement('div');
alert(isInDocument(elem));
document.body.appendChild(elem);
alert(isInDocument(elem));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文