1. 程式人生 > >js操作DOM--新增、刪除節點

js操作DOM--新增、刪除節點

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="父節點 \n"+nodestatus(parent)+"\n";
//返回元素節點p的最後一個孩子
last=parent.lastChild;
msg+="刪除之前:lastChild--"+nodestatus(last)+"\n";
//刪除節點p的最後一個孩子,變為b
parent.removeChild(last);
last=parent.lastChild;
msg+="刪除之後:lastChild--"+nodestatus(last)+"\n";
alert(msg);
-->
</script>
</body>

---------------------------------------------------------------------------------------------------------------------------------

=================================================================

<html>

<head>

<title>js控制新增、刪除節點</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;
       
        //建立新屬性
        var newAttr = document.createAttribute("id");
        newAttr.nodeValue = "p" + seq;
        newElement.setAttribute(newAttr);
       
        //建立文字內容
        var txtNode = document.createTextNode("段落" + seq);
       
        //新增節點
        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="新增節點" onclick="addParagraph();"/>
    <input type="button" value="刪除節點" onclick="delParagraph();"/>
    <div id="paragraphs">
        <p id="p1">段落1</p>
        <p id="p2">段落2</p>
    </div>
</center>
</body>

</html>