如何在body标签中插入insertBefore()元素?
问题描述:
我正在这样尝试在js中使用insertBefore:
I am trying to use insertBefore in js like this:
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标签中的第一个元素。
But that would add the last p element just before the close of the body tag, how could I use it so it will be added to the top when it opens? So the last element added will be the first element inside the body tag.
我尝试过:
document.body.insertBefore(p, document.getElementsByTagName('body')[0]);
但是萤火虫显示:
未找到节点代码: 8
答
您可以获取 body 元素和 firstChild
属性。然后将其用作参考。
You can get the first child of the body
element with the firstChild
property. Then use it as the reference.
const p = document.createElement("p");
p.textContent = "test1";
document.body.insertBefore(p, document.body.firstChild);
出于某些原因,我对代码进行了现代化处理:)
I modernized your code for reasons :)