如何在不使用getElementById
方法的情况下测试元素是否存在?我已设置live demo以供参考。我也会在这里打印代码:
<!DOCTYPE html>
<html>
<head>
<script>
var getRandomID = function (size) {
var str = "",
i = 0,
chars = "0123456789abcdefghijklmnopqurstuvwxyzABCDEFGHIJKLMNOPQURSTUVWXYZ";
while (i < size) {
str += chars.substr(Math.floor(Math.random() * 62), 1);
i++;
}
return str;
},
isNull = function (element) {
var randomID = getRandomID(12),
savedID = (element.id)? element.id : null;
element.id = randomID;
var foundElm = document.getElementById(randomID);
element.removeAttribute('id');
if (savedID !== null) {
element.id = savedID;
}
return (foundElm) ? false : true;
};
window.onload = function () {
var image = document.getElementById("demo");
console.log('undefined', (typeof image === 'undefined') ? true : false); // false
console.log('null', (image === null) ? true : false); // false
console.log('find-by-id', isNull(image)); // false
image.parentNode.removeChild(image);
console.log('undefined', (typeof image === 'undefined') ? true : false); // false ~ should be true?
console.log('null', (image === null) ? true : false); // false ~ should be true?
console.log('find-by-id', isNull(image)); // true ~ correct but there must be a better way than this?
};
</script>
</head>
<body>
<div id="demo"></div>
</body>
</html>
基本上上面代码演示的是一个元素存储到变量中然后从dom中删除。即使元素已从dom中删除,该变量仍保留元素,就像第一次声明时一样。换句话说,它不是元素本身的实时引用,而是副本。因此,检查变量的值(元素)是否存在会产生意外结果。
isNull
函数是我尝试从变量中检查元素是否存在,并且它有效,但我想知道是否有更简单的方法来实现相同的结果。
PS:如果有人知道一些与该主题相关的好文章,我也会对JavaScript变量的行为感兴趣。
答案 0 :(得分:459)
似乎有些人正在这里登陆,只是想知道一个元素是否存在(与原始问题有点不同)。
这就像使用任何浏览器的选择方法一样简单,并检查它是否为 truthy 值(通常)。
例如,如果我的元素有id
"find-me"
,我可以简单地使用...
var elementExists = document.getElementById("find-me");
这是指定要么返回对元素的引用,要么null
。如果必须有布尔值,只需在方法调用之前抛出!!
。
此外,您可以使用其他许多方法来查找元素,例如(所有生活在document
之内):
querySelector()
/ querySelectorAll()
getElementsByClassName()
getElementsByName()
其中一些方法返回NodeList
,因此请务必检查其length
属性,因为NodeList
是一个对象,因此 truthy 。
为了实际确定某个元素是否作为可见DOM的一部分存在(如最初提出的问题),Csuwldcat provides a better solution than rolling your own(如此答案所包含)。也就是说,在DOM元素上使用contains()
方法。
你可以像这样使用它......
document.body.contains(someReferenceToADomElement);
答案 1 :(得分:269)
如果可用,为什么不使用getElementById()
?
此外,这是使用jQuery轻松实现的方法:
if ($('#elementId').length > 0) {
// exists.
}
如果你不能使用第三方库,只需坚持基础JavaScript:
var element = document.getElementById('elementId');
if (typeof(element) != 'undefined' && element != null)
{
// exists.
}
答案 2 :(得分:159)
使用Node.contains DOM API,您可以非常轻松地检查页面中任何元素的存在(当前在DOM中):
document.body.contains(YOUR_ELEMENT_HERE);
CROSS-BROWSER注意:IE中的document
对象没有contains()
方法 - 为确保跨浏览器兼容性,请使用document.body.contains()
代替< / p>
答案 3 :(得分:56)
我只是这样做:
if(document.getElementById("myElementId")){
alert("Element exists");
} else {
alert("Element does not exist");
}
适合我,并且没有任何问题......
答案 4 :(得分:10)
此函数检查元素是否在页面的正文中。由于contains是包容性的并且确定主体是否包含自身不是isInPage的意图,这种情况显式返回false。
function isInPage(node) {
return (node === document.body) ? false : document.body.contains(node);
}
节点是我们要在。
中检查的节点答案 5 :(得分:8)
你能检查一下parentNode属性是否为null?
即。
if(!myElement.parentNode)
{
//node is NOT on the dom
}
else
{
//element is on the dom
}
答案 6 :(得分:7)
最简单的解决方案是检查baseURI属性,该属性仅在元素插入DOM时设置,并在删除时恢复为空字符串。
var div = document.querySelector('div');
// "div" is in the DOM, so should print a string
console.log(div.baseURI);
// Remove "div" from the DOM
document.body.removeChild(div);
// Should print an empty string
console.log(div.baseURI);
<div></div>
答案 7 :(得分:4)
我更喜欢使用node.isConnected
属性(Visit MDN)。
注意:如果该元素也附加到ShadowRoot,则返回true,这可能不是每个人都想要的行为。
示例:
const element = document.createElement('div');
console.log(element.isConnected); // Returns false
document.body.append(element);
console.log(element.isConnected); // Returns true
答案 8 :(得分:3)
jQuery解决方案:
if ($('#elementId').length) {
// element exists, do something...
}
这对我使用jQuery很有用,并且不需要使用$('#elementId')[0]
。
答案 9 :(得分:3)
csuwldcat's solution似乎是最好的,但需要稍加修改才能使其与运行javascript的文档中的元素正常工作,例如iframe:
YOUR_ELEMENT.ownerDocument.body.contains(YOUR_ELEMENT);
请注意元素的ownerDocument
属性的使用,而不是简单的'document
(可能会或可能不会引用元素的所有者文档)。
torazaburo发布了一个even simpler method,它也适用于非本地元素,但不幸的是,它使用了baseURI
属性,此时浏览器并不统一实现(我只能将它转换为在基于webkit的工作中工作)。我找不到任何其他可以以类似方式使用的元素或节点属性,所以我认为目前上述解决方案是最好的。
答案 10 :(得分:3)
一种简单的检查元素是否存在的方法可以通过jQuery的单行代码完成。
这是下面的代码:
if ($('#elementId').length > 0) {
// do stuff here if element exists
}else {
// do stuff here if element not exists
}
答案 11 :(得分:2)
最简单的方法:
cond = document.getElementById('elem') || false
if (cond) {
//does
} else {
//does not
}
如果在严格可见的 DOM 中需要,这意味着不是在整个页面上,请使用类似 view-js 的东西(我的库,所以随心所欲地击败它)
<script src='https://view-js.glitch.me/view-main.js'></script>
<script>
elem = $sel('#myelem');
if (isVis(elem)) { //yes } else { //no }
</script>
function test() {
pt = document.querySelector('#result')
iv = document.querySelector('#f')
cond = document.querySelector('#'+iv.value) || false
if (cond) {
pt.innerText = 'Found!'
} else {
pt.innerText = 'Not found!'
}
}
Enter an id to see if it exists: <input id='f'></input>
<button onclick='test()'>Test!</button>
<br />
<p id='result'>I am a p tag. I will change depending on the result.</p>
<br />
<div id='demo'>I am a div. My id is demo.</div>
答案 12 :(得分:2)
另一个选项element.closest:
element.closest('body') === null
答案 13 :(得分:1)
而不是迭代父级,你可以获得当元素与dom分离时全部为零的边界矩形
function isInDOM(element) {
if (!element) return false;
var rect=element.getBoundingClientRect();
return (rect.top || rect.left || rect.height || rect.width)?true:false;
}
如果你想在零顶部和零左边处理零宽度和高度元素的边缘情况,你可以通过迭代父级直到document.body
进行双重检查。function isInDOM(element) {
if (!element) return false;
var rect=element.getBoundingClientRect();
if (element.top || element.left || element.height || element.width) return true;
while(element) {
if (element==document.body) return true;
element=element.parentNode;
}
return false;
}
答案 14 :(得分:1)
您还可以使用jQuery.contains
来检查元素是否是另一个元素的后代。我传入document
作为要搜索的父元素,因为页面DOM上存在的任何元素都是document
的后代。
jQuery.contains( document, YOUR_ELEMENT)
答案 15 :(得分:1)
// this will work prefect in all :D
function basedInDocument(el) {
// this function use for checking if this element in a real DOM
while (el.parentElement != null) {
if (el.parentElement == document.body) {
return true;
}
el = el.parentElement; // for check parent of
} // if loop break will return false mean element not in real DOM
return false;
}
答案 16 :(得分:1)
这种情况在所有情况下都是小鸡。
function del() {
//chick if dom has this element
//if not true condition means null or undifind or false .
if (!document.querySelector("#ul_list ")===true){
// msg to user
alert("click btn load ");
// if console chick for you and show null clear console.
console.clear();
// the function will stop.
return false;
}
// if its true function will log delet .
console.log("delet");
}
答案 17 :(得分:1)
我喜欢这种方法
var elem = document.getElementById('elementID');
if( elem )do this
else
do that
另外
var elem = ((document.getElementById('elemID')) ? true:false);
if( elem ) do this
else
do that
答案 18 :(得分:1)
使用jQuery的简单解决方案
$('body').find(yourElement)[0] != null
答案 19 :(得分:0)
将querySelectorAll
与forEach
一起使用:
document.querySelectorAll('.my-element').forEach((element) => {
element.classList.add('new-class');
});
相反:
const myElement = document.querySelector('.my-element');
if (myElement) {
element.classList.add('new-class');
}
答案 20 :(得分:0)
尝试一下,这是最可靠的解决方案:
window.getComputedStyle(x).display == ""
即:
var x = document.createElement("html")
var y = document.createElement("body")
var z = document.createElement("div")
x.appendChild(y);
y.appendChild(z);
z.style.display = "block";
console.log(z.closest("html") == null);//false
console.log(z.style.display);//block
console.log(window.getComputedStyle(z).display == "");//true
答案 21 :(得分:0)
通过Node::contains()
检查元素是否为<html>
的子元素:
const div = document.createElement('div');
document.documentElement.contains(div); //-> false
document.body.appendChild(div);
document.documentElement.contains(div); //-> true
我已经在is-dom-detached中介绍了这一点以及更多内容。
答案 22 :(得分:0)
除HTML元素外,所有现有元素均已设置parentElement!
function elExists (e) {
return (e.nodeName === 'HTML' || e.parentElement !== null);
};
答案 23 :(得分:0)
此代码对我有用,并且没有问题。
const
答案 24 :(得分:0)
检查元素是否存在
mapping <- function(data, col, old, new) {
data[[col]] <- dplyr::recode(data[[col]], !!!setNames(new, old))
data
}
mapping(df, "id", c(2, 3), c(7L, 8L))
# id value
#1 1 1
#2 7 1
#3 8 1
#4 4 1
#5 5 1
答案 25 :(得分:0)
因为这个问题,我来到了这里。上面的解决方案很少能解决问题。经过几次查找,我在互联网上找到了一个解决方案,该解决方案提供当前视口中是否存在节点,我尝试解决的答案是否存在于正文中。
function isInViewport(element) {
const rect = element.getBoundingClientRect();
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
rect.right <= (window.innerWidth || document.documentElement.clientWidth)
);
}
isInViewport(document.querySelector('.selector-i-am-looking-for'));
该片段取自 HERE 以作为备份保存,因为链接可能会在一段时间后不可用。检查链接以获取解释。
而且,不打算在评论中发帖,因为在大多数情况下,它们会被忽略。
答案 26 :(得分:-1)
使用此:
var isInDOM = function(element, inBody) {
var _ = element, last;
while (_) {
last = _;
if (inBody && last === document.body) { break;}
_ = _.parentNode;
}
return inBody ? last === document.body : last === document;
};
答案 27 :(得分:-1)
在下面使用此命令返回DOM中是否存在该元素:
return !!document.getElementById('myElement');