JavaScript – Insert Element after Specific HTML Element

To insert element in document after specific HTML Element using JavaScript, get reference to this HTML Element; call after() method on this HTML Element; and pass the element to insert, as argument to after() method.


In the following example, we have HTML Element with id "myElement", and we shall add a paragraph element after this HTML Element using after() method.


<!DOCTYPE html>
<html lang="en">
        #myElement {
            border:1px solid #CCC;
    <meta charset="utf-8">
    <h2>Insert Element after specific HTML Element in JavaScript</h2>
    <div id="myElement" class="dummy" style="width:100px;height:100px;background:#CCC;">Hello World!</div>
    <button type="button" onclick="execute()">Click Me</button>
    function execute(){
        //create new element
        var para = document.createElement('p');
        para.textContent = 'A new paragraph element.';
        //get reference to HTML element
        var element = document.getElementById('myElement');
        //add new after after specified HTML element
Try Online

When you click on Click Me button in the output of HTML, a new HTML Element will be added after the HTML Element with id "myElement".


In this JavaScript Tutorial, we learned how to insert an element in the document after a specific HTML Element using after() method in JavaScript.