js操作DOM--添加、刪除節點的簡單一實例,jsdom--

來源:互聯網
上載者:User

js操作DOM--添加、刪除節點的簡單一實例,jsdom--

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>

以上這篇js操作DOM--添加、刪除節點的簡單一實例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援幫客之家。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.