JavaScript DOM节点添加与删除操作示例

作者:流萤

时间:2026-10-30

浏览:418

本文通过两个具体代码示例,演示了如何使用JavaScript动态操作DOM节点。内容涵盖利用removeChild方法删除指定子节点,以及通过createElement、createAttribute和appendChild等方法创建并添加新段落节点。示例包含完整的HTML结构与脚本逻辑,旨在帮助开发者理解节点增删的核心API用法。

文章目录

使用removeChild删除节点


js removeChild() 用法

<body> 
<p id="p1">welcome to <b>javascript</b> world !</p> 
<script language="javascript" type="text/javascript"> 
<!-- 
function nodestatus(node) 
{ 
 var temp=""; 
 if(node.nodeName!=null) 
 { 
  temp+="nodeName="+node.nodeName+"\n"; 
 } 
 else temp+="nodeName=null \n"; 
 if(node.nodeType!=null) 
 { 
  temp+="nodeType="+node.nodeType+"\n"; 
 } 
 else temp+="nodeType=null \n"; 
 if(node.nodeValue!=null) 
 { 
  temp+="nodeValue="+node.nodeValue+"\n"; 
 } 
 else temp+="nodeValue=null \n"; 
 return temp; 
} 
var parent=document.getElementById("p1"); 
var msg="父节点 \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>
<script type="text/javascript">
  var all;
  function addParagraph() {
    all = document.getElementById("paragraphs").childNodes;
    var newElement = document.createElement("p");
    var seq = all.length + 1;
    
    //创建新属性
    var newAttr = document.createAttribute("id");
    newAttr.nodeValue = "p" + seq;
    newElement.setAttribute(newAttr);
    
    //创建文本内容
    var txtNode = document.createTextNode("段落" + seq);
    
    //添加节点
    newElement.appendChild(txtNode);
    document.getElementById("paragraphs").appendChild(newElement);
  }
  function delParagraph() {
    all = document.getElementById("paragraphs").childNodes;
    document.getElementById("paragraphs").removeChild(all[all.length -1]);
  }
</script>
<style>
  p{
    background-color : #e6e6e6 ;
  }
</style>
<body>
<center>
  <input type="button" value="添加节点" onclick="addParagraph();"/>
  <input type="button" value="删除节点" onclick="delParagraph();"/>
  <div id="paragraphs">
    <p id="p1">段落1</p>
    <p id="p2">段落2</p>
  </div>
</center>
</body>

</html>

以上关于JavaScript操作DOM节点中增加与删除功能的示例代码,即为本文分享的全部内容。希望这些实例能为读者提供有价值的参考,同时也欢迎大家继续支持本站获取更多技术资源。

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章