js操作DOM--添加、删除节点的简单实例
jsremoveChild()用法
<body>
<pid="p1">welcometo<b>javascript</b>world!</p>
<scriptlanguage="javascript"type="text/javascript">
<!--
functionnodestatus(node)
{
vartemp="";
if(node.nodeName!=null)
{
temp+="nodeName="+node.nodeName+"\n";
}
elsetemp+="nodeName=null\n";
if(node.nodeType!=null)
{
temp+="nodeType="+node.nodeType+"\n";
}
elsetemp+="nodeType=null\n";
if(node.nodeValue!=null)
{
temp+="nodeValue="+node.nodeValue+"\n";
}
elsetemp+="nodeValue=null\n";
returntemp;
}
varparent=document.getElementById("p1");
varmsg="父节点\n"+nodestatus(parent)+"\n";
//返回元素节点p的最后一个孩子
last=parent.lastChild;
msg+="删除之前:lastChild--"+nodestatus(last)+"\n";
//删除节点p的最后一个孩子,变为b
parent.removeChild(last);
last=parent.lastChild;
msg+="删除之后:lastChild--"+nodestatus(last)+"\n";
alert(msg);
-->
</script>
</body>
<html>
<head>
<title>js控制添加、删除节点</title>
</head>
<scripttype="text/javascript">
varall;
functionaddParagraph(){
all=document.getElementById("paragraphs").childNodes;
varnewElement=document.createElement("p");
varseq=all.length+1;
//创建新属性
varnewAttr=document.createAttribute("id");
newAttr.nodeValue="p"+seq;
newElement.setAttribute(newAttr);
//创建文本内容
vartxtNode=document.createTextNode("段落"+seq);
//添加节点
newElement.appendChild(txtNode);
document.getElementById("paragraphs").appendChild(newElement);
}
functiondelParagraph(){
all=document.getElementById("paragraphs").childNodes;
document.getElementById("paragraphs").removeChild(all[all.length-1]);
}
</script>
<style>
p{
background-color:#e6e6e6;
}
</style>
<body>
<center>
<inputtype="button"value="添加节点"onclick="addParagraph();"/>
<inputtype="button"value="删除节点"onclick="delParagraph();"/>
<divid="paragraphs">
<pid="p1">段落1</p>
<pid="p2">段落2</p>
</div>
</center>
</body>
</html>
以上这篇js操作DOM--添加、删除节点的简单实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下