Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

dom

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 in advance.

like image 410
vitaliy Avatar asked Dec 03 '10 02:12

vitaliy


People also ask

What does insertBefore return?

insertBefore() The insertBefore() method of the Node interface inserts a node before a reference node as a child of a specified parent node. If the given node already exists in the document, insertBefore() moves it from its current position to the new position.

How do you create a new element as a first child to the parent element?

To insert element as a first child using jQuery, use the prepend() method. The prepend( content ) method prepends content to the inside of every matched element.


2 Answers

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);
like image 76
PleaseStand Avatar answered Oct 29 '22 13:10

PleaseStand


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);
like image 41
Alex Avatar answered Oct 29 '22 14:10

Alex