Skip to content

JavaScript adds element after another | Example code

  • by

Use the before method to add elements 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 these 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

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