[英]inserting divs into the dom using javascript?
im trying to insert a new div into the DOM with an id of "app" 我试图将一个新的div插入ID为“ app”的DOM中
var new_div = document.createElement("div");
var app_div = document.getElementById("app");
document.body.insertBefore(new_div, app_div);
this gives me an error in the console: 这在控制台中给了我一个错误:
Uncaught TypeError: Cannot call method 'insertBefore' of null
未捕获的TypeError:无法调用null的方法“ insertBefore”
but i don't know why? 但我不知道为什么?
除了按照Igor的建议将其更好地包装在onload()之外,您是否不想先将new_div添加到文档中?
document.body.insertBefore(new_div, document.body.firstChild);
尝试使用jquery document.ready事件
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.