Reputation: 327
I am currently appending a node to the end of a div to dynamically add to a div but I am looking to append it to the beginning rather than the end of the div.
my current code looks like this:
var para=document.createElement('div');
var node=document.createTextNode('this is new');
para.appendChild(node);
var element=document.getElementById("div1");
element.appendChild(para);
<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
How can I append to the beginning of the div?
Upvotes: 1
Views: 11790
Reputation: 2241
you can use javascript insertBefore() method. when you are adding to the dom.
Upvotes: 0
Reputation: 6736
i m not sure but you can do something like this :
<script type="text/javascript">
window.onload=function(){
dv=document.createElement('div1');
txt=document.createTextNode('this is new');
dv.appendChild(txt);
document.getElementById('div1').appendChild(dv);
}
</script>
Upvotes: 0
Reputation: 2887
Look into jQuery (http://www.jquery.com) because it'll make your life just so much easier. Other libraries exist, but jQuery is the most popular.
Your code with jQuery:
$("<div/>").append("this is new").appendTo($("#div1"))
And for prepending:
$("<div/>").prepend("this is new").prependTo($("#div1"))
Upvotes: 2
Reputation: 262919
You can use insertBefore() with the parent's firstChild as the reference element:
var element = document.getElementById("div1");
element.insertBefore(para, element.firstChild);
Upvotes: 5