尝试向 DOM 添加新元素,但根据我尝试执行的操作,我会收到各种错误。
<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/