javascript 如果元素未定义,document.getelementbyId 将返回 null?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15666163/
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
document.getelementbyId will return null if element is not defined?
提问by Victor
In my code, I see this:
在我的代码中,我看到了这个:
if (document.getElementById('xx') !=null) {
//do stuff
}
if xx
element is not defined, will this evaluate to true or false?
如果xx
元素未定义,这将评估为真还是假?
Should I write:
我应该写:
if (document.getElementById('xx'))
to be safe?
安全吗?
回答by Garrett
console.log(document.getElementById('xx') ) evaluates to null.
document.getElementById('xx') !=null evaluates to false
You should use document.getElementById('xx') !== null
as it is a stronger equality check.
您应该使用document.getElementById('xx') !== null
它,因为它是一种更强的相等性检查。
回答by bobince
getElementById
is defined by DOM Level 1 HTMLto return null
in the case no element is matched.
getElementById
由DOM Level 1 HTML定义null
在没有元素匹配的情况下返回。
!==null
is the most explicit form of the check, and probably the best, but there is no non-null
falsy value that getElementById
can return - you can only get null
or an always-truthy Element object. So there's no practical difference here between !==null
, !=null
or the looser if (document.getElementById('xx'))
.
!==null
是最明确的检查形式,也可能是最好的形式,但没有可以返回的非null
虚假值getElementById
- 您只能获取null
或始终为真的 Element 对象。所以这里没有实际区别!==null
,!=null
或者更宽松的if (document.getElementById('xx'))
.
回答by Peter Rasmussen
Yes it will return null if it's not present you can try this below in the demo. Both will return true. The first elements exists the second doesn't.
是的,如果它不存在,它将返回 null 你可以在下面的演示中尝试这个。两者都将返回 true。第一个元素存在,第二个不存在。
Html
html
<div id="xx"></div>
Javascript:
Javascript:
if (document.getElementById('xx') !=null)
console.log('it exists!');
if (document.getElementById('xxThisisNotAnElementOnThePage') ==null)
console.log('does not exist!');