<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> <ul id="city"> <li id="sz">深圳</li> <li>广州</li> <li id="nn">南宁</li> <li>上海</li> </ul> <button id="btn">杭州</button> <button id="btn2">深圳前面插入杭州</button> <button id="btn3">替换南宁节点</button> <button id="btn4">删除南宁</button> <button id="btn5">读取代码</button> <button id="btn6">更改南宁节点内容</button> <button id="btn7">添加一个苏杭</button> <button id="btn8">推荐方法:添加一个苏杭节点</button> </body> <script type="text/javascript"> window.onload = function() { myClick("btn", function() { var city = document.getElementById("city"); var li = document.createElement("li"); var text = document.createTextNode("杭州"); li.appendChild(text); city.appendChild(li); //appendChild添加节点 }); myClick("btn2", function() { var city = document.getElementById("city"); var li = document.createElement("li"); // createElement创建一个元素 var sz = document.getElementById("sz"); var text = document.createTextNode("杭州"); // createTextNode创建一个文本 li.appendChild(text); city.insertBefore(li,sz); // insertBefore节点添加到前面 }); myClick("btn3", function() { var city = document.getElementById("city"); var li = document.createElement("li"); var nn = document.getElementById("nn"); var text = document.createTextNode("苏杭"); li.appendChild(text); city.replaceChild(li,nn); // replaceChild替换节点 }); myClick("btn4", function() { var city = document.getElementById("city"); var nn = document.getElementById("nn"); city.removeChild(nn) // removeChild删除节点 }); myClick("btn5", function() { var city = document.getElementById("city"); alert(city.innerHTML); }); myClick("btn6", function() { var nn = document.getElementById("nn"); nn.innerHTML="难方"; }); myClick("btn7", function() { var city = document.getElementById("city"); city.innerHTML +="<li>苏杭</li>"; }); myClick("btn8", function() { var city = document.getElementById("city"); var li = document.createElement("li"); li.innerHTML="苏杭"; city.appendChild(li); }); } function myClick(idStr,fun){ var btn =document.getElementById(idStr); btn.onclick=fun; } </script> </html>