从<body>获取第一个元素然后insertBefore()

vit*_*liy 8 javascript dom

我已经在这里呆了几个小时了,我即将开始撕头发.基本上我需要做的是获取身体中出现的第一个元素,然后在它之前插入另一个元素.

我已经尝试了以下方法来获取第一个没有成功的元素(undefined或null)

window.document.body.firstChild

document.getElementsByTagName("body").firstChild

document.getElementsByTagName("body")[0].firstChild

window.document.documentElement.childNodes[1].childNodes[0]
Run Code Online (Sandbox Code Playgroud)

以前的片段中有大量混合和匹配的尝试.我也试过让身体然后appendChild()也没有成功.

任何帮助在这里表示赞赏.提前致谢.

Ple*_*and 14

是的,document.body.firstChild是对的.您可能忽略了insertBefore是父元素的方法这一事实,它将在现有元素之前获取新元素.例如:

var addedElement = document.createElement('p');
addedElement.appendChild(document.createTextNode('Hello, world!'));

var body = document.body;
body.insertBefore(addedElement, body.firstChild);
Run Code Online (Sandbox Code Playgroud)


Ale*_*lex 4

你想要这样的东西:

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);
Run Code Online (Sandbox Code Playgroud)