开发者

Getting the first element from <body> then insertBefore()

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.

Any help here is appreciated. Thanks 开发者_如何学Goin advance.


Yes, document.body.firstChild is correct. It's likely that you are overlooking the fact that insertBefore is a method of the parent element, and it takes the new element before the existing one. For example:

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

var body = document.body;
body.insertBefore(addedElement, body.firstChild);


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


The most elegant solution to prepend an element to the body I could up with is a one-liner:

document.body.insertBefore(element, dom.document.body.firstChild)
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜