簡體   English   中英

如何在文檔上的其他內容之前插入元素?

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

我不認為我可以使用insertBefore()因為我不知道DOM中的第一個元素。

編輯:

我正在嘗試插入一個body標簽(即<body> )。

不使用庫,試試這個:

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

好吧,但你可以隨時查看:

  • 如果文檔正文至少有一個子 document.body.insertBefore([the new element], document.body.firstChild) ,請使用document.body.insertBefore([the new element], document.body.firstChild)

  • 如果文檔正文沒有子 document.body.appendChild([the new element]) ,只需使用document.body.appendChild([the new element])

文檔中的第一個元素是document.body.children[0]

使用prepend()將元素添加到容器(主體)的開頭。 http://api.jquery.com/prepend/

$('body').prepend()

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

那里。 只需使用body標簽包含當前HTML。

使用.insertBefore()方法

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM