14nodeOper.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> .box { width: 200px; height: 200px; background-color: pink; } .block { display: block; } </style> </head> <body> <button id="btn_create">创建</button> <button id="btn_del">删除</button> <script src="../../01-ES/code/tool.js"></script> <script> // 创建元素 var oDiv = document.createElement("div"); oDiv.innerHTML = "我是动态创建div"; oDiv.className = "box"; // 将元素添加到body 上树 //document.body.appendChild(oDiv); 在末尾追加儿子 document.body.insertBefore(oDiv,document.body.children[0]); var i = 0; $("btn_create").onclick = function() { var oSpan = document.createElement("span"); oSpan.className = "block"; oSpan.innerHTML = i++; document.body.appendChild(oSpan); //document.body.innerHTML += "<span>"+(i++)+"</span><br/>"; } $("btn_del").onclick = function() { var spans = document.getElementsByTagName("span"); /* for(var i=0; i<spans.length; i++) { spans[i].remove(); // 删除自己 i--; } */ /* for(var i=spans.length-1; i>=0; i--) { spans[i].remove(); } */ } // i=0 [span0,span1,span2,.....] // i=1 [span1,span2,.....] </script> </body> </html>