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.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With