点击按钮追加元素和元素内容

 

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Document</title>
 6     <script>
 7     window.onload = function(){
 8         var obtn = document.getElementById("btn");
 9 
10         obtn.onclick=function(){ //按钮点击事件属性,属性值为函数
11                     insert();
12         }
13     function insert(){
14         var obody = document.getElementsByTagName("body");
15         var odiv = document.createElement("div");
16         var txt = document.createTextNode("测试");
17         //alert(txt.nodeValue);
18         odiv.appendChild(txt);
19         //alert(odiv.nodeValue);节点值为null但是由于执行了,odiv.appendChild(txt);,innerHTML值不为空
20      
21         obody[0].appendChild(odiv);//需注意的是ByTagName找到的元素肯定是一个集合,就算页面只有一个,那么也就说这个集合的长度为1,和数组类似。必须使用[]下标方式         
22 }
23 }
24     </script>
25 </head>
26 <body >
27 
28     <button id="btn">点击插入</button>
29 </body>
30 </html>
原文地址:https://www.cnblogs.com/hanguidong/p/9092355.html