Reputation: 21901
I don't think I can use insertBefore()
because I do not know what element will be first in the DOM.
I am trying to insert a body tag (i.e. <body>
).
Upvotes: 3
Views: 970
Reputation: 16210
document.body.innerHTML = '<body>'+document.body.innerHTML+'</body>';
There. Simply envelops the current HTML with the body tag.
Upvotes: 0
Reputation: 2435
Use .insertBefore() method
document.body.insertBefore(newNode, document.body.children[0])
Upvotes: 0
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
Reputation: 2238
Without using a library, try this:
document.body.insertBefore(document.createElement("div"), document.body.firstChild);
Upvotes: 5
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
Reputation: 22951
The first element in the document will be document.body.children[0]
.
Upvotes: 2