59

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

slemdx
  • 1,055
  • 2
  • 16
  • 19
  • Try out document.body.prepend. Also, it is generally good practice to not set innerHTML. Use `oldNode.replaceWith(newNode)` or set `oldNode.innerText` – Gibolt Aug 07 '17 at 23:49
  • @Gibolt `textContent` should be preferred for setting text. – alex Apr 11 '19 at 09:49

4 Answers4

105

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

alex
  • 479,566
  • 201
  • 878
  • 984
  • You should not push text to an element with `innerHTML`. Use `textContet` instead. – Persijn Apr 10 '19 at 12:16
  • @Persijn It was for an example only, and back in 2011 you had to use `textContent` or `innerText` in IE, so this was more convenient. – alex Apr 10 '19 at 16:14
  • agread, but i commented it since we no longer do this. Could you change/edit it? – Persijn Apr 11 '19 at 08:24
  • @Persijn It's literally the code from the OP's question, but yes I can change it – alex Apr 11 '19 at 09:47
  • Don't we answers question for the community? And not for a single user? We are not a helping service. – Persijn Apr 11 '19 at 12:53
14

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

Gibolt
  • 42,564
  • 15
  • 187
  • 127
2

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

KooiInc
  • 119,216
  • 31
  • 141
  • 177
  • 1
    Which browsers don't support `document.body`? – alex Aug 29 '11 at 07:06
  • 1
    @alex you're right, every browser seems to support it. I think it's a trace in my memory from a long gone past. – KooiInc Aug 29 '11 at 09:36
  • 1
    @Kooilnc Thanks for getting back to me, I have a lot of `document.body` in the wild and was a little worried :P – alex Aug 29 '11 at 09:52
0

let li = document.querySelectorAll("li");
let newli = document.createElement("li");
newli.innerText = "7";
li[6].before(newli); //this work as insertBefore()this line add 7 before 8
//li[5].after(newli);
<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
  <li>6</li>
  <li>8</li>
  <li>9</li>
  <li>10</li>
</ul>
  • Thank you for this code snippet, which might provide some limited, immediate help. A proper [explanation](https://meta.stackoverflow.com/questions/392712/explaining-entirely-code-based-answers) would greatly improve its long-term value by showing why this is a good solution to the problem and would make it more useful to future readers with other, similar questions. Please [edit](https://stackoverflow.com/posts/67831977/edit) your answer to add some explanation, including the assumptions you’ve made – Dmitriy Jun 04 '21 at 07:39