HTML DOM appendChild() 方法

1.

 1 <!DOCTYPE html>
 2 <html>
 3 <body>
 4 
 5 <ul id="myList"><li>Coffee</li><li>Tea</li></ul>
 6 
 7 <p id="demo">请点击按钮向列表中添加项目。</p>
 8 
 9 <button onclick="myFunction()">亲自试一试</button>
10 
11 <script>
12 function myFunction()
13 {
14 var node=document.createElement("LI");
15 var textnode=document.createTextNode("Water");
16 
17 
18 node.appendChild(textnode);
19 
20 //此时node为<li>Water</li>
21 
22 //(不知为何 appendChild方法能将文本append到标签里)
23 
24 
25 document.getElementById("myList").appendChild(node);
26 }
27 </script>
28 
29 <p><b>注释:</b>首先创建 LI 节点,然后创建文本节点,然后把这个文本节点追加到 LI 节点。最后把 LI 节点添加到列表中。</p>
30 
31 </body>
32 </html>

2.

 1 <!DOCTYPE html>
 2 <html>
 3 <body>
 4 
 5 <ul id="myList1"><li>Coffee</li><li>Tea</li></ul>
 6 <ul id="myList2"><li>Water</li><li>Milk</li></ul>
 7 
 8 <p id="demo2">demo2</p>
 9 <p id="demo">请点击按钮把项目从一个列表移动到另一个列表中。</p>
10 
11 <button onclick="myFunction()">亲自试一试</button>
12 
13 <script>
14 function myFunction()
15 {
16 var node=document.getElementById("myList2").lastChild;
17 
18 //这里倒像是把 <li>Milk</li> 剪切出来了
19 console.log(node);
20 document.getElementById("demo2").appendChild(node);
21 
22 //然后再追加到这里
23 }
24 </script>
25 
26 </body>
27 </html>
28 
29  
30 
31
-------------------------------------------------- 以上来源于W3School "HTML DOM appendChild() 方法" 一节
原文地址:https://www.cnblogs.com/qhxblog/p/8462449.html