How to insertBefore() element in body tag?

How to insertBefore() element in body tag?

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

Solutions/Answers:

Solution 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 🙂

Solution 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.

Related:  Npm install cannot find module 'semver'

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

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

Links: developer.mozilla.orgPolyfill

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

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

References