js操作DOM--添加、刪除節(jié)點的簡單實例
來源:易賢網(wǎng) 閱讀:983 次 日期:2016-07-25 15:24:41
溫馨提示:易賢網(wǎng)小編為您整理了“js操作DOM--添加、刪除節(jié)點的簡單實例”,方便廣大網(wǎng)友查閱!

下面小編就為大家?guī)硪黄猨s操作DOM--添加、刪除節(jié)點的簡單實例。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。

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é)點 \n"+nodestatus(parent)+"\n"; 

//返回元素節(jié)點p的最后一個孩子 

last=parent.lastChild; 

msg+="刪除之前:lastChild--"+nodestatus(last)+"\n"; 

//刪除節(jié)點p的最后一個孩子,變?yōu)閎 

parent.removeChild(last); 

last=parent.lastChild; 

msg+="刪除之后:lastChild--"+nodestatus(last)+"\n"; 

alert(msg); 

--> 

</script> 

</body> 

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

<html>

<head>

<title>js控制添加、刪除節(jié)點</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é)點

    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é)點" onclick="addParagraph();"/>

  <input type="button" value="刪除節(jié)點" onclick="delParagraph();"/>

  <div id="paragraphs">

    <p id="p1">段落1</p>

    <p id="p2">段落2</p>

  </div>

</center>

</body>

</html>

以上這篇js操作DOM--添加、刪除節(jié)點的簡單實例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考

更多信息請查看網(wǎng)絡編程
易賢網(wǎng)手機網(wǎng)站地址:js操作DOM--添加、刪除節(jié)點的簡單實例

2025國考·省考課程試聽報名

  • 報班類型
  • 姓名
  • 手機號
  • 驗證碼
關于我們 | 聯(lián)系我們 | 人才招聘 | 網(wǎng)站聲明 | 網(wǎng)站幫助 | 非正式的簡要咨詢 | 簡要咨詢須知 | 新媒體/短視頻平臺 | 手機站點 | 投訴建議
工業(yè)和信息化部備案號:滇ICP備2023014141號-1 云南省教育廳備案號:云教ICP備0901021 滇公網(wǎng)安備53010202001879號 人力資源服務許可證:(云)人服證字(2023)第0102001523號
聯(lián)系電話:0871-65099533/13759567129 獲取招聘考試信息及咨詢關注公眾號:hfpxwx
咨詢QQ:1093837350(9:00—18:00)版權所有:易賢網(wǎng)