Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
17
rated 0 times [  22] [ 5]  / answers: 1 / hits: 80781  / 13 Years ago, mon, may 16, 2011, 12:00:00

I am trying to use insertBefore in js like this:



var p = document.createElement(p);
p.innerHTML = test1;
document.body.insertBefore(p, null);

var p = document.createElement(p);
p.innerHTML = test2;
document.body.insertBefore(p, null);


But that would add the last p element just before the close of the body tag, how could I use it so it will be added to the top when it opens? So the last element added will be the first element inside the body tag.



I tried:



document.body.insertBefore(p, document.getElementsByTagName('body')[0]);


But firebug shows:



Node was not found code: 8


More From » dom

 Answers
25

You can get the first child of the body element with the firstChild property. Then use it as the reference.





const p = document.createElement(p);
p.textContent = test1;
document.body.insertBefore(p, document.body.firstChild);





I modernized your code for reasons :)


[#92225] Friday, May 13, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
victorr

Total Points: 193
Total Questions: 86
Total Answers: 105

Location: Pitcairn Islands
Member since Thu, Jun 24, 2021
3 Years ago
;