向 DOM 添加新元素时出现问题
Problems adding a new element to the DOM?
试图向 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
这是你想要的:
<html>
<head>
<script>
var newElement = document.createElement("pre");
var newText = document.createTextNode("Contents of the element");
newElement.appendChild(newText);
document.body.appendChild(newElement);
</script>
</head>
<body>
<p>Welcome</p>
</body>
这是JSFiddle演示
试试这个新的小提琴: http://jsfiddle.net/pRVAd/1/
<html>
<head>
<script>
function doTheThing() {
var newElement = document.createElement("pre");
var newText = document.createTextNode("Contents of the element");
newElement.appendChild(newText);
document.getElementsByTagName("body")[0].appendChild(newElement);
}
</script>
</head>
<body>
<input type="button" value="Do The Thing" onclick="doTheThing()">
<p>Welcome</p>
</body>
<html>
正确的 sintax 是:document.getElementsByTagName("TagName")[index]
<html>
<head>
<script>
// This function will be executed once that the DOM tree is finalized
// (the page has finished loading)
window.onload = function() {
var newElement = document.createElement("pre");
var newText = document.createTextNode("Contents of the element");
newElement.appendChild(newText);
// You have to use document.body instead of document.getElementsByTag("body")
document.body.appendChild(newElement);
}
</script>
</head>
<body>
<p>Welcome</p>
</body>
</html>
window.onload
以及如何正确使用它。
document.body
相关文章:
- Small Javascript从动态表单中删除多个元素的问题
- 使用javascript删除元素时出现的问题
- 获取要引发的fadeIn元素时出现问题
- 使用AngularJS UI路由器时出现元素绑定问题
- 访问带有变量的Object元素时出现问题
- 数据互绑定问题:转换器只运行一次,无法绑定元素的 ID
- 在方形空间 (YUI) 上重绘元素时出现问题
- 替换
元素中的特殊字符的问题
- 在自定义元素中扩展 HTMLCanvasElement 问题
- 在具有CONTENT标记的自定义元素中使用SELECT标记时出现问题
- 性能问题:存储对DOM元素的引用与使用选择器相比
- OnMouseMove on body标记导致子下拉元素出现问题
- Javascript连接元素,出现问题
- 包含方法和突出显示元素的问题
- 单击元素时出现问题,这些元素是用.html()添加到页面的
- 将元素推送到嵌套数组的问题
- firefox中的浮动元素问题
- 这种计算画布元素中非白色像素的方法有什么问题
- Scriptaculous排序表和句柄的问题(元素排序不正确)
- 问题元素相同的类