How to insertBefore() element in body tag?

余生长醉 提交于 2020-02-16 18:37:30

问题


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);

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.

I tried:

document.body.insertBefore(p, document.getElementsByTagName('body')[0]);

But firebug shows:

Node was not found" code: "8


回答1:


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 :)




回答2:


document.body.prepend(p);

This is a new addition in (likely) ES7. It is vanilla JS and is more readable than previous options. It is currently available in 83% of browsers, including Chrome, FF, and Opera.

You can directly prepend strings, although they won't be 'p' tags

document.body.prepend('This text!');

Links: developer.mozilla.org - Polyfill




回答3:


You have to insert before something. document.getElementsByTagName('body')[0] is the body element (the syntax is a bit of a trick to get the body element in all browsers)1. If you want to insert into the body, you want to insert before the first element of it. That could look like this:

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]);

1in some browsers it's document.body, other document.documentElement etc., but in all browsers the tagname is body



来源:https://stackoverflow.com/questions/6013861/how-to-insertbefore-element-in-body-tag

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!