有没有 document.getElementById('element');将 return 未定义

is there a case when document.getElementById('element'); will return undefined

根据我的理解和一点经验,document.getElementById('element');将 return 元素(如果存在)否则 return null(如果不存在)。 所以无论如何它都不会 return undefined 我想从专家那里确认这些,因此在这里向专家社区询问 谢谢

不,它总是 return null 或 DOM 元素。它不能 return undefined.

参见 W3C DOM spec:

Returns the Element that has an ID attribute with the given value. If no such element exists, this returns null.

请注意,该规范还说明了这一点:

If more than one element has an ID attribute with that value, what is returned is undefined.

这并不意味着它会 return undefined,它只是意味着当多个元素具有给定 ID 时调用 getElementById 会调用 未定义的行为。但是,即使在那种情况下,也没有实现 return 除了元素或 null 之外的任何东西。

如上评论所述:

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8" />
  <title>Test Page</title>
 <script type="text/javascript" id="UN">
//<!--
var a, b, undef;

function testthis()
{ a=document.getElementById("UN");
  //COULD now do: b=a.undef;
  b=document.getElementById("UN").undef;
  //If you set a breakpoint where you can examine b
  // its value will be undefined
  return;
}

//-->
 </script>
</head>
<body onload="testthis();">
test page
</body>
</html>

可以指出我们正在处理对象;如果找不到 ID(没有对象具有该 ID),document.getElementById() 函数将 return null,如果可以找到 ID,则 return 一个对象。没有同时具有 ID 的对象这样的东西,但在其他方面是 "undefined"——尽管正如这个测试代码所示,一个对象可能包含一些未定义的东西(比如那个 undef 变量)。