如何在body标签中插入insertBefore()元素? [英] How to insertBefore() element in body tag?
本文介绍了如何在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
推荐答案
您可以获取<$ c的第一个孩子$ c> 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 :)
这篇关于如何在body标签中插入insertBefore()元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文