附加< li>项目to< ul>与TS
我一直在尝试将“鳄梨”附加到此列表中,但是后来我得到了错误消息
und> typeError:无法读取null的属性(读取'appendchild')
<!DOCTYPE html >
<html lang="de">
<head >
<title >Am I Loaded ?! </title >
<script>
const element = document.getElementById("list")
const elementText = document.createTextNode("Avocado")
element.appendChild(elementText);
</script>
</head>
<body>
<h1>Meine Obstschale</h1>
<ul id="list">
<li >Apple </li >
<li >Pear </li >
<li >Orange </li >
<li >Banana </li >
</ul >
</body >
</html>
我在这里做错了什么?
I have been trying to append "Avocado" to this list but then I get the error message
Uncaught TypeError: Cannot read properties of null (reading 'appendChild')
<!DOCTYPE html >
<html lang="de">
<head >
<title >Am I Loaded ?! </title >
<script>
const element = document.getElementById("list")
const elementText = document.createTextNode("Avocado")
element.appendChild(elementText);
</script>
</head>
<body>
<h1>Meine Obstschale</h1>
<ul id="list">
<li >Apple </li >
<li >Pear </li >
<li >Orange </li >
<li >Banana </li >
</ul >
</body >
</html>
What am I doing wrong here, please?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
该错误告诉您您正在尝试在空对象上调用成员函数
附录
。这不起作用,因为空对象上没有成员功能。在您的代码中,您仅调用appendchild
一次,这意味着element
是该空对象。知道这一点,您可以看到getElementById
返回该空对象。您的ID不存在,或者尚未加载。tl; dr;在加载页面元素之前,您正在运行JavaScript。
您可以将脚本立即放置在关闭
body
之前,以规避此问题。The error tells you that you are trying to invoke the member function
appendChild
on a null object. This does not work because there are no member functions on a null object. In your code you only invokeappendChild
once, which means thatelement
is that null object. Knowing this, you can see thatgetElementById
returned that null object. Either your ID does not exist or it is not loaded yet.tl;dr; You are running that Javascript before the elements of your page are loaded.
You can place your script right before the closing
body
to circumvent this.