Skip to content

JavaScript insert after | Append element example

  • by

JaJavaScript doesn’t have insertAfter() method, but insertBefore() method that allows you to insert a new after an existing node as a child node.

How to insert an element after another element in JavaScript?

To insert a new element after an existing element, first identify that element and then create a new one after that using the after the method.

element.after(newEl);

For the child node, First, select the next sibling node of the existing node. Then, select the parent node of the existing node and call the insertBefore() method.

menu.insertBefore(li, menu.firstElementChild.nextSibling);

JavaScript insert after Example

HTML examples code:

Insert div after div element

<!DOCTYPE html>
<html>
<body>

    <div id="div1">Hellow</div>

    <script>
        // Parent Element
        const el = document.getElementById("div1");

        const newEl = document.createElement("div");
        newEl.id = "foo";

        el.after(newEl);


    </script>
</body>

</html>

Output:

JavaScript insert after element Example

Insert new li in the existing list

<!DOCTYPE html>
<html>
<body>
    <ul id="menu">
        <li>Home</li>
        <li>About</li>
        <li>Contact</li>
    </ul>


    <script>
        let menu = document.getElementById('menu');
        // create a new li node
        let li = document.createElement('li');
        li.textContent = 'Services';

        // insert a new node after the first list item
        menu.insertBefore(li, menu.firstElementChild.nextSibling);
    </script>
</body>

</html>

Output:

JavaScript append element HTML example

Do comment if you have any doubts and suggestions on this topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *