天天看点

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

添加和删除节点实例:

<!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-]);
}
</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>
           

继续阅读