标签:javascript 对象 dom 节点
一、简介
通过js dom找到某个元素,对该元素增加子节点,或删除该元素的子节点。
二、示例
1.动态增加和删除节点元素
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta content="text/css" charset="utf-8" /> <style> button { width: 100px; height: 50px; background:GREEN; } div{ width:1500px; height:500px; background:red; margin-top:100px; } </style> </head> <body> <button onclick="addEle()">添加</button> <button onclick="deleteEle()">删除</button> <div id="div1"> <p id="p0">段落1</p> </div> </body> <script> var x= 0; //定义一个全局的变量 function addEle(){ var ele = document.createElement("p"); var node = document.createTextNode("这个是一个段落"); x++; ele.id="p" +x; //对该节点元素设置id ele.style.color="white";//设置节点元素的颜色 ele.appendChild(node); var ele_parent = document.getElementById("div1"); ele_parent.appendChild(ele); } function deleteEle(){ var ele_parent = document.getElementById("div1"); var ele_child = document.getElementById("p"+x); x--; ele_parent.removeChild(ele_child); } </script> </html>
运行效果:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta content="text/css" charset="utf-8" /> <style> button { width: 100px; height: 50px; background: GREEN; } div { width: 500px; height: 3500px; background: red; margin-top: 100px; } </style> </head> <body> <button onclick="addEle()">添加</button> <button onclick="deleteEle()">删除</button> <div id="div1"></div> </body> <script> /** * <div> * <img src="./header" width="500" height="100" /> * <br/> * <a href="http://xxx">风景图片</a> * </div> */ var x= 0; //定义一个全局的变量 function addEle(){ x++; var ele = document.createElement("img");//创建img节点 ele.id="img" +x; //对该节点元素设置id ele.src="./header.jpg"; ele.width="500"; ele.height="100"; var eleBr=document.createElement("br");//创建br节点 eleBr.id="br" +x; var ele2 = document.createElement("a");//创建a节点 ele2.id="a" + x; ele2.href="http://www.baidu.com"; var node2 = document.createTextNode("风景图片"+x); ele2.appendChild(node2); var ele_parent = document.getElementById("div1"); ele_parent.appendChild(ele); ele_parent.appendChild(eleBr); ele_parent.appendChild(ele2); } function deleteEle(){ var ele_parent = document.getElementById("div1"); var ele_child = document.getElementById("img"+x); var ele_child2=document.getElementById("br" +x); var ele_child3 = document.getElementById("a" +x); ele_parent.removeChild(ele_child3); ele_parent.removeChild(ele_child2); ele_parent.removeChild(ele_child); x--; } </script> </html>
运行效果:
标签:javascript 对象 dom 节点
原文地址:http://blog.csdn.net/z18789231876/article/details/43794085