JavaScript动态改变HTML页面元素例如添加或删除
可以通过JavaScript动态的改变HTML中的元素
向HTML中添加元素
首先需要创建一个标签,然后向该标签中添加相应的内容,然后将创建好的标签添加到相应的位置。
<!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<htmlxmlns="http://www.w3.org/1999/xhtml">
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=gb2312"/>
<title>测试文档</title>
<scripttype="text/javascript">
functionadd(){
varelement=document.createElement("p");
varnode=document.createTextNode("添加新段落");
element.appendChild(node);
x=document.getElementById("demo");
x.appendChild(element);
}
</script>
</head>
<body>
<divid="demo">
<p>这是第一段</p>
</div>
<inputtype="button"value="按钮"onclick="add()"/>
</body>
</html>
删除HTML中的某个元素
<!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<htmlxmlns="http://www.w3.org/1999/xhtml">
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=gb2312"/>
<title>测试文档</title>
<scripttype="text/javascript">
functiondeleteE(){
varfather=document.getElementById("demo");
varchild=document.getElementById("p1");
father.removeChild(child);
}
</script>
</head>
<body>
<divid="demo">
<pid="p1">这是第一段</p>
<pid="p2">这是第二段</p>
</div>
<inputtype="button"value="删除"onclick="deleteE()"/>
</body>
</html>热门推荐
1 训练狗狗基础
2 怎么训练狗狗笑
3 怎么训练狗狗卧下
4 上海狗狗训练基地
5 训练狗狗排便
6 狗狗基础训练
8 如何训练狗狗装死
9 狗狗站姿训练
10 狗狗训练用品
11 训练狗狗吧
12 狗狗要怎么训练
13 怎么训练狗狗玩球
14 训练狗狗唤回
15 狗狗训练躺下
16 狗狗训练指令
17 狗狗的训练技巧
18 狗狗不好训练