Languages
[Edit]
EN

JavaScript - how to insert element after element?

5 points
Created by:
Marcin
19490

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?
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join