gpt4 book ai didi

javascript - 向 DOM 添加新元素时遇到问题?

转载 作者:行者123 更新时间:2023-11-28 21:03:29 24 4
gpt4 key购买 nike

尝试向 DOM 添加新元素,但根据我尝试执行的操作,我会收到各种错误。

http://jsfiddle.net/pRVAd/

<html>
<head>
<script>
var newElement = document.createElement("pre");
var newText = document.createTextNode("Contents of the element");
newElement.appendChild(newText);
document.getElementsByTag("body").appendChild(newElement);
</script>
</head>
<body>
<p>Welcome</p>
</body>

</html>​

最佳答案

脚本位于 <head>并且您的代码立即运行(这不是延迟的函数调用)。 <body>当您尝试运行它时它不存在。

将脚本移至 </body> 之前 或将其移至函数中并命名为 onload .

getElementsByTag不是 document 上的方法目的。您可能是说 getElementsByTagName但它返回一个 NodeList,而不是 HTMLElementNode。这就像一个数组。您需要将第一个项目从其上拉下来,或者更好:

使用document.body

关于javascript - 向 DOM 添加新元素时遇到问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10448718/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com