2013-02-11 104 views
0

我目前正在将一个节点追加到一个div的末尾来动态添加到一个div,但我正在寻找将它追加到开头而不是div的结尾。如何在JavaScript中将节点追加到div的开头?

我当前的代码看起来是这样的:

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> 

我如何可以追加到div的开始?

回答

3

您可以使用insertBefore()与父母的firstChild作为参考元素:

var element = document.getElementById("div1"); 
element.insertBefore(para, element.firstChild); 
+0

如果节点/元素是无子的。这将如何工作? – 2013-02-11 06:55:14

+1

@Justin,在这种情况下,firstChild将为null,并且insertBefore()将继续将新元素附加到父元素的末尾(这与开始时相同,因为它是空的) 。 – 2013-02-11 06:56:15

+0

+1感谢您的回复。 – 2013-02-11 07:01:06

0

查找到的jQuery(http://www.jquery.com),因为它会让你的生活只是这么容易得多。其他库存在,但jQuery是最流行的。

您的代码使用jQuery:

$("<div/>").append("this is new").appendTo($("#div1")) 

而对于前面加上:

$("<div/>").prepend("this is new").prependTo($("#div1")) 
0

我不敢肯定,但你可以做这样的事情:

<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> 
0

你可以使用javascript insertBefore()方法。当你添加到DOM。