<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>
DOM删除添加节点小例子
最新推荐文章于 2019-06-24 12:34:20 发布