1. 程式人生 > >js動態新增div(一)

js動態新增div(一)

利用JavaScript動態新增Div的方式有很多,一下是個比較常用的。

一、在一個Div前新增Div

<html>
  <body>
  <div   id="a">  
   <div   id="a1">1</div>
   <div   id="a2">2</div>  
  </div>  
        <a href="javascript:addDiv();">test</a>                         
  </body>
<script   type="text/javascript">  
 function addDiv(){
        var   newNode=document.createElement("div");  
        newNode.setAttribute("id","a3");  
        var   txtNode=document.createTextNode("3");  
        newNode.appendChild(txtNode);  
         
        document.getElementById("a").insertBefore(newNode,document.getElementById("a2"));  
         
        alert(document.getElementById("a").innerHTML)  
}
 </script>  
</html>