Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 890
slemdx Avatar asked May 16 '11 06:05

slemdx


People also ask

How do you use insertBefore?

How it works. First, get the menu element using the getElementById() method. Second, create a new list item using the createElement() method. Third, insert the list item element before the first child element of the menu element using the insertBefore() method.

How does insertBefore work in Javascript?

The insertBefore() method of the Node interface inserts a node before a reference node as a child of a specified parent node. If the given node already exists in the document, insertBefore() moves it from its current position to the new position.


2 Answers

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

like image 107
alex Avatar answered Oct 05 '22 16:10

alex


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

like image 37
Gibolt Avatar answered Oct 05 '22 16:10

Gibolt