js操作DOM--添加、刪除節(jié)點(diǎn)的簡(jiǎn)單實(shí)例

字號(hào):


    下面小編就為大家?guī)硪黄猨s操作DOM--添加、刪除節(jié)點(diǎn)的簡(jiǎn)單實(shí)例。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。
    js removeChild() 用法
    <body> 
    <p id="p1">welcome to <b>javascript</b> world !</p> 
    <script language="javascript" type="text/javascript"> 
    <!-- 
    function nodestatus(node) 
    { 
     var temp=""; 
     if(node.nodeName!=null) 
     { 
      temp+="nodeName="+node.nodeName+"\n"; 
     } 
     else temp+="nodeName=null \n"; 
     if(node.nodeType!=null) 
     { 
      temp+="nodeType="+node.nodeType+"\n"; 
     } 
     else temp+="nodeType=null \n"; 
     if(node.nodeValue!=null) 
     { 
      temp+="nodeValue="+node.nodeValue+"\n"; 
     } 
     else temp+="nodeValue=null \n"; 
     return temp; 
    } 
    var parent=document.getElementById("p1"); 
    var msg="父節(jié)點(diǎn) \n"+nodestatus(parent)+"\n"; 
    //返回元素節(jié)點(diǎn)p的最后一個(gè)孩子 
    last=parent.lastChild; 
    msg+="刪除之前:lastChild--"+nodestatus(last)+"\n"; 
    //刪除節(jié)點(diǎn)p的最后一個(gè)孩子,變?yōu)閎 
    parent.removeChild(last); 
    last=parent.lastChild; 
    msg+="刪除之后:lastChild--"+nodestatus(last)+"\n"; 
    alert(msg); 
    --> 
    </script> 
    </body> 
    --------------------------------------------------------------
    <html>
    <head>
    <title>js控制添加、刪除節(jié)點(diǎn)</title>
    </head>
    <script type="text/javascript">
      var all;
      function addParagraph() {
        all = document.getElementById("paragraphs").childNodes;
        var newElement = document.createElement("p");
        var seq = all.length + 1;
        //創(chuàng)建新屬性
        var newAttr = document.createAttribute("id");
        newAttr.nodeValue = "p" + seq;
        newElement.setAttribute(newAttr);
        //創(chuàng)建文本內(nèi)容
        var txtNode = document.createTextNode("段落" + seq);
        //添加節(jié)點(diǎn)
        newElement.appendChild(txtNode);
        document.getElementById("paragraphs").appendChild(newElement);
      }
      function delParagraph() {
        all = document.getElementById("paragraphs").childNodes;
        document.getElementById("paragraphs").removeChild(all[all.length -1]);
      }
    </script>
    <style>
      p{
        background-color : #e6e6e6 ;
      }
    </style>
    <body>
    <center>
      <input type="button" value="添加節(jié)點(diǎn)" onclick="addParagraph();"/>
      <input type="button" value="刪除節(jié)點(diǎn)" onclick="delParagraph();"/>
      <div id="paragraphs">
        <p id="p1">段落1</p>
        <p id="p2">段落2</p>
      </div>
    </center>
    </body>
    </html>
    以上這篇js操作DOM--添加、刪除節(jié)點(diǎn)的簡(jiǎn)單實(shí)例就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考