我正在尝试像这样在 js 中使用 insertBefore:
var p = document.createElement("p");
p.innerHTML = "test1";
document.body.insertBefore(p, null);
var p = document.createElement("p");
p.innerHTML = "test2";
document.body.insertBefore(p, null);
但这会在 body 标记结束之前添加最后一个 p 元素,我如何使用它以便在打开时将其添加到顶部?所以最后添加的元素将是 body 标签内的第一个元素。
我试过:
document.body.insertBefore(p, document.getElementsByTagName('body')[0]);
但是 Firebug 显示:
找不到节点“代码:”8
最佳答案
您可以使用 firstChild
属性获取 body
元素的第一个子元素。然后作为引用。
const p = document.createElement("p");
p.textContent = "test1";
document.body.insertBefore(p, document.body.firstChild);
出于某些原因,我对您的代码进行了现代化改造 :)
关于javascript - 如何在 body 标签中插入 Before() 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6013861/