如何在body标签中插入insertBefore()元素?

| 我正在尝试在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]);
但是萤火虫显示: 找不到节点\“代码:\” 8     
已邀请:
您可以使用
firstChild
属性获得
body
元素的第一个孩子。然后将其用作参考。
const p = document.createElement(\"p\");
p.textContent = \"test1\";
document.body.insertBefore(p, document.body.firstChild);
document.body.prepend(p);
这是(可能)ES7中的新增功能。它是Vanilla JS,比以前的选项更具可读性。目前,有83%的浏览器都可以使用它,包括Chrome,FF和Opera。 您可以直接在字符串前添加前缀,尽管它们不会是\'p \'标签
document.body.prepend(\'This text!\');
链接:developer.mozilla.org-Polyfill     
您必须在某些内容之前插入。
document.getElementsByTagName(\'body\')[0]
是body元素(语法是在所有浏览器中获取body元素的技巧)1。如果要插入主体,则要插入主体的第一个元素之前。可能看起来像这样:
var body   = document.body || document.getElementsByTagName(\'body\')[0],
    newpar = document.createElement(\'p\');
newpar.innerHTML = \'Man, someone just created me!\';
body.insertBefore(newpar,body.childNodes[0]);
1在某些浏览器中为
document.body
,在其他浏览器中为
document.documentElement
等,但在所有浏览器中,标记名均为
body
    

要回复问题请先登录注册