js Operation DOM Simple Example of Add Remove Nodes

  • 2021-07-02 22:57:42
  • OfStack


js removeChild()  Usage 

<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=" Parent node  \n"+nodestatus(parent)+"\n"; 
// Return Element Node p The last of 1 A child  
last=parent.lastChild; 
msg+=" Before deletion: lastChild--"+nodestatus(last)+"\n"; 
// Delete Node p The last of 1 A child , Become b 
parent.removeChild(last); 
last=parent.lastChild; 
msg+=" After deletion: lastChild--"+nodestatus(last)+"\n"; 
alert(msg); 
--> 
</script> 
</body> 

<html>

<head>

<title>js Control the addition and deletion of nodes </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;
    
    // Create a new property 
    var newAttr = document.createAttribute("id");
    newAttr.nodeValue = "p" + seq;
    newElement.setAttribute(newAttr);
    
    // Create text content 
    var txtNode = document.createTextNode(" Paragraph " + seq);
    
    // Add Node 
    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=" Add Node " onclick="addParagraph();"/>
  <input type="button" value=" Delete Node " onclick="delParagraph();"/>
  <div id="paragraphs">
    <p id="p1"> Paragraph 1</p>
    <p id="p2"> Paragraph 2</p>
  </div>
</center>
</body>

</html>

Related articles: