DOM删除添加节点小例子


<body>
<table id="tab1">
	<tbody id="tbo1">
	<tr id="tr1">
		<td id="td1" name="td1">
			<p id="p1">aaaaaa</p>
			dddd
			<a href="#" style="color:blue" id="a1">1111111111111</a>
		</td>
		<td>2222</td>
		<td>3333</td>
	</tr>
	<tr id="tr2">
		<td id="td2">
			<a href="#" style="color:red" id="a2">22222222222</a>
		</td>
	</tr>
	<tr id="tr3">
		<td>
			
		</td>
	</tr>
	</tbody>
</table>
<input type="button" value="添加节点" οnclick="createChildNode('td1')" />
			<input type="button" value="删除节点" οnclick="removeChildNode('td1')" />
			<input type="button" value="innerHTML" οnclick="a('td1')" />
</body>
</html>

<script language="JavaScript" type="text/javascript">
	function removeChildNode(id)
	{
		//alert("aaaaaaaaaa");
		var test = document.getElementById(id);	
		var children = test.childNodes;	
		alert(children.length);
		//alert(children[children.length-1]);
		//children.hasChildNodes()
		//if(children[children.length-1]!=undefined&&children[children.length-1]!=null){
		if(test.hasChildNodes()){
			test.removeChild(children[children.length-1]);
		}else{
			alert("已到根节点");
		}
		//for(i=0;i<children.length;i++){
			//alert(children[i].id);
			//test.removeChild(children[i]);
		//}

		//xmlDoc.documentElement.removeChild(y);
		
		//var i= document.getElementById(xmlDoc).getxmlDoc.documentElement.childNodes;
		//alert(i);
		//alert(y);
	}	
	function createChildNode(id){
		var test = document.getElementById(id);
		var para = document.createElement("a");	
		var att1 = document.createAttribute("href");
		var att2 = document.createAttribute("style");
		para.name="aName";
		att1.nodeValue="#";
		//name1.nodeValue="color:red";
		para.setAttributeNode(att1);
		//para.setAttributeNode(att2);
		//para.setAttributeNode(newatt);
		//para.setAttribute("href","#");
		var text = document.createTextNode("要添加的文本 ");	
		//para.appendChild(text);	
		test.appendChild(text);
	
	}

	function a(id){
		document.getElementById(id).innerHTML = "<a href='#'>12</a>";
	
	}
		
</script>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值