124697
124697

Reputation: 21901

How do I insert an element before everything else on a document?

I don't think I can use insertBefore() because I do not know what element will be first in the DOM.

Edit:

I am trying to insert a body tag (i.e. <body>).

Upvotes: 3

Views: 970

Answers (6)

Some Guy
Some Guy

Reputation: 16210

document.body.innerHTML = '<body>'+document.body.innerHTML+'</body>';

There. Simply envelops the current HTML with the body tag.

Upvotes: 0

ant_Ti
ant_Ti

Reputation: 2435

Use .insertBefore() method

document.body.insertBefore(newNode, document.body.children[0])

Upvotes: 0

Mat&#237;as Fidemraizer
Mat&#237;as Fidemraizer

Reputation: 64943

Well, but you can always check this:

  • If document body has at least one child, use document.body.insertBefore([the new element], document.body.firstChild)

  • If document body has no children, just use document.body.appendChild([the new element]).

Upvotes: 4

Pat
Pat

Reputation: 2238

Without using a library, try this:

document.body.insertBefore(document.createElement("div"), document.body.firstChild);

Upvotes: 5

js1568
js1568

Reputation: 7032

Use prepend() to add an element to the beginning of a container (the body). http://api.jquery.com/prepend/

$('body').prepend()

Upvotes: 0

bjornd
bjornd

Reputation: 22951

The first element in the document will be document.body.children[0].

Upvotes: 2

Related Questions