Top community members
All Wiki Articles Create Wiki Article

Many years me and my friends we were volunteers on my university doing programming classes for young people.

I got main conclusion: Young people are awesome, especially students, because they always bring new and fresh ideas :)
* I loved to do it but my time is limited

  I decided to create something that will help millions of students

Now I am here

co-founder

JavaScript - how to insert element after element?

0 contributions
5 points

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?
0 contributions

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more