js操作DOM--添加、刪除節(jié)點的簡單實例
更新時間:2016年07月08日 11:07:29 投稿:jingxian
下面小編就為大家?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)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
您可能感興趣的文章:
- 詳解JS獲取HTML DOM元素的8種方法
- JavaScript獲取DOM元素的11種方法總結(jié)
- 通過JS動態(tài)創(chuàng)建一個html DOM元素并顯示
- JS動態(tài)創(chuàng)建DOM元素的方法
- 快速解決js動態(tài)改變dom元素屬性后頁面及時渲染的問題
- JavaScript DOM元素尺寸和位置
- JS選取DOM元素的簡單方法
- 原生JavaScript來實現(xiàn)對dom元素class的操作方法(推薦)
- JS實現(xiàn)動態(tài)添加DOM節(jié)點和事件的方法示例
- JavaScript DOM節(jié)點添加示例
- JavaScript DOM元素常見操作詳解【添加、刪除、修改等】
相關(guān)文章
Bootstrap 折疊(Collapse)插件用法實例詳解
這篇文章主要介紹了Bootstrap 折疊(Collapse)插件用法實例詳解的相關(guān)資料,需要的朋友可以參考下2016-06-06JS實現(xiàn)不使用圖片仿Windows右鍵菜單效果代碼
這篇文章主要介紹了JS實現(xiàn)不使用圖片仿Windows右鍵菜單效果代碼,涉及文鼎字及css樣式的使用技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-10-10scrapyd schedule.json setting 傳入多個值問題
這篇文章主要介紹了scrapyd schedule.json setting 傳入多個值,本文給出了問題分析及思路解決方案,非常不錯,具有一定的參考借鑒價值,需要的朋友參考下吧2019-08-08