JavaScript - Insert a Div Element Before a Div Element

Here is a JavaScript example to insert a div element before a div element.

In the following example, it will first get the existing element and then will insert a div element before that.

The Script for the HTML Head Part:

    window.onload=function() {
        // get the existing element
        var refElement = document.getElementById("child");
        // get the element's parent node
        var parent = refElement.parentNode;
        // create new div element
        var newDiv = document.createElement("div");
        // attach to page before child element
        parent.insertBefore(newDiv, refElement);
        // give it some content
        newDiv.innerHTML = "<p>This is the new content in a div element.</p>";

The Script for the HTML Body Part:

<div id="child">
        This is the old content in a div element.


As shown in the featured image of this article.

Leave a Comment