简体   繁体   English

使用javascript将div插入dom中?

[英]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? 但我不知道为什么?

You need to wrap your code to window.onload handler: 您需要将代码包装到window.onload处理程序中:

window.onload = function() {
    var new_div = document.createElement("div");
    var app_div = document.getElementById("app");
    document.body.insertBefore(new_div, app_div);
}

Example on jsFiddle . jsFiddle上的示例

除了按照Igor的建议将其更好地包装在onload()之外,您是否不想先将new_div添加到文档中?

document.body.insertBefore(new_div, document.body.firstChild);

尝试使用jquery document.ready事件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM