JavaScript - Insert a Div Element Before a Div Element

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:

<script>
    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>";
    }
</script>

The Script for the HTML Body Part:

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

Output

As shown in the featured image of this article.