You are here: Reference > JavaScript > client-side > HTML DOM > methods > insertBefore

insertBefore method

Browser support:
Inserts an element before the specified child of the current element.
If the element has a parent element, then it will be removed from the parent element before the insertion. The inserted element will be placed before the specified child in the childNodes collection of the current element.
  • If you want to create a new element for insertion, use the createElement method first, then use insertBefore or appendChild methods for the newly created element.
  • To insert an element after the last child of the current element, use the appendChild method.
  • If you need to insert a new row into a table or a new cell into a row, you can also use the insertRow and insertCell methods.
  • If you want to remove a child from an element, use the removeChild method.
Note: the insertBefore method cannot be used for elements that belong to another document. Use the adoptNode or importNode method on foreign elements first.


object.insertBefore (elementToInsert, beforeElement);
You can find the related objects in the Supported by objects section below.


Required. Reference to the element to insert.
Required. Reference to the child element of the current element before which the new element needs to be inserted. This parameter is optional in Internet Explorer. If this parameter is not specified or its value is null, the new element will be inserted at the end of the child list (like the appendChild method).

Return value:

Returns the inserted element.

Example HTML code 1:

This example illustrates the use of the insertBefore method:
    <script type="text/javascript">
        function InsertAsFirstChild () {
            var what = document.getElementById ("what");
            var to = document.getElementById ("to");
            to.insertBefore (what, to.firstChild);
    <div id="to" style="background:yellow;">
        Insert the element before this text.
    <div id="what">The element to insert</div>
    <br /><br />
    <button onclick="InsertAsFirstChild ();">Insert as the first child!</button>
Did you find this example helpful? yes no

Supported by objects:

Related pages:

External links:

User Contributed Comments

Post Content

Post Content