首页 > 代码库 > 文档对象模型DOM(createNode)

文档对象模型DOM(createNode)

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script type="text/javascript">
			function t1(){
				var div1 = document.getElementById("div1");
				var p = document.createElement("p");
				var t = document.createTextNode("u34");
				p.setAttribute("name","zhangsan");
				p.appendChild(t);
				div1.appendChild(p);
			}
			
			function t2(){
				var div1 = document.getElementById("div1");
				var list = div1.childNodes;
				if(list.length==0){
					alert("无法删除!");
					return;
				}
				div1.removeChild(list[0]);
			}
			
			function t3(){
				var div1 = document.getElementById("div1");
				var list = div1.childNodes;
				if(list.length==0){
					alert("无法替换!");
					return;
				}
				var h = document.createElement("h1");
				var t = document.createTextNode("AAAA");
				h.appendChild(t);
				div1.replaceChild(h,list[list.length-1]);
			}
			function t4(){
				var div1 = document.getElementById("div1");
				var list = div1.childNodes;
			
				var h = document.createElement("h1");
				var t = document.createTextNode("BBBB");
				h.appendChild(t);
				div1.insertBefore(h,list[1]);
			}
			function t5(){
				var div1 = document.getElementById("div1");
						
				var h = document.createElement("h1");
				var t = document.createTextNode("BBBB");
				h.appendChild(t);
				var hh = h.cloneNode(true);
				div1.appendChild(hh);
			}
		</script>
	</head>
	<body>
		<input type="button" onclick="t1()" value="http://www.mamicode.com/增加"/>
		<input type="button" onclick="t2()" value="http://www.mamicode.com/删除"/>
		<input type="button" onclick="t3()" value="http://www.mamicode.com/替换"/>
		<input type="button" onclick="t4()" value="http://www.mamicode.com/插入"/>
		<input type="button" onclick="t5()" value="http://www.mamicode.com/复制插入"/>
		<div id="div1" style="width: 300px;height: 300px;background-color: red;"></div>
	</body>
</html>

  

文档对象模型DOM(createNode)