Daniel Fein
Daniel Fein

Reputation: 327

How can I append a node to the beginning of a div in Javascript?

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

Answers (5)

naresh kumar
naresh kumar

Reputation: 2241

you can use javascript insertBefore() method. when you are adding to the dom.

Upvotes: 0

Devang Rathod
Devang Rathod

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

turiyag
turiyag

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

Fr&#233;d&#233;ric Hamidi
Fr&#233;d&#233;ric Hamidi

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

Related Questions