03-JS中添加节点

JS中添加节点

1、创建Dom元素
1) createElement(标签名) 创建一个节点
节点创建后是不是在页面中能够显示,不是
2) appendChild(节点) 追加一个节点

2、插入一个元素
insertBefore(新节点,原有节点) 在原有节点前插入新节点

3、删除一个元素
removeChild(节点) 删除一个节点

 1 <!DOCTYPE html>
 2 <html>
 3     <head>
 4         <meta charset="UTF-8">
 5         <title></title>
 6     </head>
 7     <body>
 8         <input type="text" name="" id="txt1" value="" />
 9         <input type="button" id="btn1" value="添加 li" />
10         <ul id="ul1">
11         </ul>
12     </body>
13     <script type="text/javascript">
14         window.onload = function(){
15             var oBtn = document.getElementById("btn1");
16             var oUl = document.getElementById("ul1");
17             
18             oBtn.onclick=function(){
19                 //创建一个新节点
20                 var oLi = document.createElement("li");
21                 var oTxt = document.getElementById("txt1");
22                 
23                 oLi.innerHTML = oTxt.value+"<a href='#'>删除</a>";
24                 //在ul中添加子节点
25                 //oUl.appendChild(oLi);
26                 
27                 var first = oUl.firstChild;
28                 if(first){
29                     oUl.insertBefore(oLi,first);
30                 }else{
31                     oUl.appendChild(oLi);
32                 }
33                 
34                 //删除操作
35                 //获得所有的  a  标签
36                 var aTag = document.getElementsByTagName('a');
37                 //console.log(aTag.length);
38                 
39                 for (var i=0;i<aTag.length;i++) {
40                     // 给 a 添加单击事件
41                     aTag[i].onclick = function(){
42                         //this.parentNode.style.display = "none";    
43                         oUl.removeChild(this.parentNode);
44                     }
45                 }
46             }
47             
48             
49         }
50     </script>
51     
52 </html>
原文地址:https://www.cnblogs.com/liuxuanhang/p/7805791.html