[英]DOM Error with javascript appending
使用此代码
var html='<div class="somediv"></div>';
var target=document.getElementById('contentArea');
target.appendChild(html);
我越来越
Uncaught Error: NOT_FOUND_ERR: DOM Exception 8
Uncaught TypeError: Cannot call method 'appendChild' of null
有什么建议吗?
不能肯定地说,因为您没有提供要选择的DOM,但是我猜想您是在contentArea
元素存在之前运行脚本的。
如果是这样,请将您的脚本放在body
元素的末尾。
<head>
...
</head>
<body>
<div id="contentArea">
...
</div>
<script type="text/javascript">
// your script here
</script>
</body>
或者,只需将所有内容包装在内:
window.onload = function(){
// your script here
}
没有直接关系,但是您不应该将HTML字符串传递给appendChild
。 您应该创建一个DOM节点,并将其附加。
var target=document.getElementById('contentArea');
target.appendChild(document.createElement('div')).className = 'somediv';
在执行DOM操作时,在保留元素之前,请确保已加载这些元素。 将脚本放到底部,就在</body>
标签之前
//all other HTML up here
<script>
var html=document.createElement('div');
html.className = 'somediv';
var target=document.getElementById('contentArea');
target.appendChild(html);
</script>
</body>
或者您可以使用window.onload
运行脚本
load
事件在文档加载过程结束时触发。 此时,文档中的所有对象都在DOM中,并且所有图像和子帧均已完成加载。
window.onload = function() {
var html=document.createElement('div');
html.className = 'somediv';
var target=document.getElementById('contentArea');
target.appendChild(html);
}
var target=document.getElementById('contentArea');
找不到ID为contentArea
的元素。 您可以张贴其余代码吗?
我遇到了相同的错误Uncaught Error: NOT_FOUND_ERR: DOM Exception 8
试图将jQuery对象数组添加到DOM元素。 我发现该规范允许您在DOM元素数组之前添加jQuery对象数组。
阅读此: http : //bugs.jquery.com/ticket/11231了解详细信息
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.