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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 01:36:41  来源:igfitidea点击:

document.getelementbyId will return null if element is not defined?

javascriptdomdocument

提问by Victor

In my code, I see this:

在我的代码中,我看到了这个:

if (document.getElementById('xx') !=null) {
    //do stuff
}

if xxelement 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') !== nullas it is a stronger equality check.

您应该使用document.getElementById('xx') !== null它,因为它是一种更强的相等性检查。

回答by bobince

getElementByIdis defined by DOM Level 1 HTMLto return nullin the case no element is matched.

getElementByIdDOM Level 1 HTML定义null在没有元素匹配的情况下返回。

!==nullis the most explicit form of the check, and probably the best, but there is no non-nullfalsy value that getElementByIdcan return - you can only get nullor an always-truthy Element object. So there's no practical difference here between !==null, !=nullor 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。第一个元素存在,第二个不存在。

Demo

演示

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!');