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.

Example

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.

example.html

</>
Copy
<!DOCTYPE html>
<html lang="en">
<head>
    <style>
        #myElement {
            border:1px solid #CCC;
            width:100px;
            height:100px;
        }
    </style>
    <meta charset="utf-8">
</head> 
<body>
    <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>
    <br>
    <button type="button" onclick="execute()">Click Me</button>
    <script>
    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
        element.after(para);
    }
    </script>
</body>
</html>

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".

Conclusion

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