开发者

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

开发者 https://www.devze.com 2023-03-29 22:22 出处:网络
I don\'t think I can use insertBefore() because I do not know what element will be first in the DOM. Edit:

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


Without using a library, try this:

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


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


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


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

$('body').prepend()


Use .insertBefore() method

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


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

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

0

精彩评论

暂无评论...
验证码 换一张
取 消