Sunday, 30 September 2018

JavaScript: insertAfter: Insert element after an element

In this post, I am going to implement insertAfter function used to insert an element after given element.

function insertAfter(newNode, referenceNode) {
    referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}

Following is the complete working application.

process.js
function addData(){
 var para = document.createElement("p");
 var text = document.getElementById("text").value;
 var textNode = document.createTextNode(text);
 para.appendChild(textNode);
 
 var targetElement = document.getElementById("myButton");
 
 insertAfter(para, targetElement);
}

function insertAfter(newNode, referenceNode) {
    referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}


changeDom.html
<!DOCTYPE html>

<html>
 <head>
  <title>Change DOM</title>
  <script src="process.js"></script>
 </head>
 
 <body>
  
  <div id="data1">
   <input type="text" id="text"/><br />
   <input type="button" id="myButton" value="click me" onclick="addData();" />
  </div>
 </body>
</html>



Previous                                                 Next                                                 Home

No comments:

Post a Comment