Javascript 使用javascript检查div是否不存在
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10886190/
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
Check if a div does NOT exist with javascript
提问by Wilson
Checking if a div exists is fairly simple
检查 div 是否存在相当简单
if(document.getif(document.getElementById('if')){
}
But how can I check if a div with the given id does not exist?
但是如何检查具有给定 id 的 div 是否不存在?
回答by Jimbo Jonny
var myElem = document.getElementById('myElementId');
if (myElem === null) alert('does not exist!');
回答by Esailija
if (!document.getElementById("given-id")) {
//It does not exist
}
The statement document.getElementById("given-id")
returns null
if an element with given-id
doesn't exist, and null
is falsy meaning that it translates to false when evaluated in an if-statement. (other falsy values)
如果元素不存在,则该语句document.getElementById("given-id")
返回,并且是假的,这意味着在 if 语句中评估时它会转换为假。(其他假值)null
given-id
null
回答by Hristo
Try getting the element with the ID and check if the return value is null:
尝试获取带有 ID 的元素并检查返回值是否为空:
document.getElementById('some_nonexistent_id') === null
If you're using jQuery, you can do:
如果您使用 jQuery,则可以执行以下操作:
$('#some_nonexistent_id').length === 0
回答by Chinmay235
Check both my JavaScript and JQuery code :
检查我的 JavaScript 和 JQuery 代码:
JavaScript:
JavaScript:
if (!document.getElementById('MyElementId')){
alert('Does not exist!');
}
JQuery:
查询:
if (!$("#MyElementId").length){
alert('Does not exist!');
}
回答by SLaks
getElementById
returns null
if there is no such element.
getElementById
null
如果没有这样的元素,则返回。
回答by SLaks
There's an even better solution. You don't even need to check if the element returns null
. You can simply do this:
有一个更好的解决方案。您甚至不需要检查元素是否返回null
。你可以简单地这样做:
if (document.getElementById('elementId')) {
console.log('exists')
}
That code will only log exists
to console if the element actually exists in the DOM.
exists
如果元素确实存在于 DOM 中,那么该代码只会记录到控制台。
回答by Ema.H
That works with :
这适用于:
var element = document.getElementById('myElem');
if (typeof (element) != undefined && typeof (element) != null && typeof (element) != 'undefined') {
console.log('element exists');
}
else{
console.log('element NOT exists');
}
回答by Cyber
I do below and check if id
exist and execute function if exist.
我在下面做并检查是否id
存在并执行函数(如果存在)。
var divIDVar = $('#divID').length;
if (divIDVar === 0){
console.log('No DIV Exist');
} else{
FNCsomefunction();
}
回答by sMyles
All these answers do NOTtake into account that you asked specifically about a DIVelement.
所有这些答案都没有考虑到您专门询问了DIV元素。
document.querySelector("div#the-div-id")
@see https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector
@see https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector