How to insertBefore() element in body tag?

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


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


Modern Solution - prepend

document.body.prepend(p)

This is vanilla JS and is more readable than previous options. It is currently available in all modern browsers.

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

parent.prepend("This text!")

Related DOM methods

  1. Read More - parent.append
  2. Read More - child.before and child.after
  3. Read More - child.replaceWith

Mozilla Documentation