JavaScript adds element after another | Example code

Use before method to add element after another element in JavaScript.

Note: before and after are both marked as “experimental” on MDN page: Experimental. Expect behavior to change in the future.

JavaScript add element after another HTML example

HTML example codes:-

Insert p tag after div tag

<!DOCTYPE html>
<html>
<body>

    <div id="div1">Hello world</div>

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

        // creating new element 
        const newEl = document.createElement("p");
        newEl.id = "foo";

        el.after(newEl);

        // Adding text in new p tag
        document.getElementById("foo").innerHTML = "I am new tag";

    </script>
</body>

</html>

Output:

JavaScript adds element after another html

Read more:

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

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.