您的位置:首页 > Web前端 > JavaScript

JavaScript HTML DOM 添加和删除节点(HTML 元素)

2017-09-06 13:16 676 查看
添加和删除节点实例:

<!DOCTYPE html>
<html>
<body>
<script>
function addOnclick(){
var para=document.createElement("p");
var node=document.createTextNode("This is new.");
para.appendChild(node);
var element=document.getElementById("div1");
element.appendChild(para);
}
function removeOnclick(){
var parent=document.getElementById("div1");
var child=document.getElementsByTagName("p");
parent.removeChild(child[child.length-1]);
}
</script>
<div id="div1">
<p id="p1">This is a paragraph.This is p1</p>
<p id="p2">This is another paragraph.</p>
</div>
<button onclick="addOnclick();">点击添加</button>
<button onclick="removeOnclick();">点击删除</button>
</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息