Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

dom

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

like image 417
code511788465541441 Avatar asked Nov 16 '25 18:11

code511788465541441


2 Answers

Without using a library, try this:

document.body.insertBefore(document.createElement("div"), document.body.firstChild);
like image 165
Pat Avatar answered Nov 18 '25 09:11

Pat


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]).

like image 37
Matías Fidemraizer Avatar answered Nov 18 '25 09:11

Matías Fidemraizer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!