Javascript Basic Tutorial: Operation of DOM Nodes
How to create a new html element
To add a new element to the HTML DOM, you must first create the element (element node) and then add Append the element to an existing element
The following example:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>DOM 與 CSS</title> </head> <body> <div name="dv" id="dv"> <p id="p1">php 中文網(wǎng)</p> <p id="p2">php.cn</p> </div> <script type="text/javascript"> var para=document.createElement("p"); //創(chuàng)建新的<p> 元素: var node=document.createTextNode("歡迎學(xué)習(xí)javascript");//創(chuàng)建了一個(gè)文本節(jié)點(diǎn) para.appendChild(node);//必須向 <p> 元素追加這個(gè)文本節(jié)點(diǎn) var element=document.getElementById("dv");//找到一個(gè)已有的元素 element.appendChild(para);//在已存在的元素后添加新元素 </script> </body> </html>
How to delete a node
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>DOM 與 CSS</title> </head> <body> <div name="dv" id="dv"> <p id="p1">php 中文網(wǎng)</p> <p id="p2">php.cn</p> <p id="p3">js 快速入門</p> </div> <script type="text/javascript"> var parent=document.getElementById("dv");//找到 id="dv" 的元素: var child=document.getElementById("p3"); //找到 id="p3" 的 <p> 元素: parent.removeChild(child);//從父元素中刪除子元素 </script> </body> </html>