1、添加DOM节点
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <ul id="parent"> <li>1</li> <li>2</li> <li>3</li> <li>4</li> </ul> <button onclick="func()">增加DOM节点</button> <script type="text/javascript"> var n=5; function func(){ var li=document.createElement("li"); var nodeText=document.createTextNode(n); li.appendChild(nodeText); var parent=document.getElementById("parent"); parent.appendChild(li); n++; } </script> </body> </html>
项目结果:
2、删除DOM节点
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <ul id="parent"> <li>1</li> <li>2</li> <li>3</li> <li>4</li> </ul> <button onclick="func()">增加DOM节点</button> <button onclick="func2()">删除DOM节点</button> <script type="text/javascript"> var n=5; function func(){ var li=document.createElement("li"); var nodeText=document.createTextNode(n); li.appendChild(nodeText); var parent=document.getElementById("parent"); parent.appendChild(li); n++; } function func2(){ var parent=document.getElementById("parent"); var lis=document.getElementsByTagName("li"); var len=lis.length; parent.removeChild(lis[len-1]); n--; } </script> </body> </html>
项目结果:
3、修改DOM节点