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

sle*_*mdx 46 javascript dom insert getelementsbytagname

我试图在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);
Run Code Online (Sandbox Code Playgroud)

但是这会在body标签关闭之前添加最后一个p元素,我怎么能使用它以便在打开时添加到顶部?所以添加的最后一个元素将是body标签内的第一个元素.

我试过了:

document.body.insertBefore(p, document.getElementsByTagName('body')[0]);
Run Code Online (Sandbox Code Playgroud)

但是萤火虫表明:

找不到节点"代码:"8

ale*_*lex 78

您可以body使用该firstChild属性获取元素的第一个子元素.然后用它作为参考.

const p = document.createElement("p");
p.textContent = "test1";
document.body.insertBefore(p, document.body.firstChild);
Run Code Online (Sandbox Code Playgroud)
const p = document.createElement("p");
p.textContent = "test1";
document.body.insertBefore(p, document.body.firstChild);
Run Code Online (Sandbox Code Playgroud)


Gib*_*olt 6

document.body.prepend(p);
Run Code Online (Sandbox Code Playgroud)

这是(可能)ES7中的新增功能。它是Vanilla JS,比以前的选项更具可读性。目前,有83%的浏览器都可以使用它,包括Chrome,FF和Opera。

您可以直接在字符串前面加上前缀,尽管它们不会是'p'标签

document.body.prepend('This text!');
Run Code Online (Sandbox Code Playgroud)

链接:developer.mozilla.org - Polyfill