javascript 从 <body> 获取第一个元素然后 insertBefore()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4341875/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting the first element from <body> then insertBefore()
提问by vitaliy
I've been at this for a few hours now and am about to start ripping hair out. Basically what I need to do is get the first element that appears in the body and then insert another element before it.
我已经在这里呆了几个小时了,我即将开始撕掉头发。基本上我需要做的是获取出现在正文中的第一个元素,然后在它之前插入另一个元素。
I've tried the following to get the first element with no success (undefined or null)
我尝试了以下方法来获取第一个元素但没有成功(未定义或为空)
window.document.body.firstChild
document.getElementsByTagName("body").firstChild
document.getElementsByTagName("body")[0].firstChild
window.document.documentElement.childNodes[1].childNodes[0]
And a whole slew of mixed and matched attempts of the previous snippets. I've also tried just getting the body then appendChild() with no success either.
以及之前片段的大量混合和匹配尝试。我也试过只获取身体然后 appendChild() 也没有成功。
Any help here is appreciated. Thanks in advance.
任何帮助在这里表示赞赏。提前致谢。
回答by PleaseStand
Yes, document.body.firstChildis correct. It's likely that you are overlooking the fact that insertBeforeis a method of the parent element, and it takes the new element before the existing one. For example:
是的,document.body.firstChild是正确的。您可能忽略了一个事实,即insertBefore是父元素的一种方法,它在现有元素之前采用新元素。例如:
var addedElement = document.createElement('p');
addedElement.appendChild(document.createTextNode('Hello, world!'));
var body = document.body;
body.insertBefore(addedElement, body.firstChild);
回答by Alex
You want something like this:
你想要这样的东西:
var first = document.body.children[0];
var beforeEle = document.createElement("div");
beforeEle.innerHTML = "I'm the first element in the body!";
document.body.insertBefore(beforeEle, first);
回答by Lichtbringer
The most elegant solution to prepend an element to the body I could up with is a one-liner:
将元素添加到我能想到的 body 的最优雅的解决方案是单行:
document.body.insertBefore(element, dom.document.body.firstChild)

