This page is Ready to Use

Notice: The WebPlatform project, supported by various stewards between 2012 and 2015, has been discontinued. This site is now available on github.

insertBefore

Summary

Inserts a child into the node, immediately before the specified reference child node.

Method of dom/Nodedom/Node

Syntax

var insertedNode = node.insertBefore(/* see parameter list */);

Parameters

newNode

Data-type
DOM Node

The new node to be inserted.

refChild

Data-type
DOM Node

(Optional)

Supplies the placement of the new node. If this parameter is specified, the new element will be inserted immediately before this existing child node. If not, it will be added after the last child node.

Return Value

Returns an object of type DOM NodeDOM Node

The inserted node.

Examples

The following example shows how to use the insertBefore method to insert a new item into an existing list.

<!doctype html>
<html>
<head>
<script type="application/javascript">
    function insertElement()
    {
        var nod=document.createElement("li");
        document.getElementById("oUL1").insertBefore(nod, document.getElementById("oLIYellow"));
        nod.textContet="Orange";
    }
</script>
</head>
<body>
    <p onclick="insertElement()">Click <strong>HERE</strong> to add an item to the following list.</p>
    <ul id="oUL1">
        <li id="oLIRed">Red</li>
        <li id="oLIYellow">Yellow</li>
        <li id="oLIBlue">Blue</li>
    </ul>
</body>
</html>

View live example

Notes

Do not specify the refChild parameter when inserting the first child node. If children already exist and you do not specify the refChild parameter, the newChild becomes the last child of the parent object. This method is accessible at run time. If elements are removed at run time, before the closing tag has been parsed, areas of the document might not render.

Related specifications

DOM Level 3 Core
Recommendation
DOM4
Working Draft

Attributions