Languages
[Edit]
EN

JavaScript - how to insert element after element?

5 points
Created by:
Marcin
2477

Using JavaScript it is possible to insert element after some element inside DOM tree in following way.

1. Custom insertAfter method example

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<head>
  <script>

    function insertAfter(newElement, placeholder) {
    	var parent = placeholder.parentNode;
      
      	if (parent == null) {
        	throw new Error('Placeholder element does not have parent node.');
        }
      
      	var sibling = placeholder.nextSibling;
      
      	if (sibling) {
        	parent.insertBefore(newElement, sibling);
        } else {
        	parent.appendChild(newElement);
        }
    }
    
  </script>
</head>
<body>
  <div>
    <p id="element-1">1st element...</p>
    <p id="element-2">2nd element...</p>
    <p id="element-3">3rd element...</p>
    <p id="element-4">4th element...</p>
  </div>
  <script>

    var element3 = document.getElementById('element-3');
    
    var newElement = document.createElement('p');
    newElement.innerText = 'This is new element placed after 3rd...';
    
    insertAfter(newElement, element3);
    
  </script>
</body>
</html>

Merged questions

  1. JavaScript - how to insert node after node?
Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.