如何修复未捕获的类型错误:无法读取 null 的属性“href”

Joh*_*hay 5 html javascript

看来,当我调用 if (test.href != " https://www.test.com ") 时,它给了我一个空值,但我不太确定为什么,因为我期望它返回网址

超文本标记语言

<p><a id="damn" href="https://www.test.com" target="_self">PC Install</a></p>
Run Code Online (Sandbox Code Playgroud)

JS 脚本:

var test= document.getElementById("damn");
if (test.href != "https://www.test.com") {console.log(test)}
Run Code Online (Sandbox Code Playgroud)

Jac*_*ord 1

使用getAttribute,它就有效了。

var test = document.getElementById("damn");
if (test.getAttribute("href") != "https://www.test.com") {
  console.log(test)
}
Run Code Online (Sandbox Code Playgroud)
<p><a id="damn" href="https://www.test.com" target="_self">PC Install</a></p>
Run Code Online (Sandbox Code Playgroud)