文档.如果未定义元素,getelementbyId将返回null

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

本文关键字:返回 null getelementbyId 如果 未定义 元素 文档      更新时间:2023-09-26

在我的代码中,我看到:

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

如果xx元素没有定义,它的值是真还是假?

我应该写:

if (document.getElementById('xx'))

要安全?

console.log(document.getElementById('xx') ) evaluates to null.
document.getElementById('xx') !=null evaluates to false

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

getElementById由DOM Level 1 HTML定义,在没有匹配到任何元素的情况下返回null

!==null是最显式的检查形式,而且可能是最好的,但是getElementById不能返回非null的假值——您只能得到null或一个始终为真的Element对象。因此,!==null, !=null或更宽松的if (document.getElementById('xx'))之间没有实际的区别。

是的,如果它不存在,它将返回null,您可以在下面的演示中尝试。两者都将返回true。第一个元素存在,第二个元素不存在。

<div id="xx"></div>
Javascript:

   if (document.getElementById('xx') !=null) 
     console.log('it exists!');
   if (document.getElementById('xxThisisNotAnElementOnThePage') ==null) 
     console.log('does not exist!');