Javascript 如何使用javascript查找元素是否存在于DOM中或者它是虚拟的(刚刚由createElement创建)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2719002/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to find with javascript if element exists in DOM or it's virtual (has been just created by createElement)
提问by mpontus
I'm looking for a way to find if element referenced in javascript has been inserted in the document.
我正在寻找一种方法来查找 javascript 中引用的元素是否已插入文档中。
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.
Jquery 有 :visible 选择器,但是当我需要找到不可见元素已放置在文档中的某个位置时,它不会给出准确的结果。
回答by csuwldcat
Here's an easier method that uses the standard Node.contains DOM APIto check in an element is currently in the DOM:
这是一个更简单的方法,它使用标准的Node.contains DOM API来检查当前在 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)
CROSS-BROWSER 注意:IE 中的文档对象没有contains()方法 - 为确保跨浏览器兼容性,请document.body.contains()改用。(或 document.head.contains 如果您正在检查链接、脚本等元素)
Notes on using a specific documentreference vs Node-level ownerDocument:
使用特定document参考与节点级别的注意事项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 canproduce 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:
有人提出了使用MY_ELEMENT.ownerDocument.contains(MY_ELEMENT)检查节点是否存在于文档中的想法。虽然这可以产生预期的结果(尽管在 99% 的情况下比必要的冗长),但它也可能导致意外的结果,具体取决于用例。我们来谈谈为什么:
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 ownerDocumentproperty to check for presence in what you thinkwill be your main, visually rendered document, you will be in a world of hurt.
如果您正在处理当前驻留在单独文档中的节点,例如使用document.implementation.createHTMLDocument()、<iframe>文档或 HTML 导入文档生成的节点,并使用该节点的ownerDocument属性检查您认为将是您的主要、视觉呈现的内容中是否存在document,你会在一个受伤的世界里。
The node property ownerDocumentis simply a pointer to whatevercurrent document the node resides in. Almost every use-case of containsinvolves checking a specificdocumentfor a node's presence. You have 0 guarantee that ownerDocumentis the same document you want to check - only you know that. The danger of ownerDocumentis 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 referenceddocumentyou intend to check, not trust relative inferences like ownerDocument.
该节点属性ownerDocument只是一个指针,无论当前文档的节点寓于几乎每个用例contains涉及检查一个特定document的节点的存在。您有 0 保证ownerDocument与您要检查的文档相同 - 只有您知道。危险ownerDocument在于有人可能会引入多种方法来引用、导入或生成驻留在其他文档中的节点。如果他们这样做,并且您编写的代码依赖于ownerDocument的相对推理,则您的代码可能会中断。为确保您的代码始终产生预期结果,您应该只与您打算检查的具体引用进行比较document,而不是相信ownerDocument.
回答by DexterW
Do this:
做这个:
var elem = document.createElement('div');
elem.setAttribute('id', 'my_new_div');
if (document.getElementById('my_new_div')) { } //element exists in the document.
回答by Tim Down
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));
回答by nitinkhuranas
回答by Sahan
function isInDocument(query){
return document.querySelectorAll(query).length != 0;
}
// isInDocument("#elemid")
回答by Jeffery To
Use compareDocumentPositionto see if the element is contained inside document. PPKhas browser compatibility details and John Resighas a version for IE.
使用compareDocumentPosition查看元素是否包含在 中document。PPK有浏览器兼容性详细信息,John Resig有 IE 版本。

