insertBefore Method

Internet Development Index

Inserts an element into the document hierarchy as a child node of a parent object.

What's New for Microsoft® Internet Explorer 6

This method now applies to the attribute object.

Syntax

oElement = object.insertBefore(oNewNode [, oChildNode])

Parameters

oNewNode Required. Object that specifies the new element to be inserted into the document hierarchy. Elements can be created with the createElement method.
oChildNode Optional. Object that specifies the placement of the new element. If this parameter is specified, the new element will be inserted immediately before this existing child element.

Return Value

Returns a reference to the element that is inserted into the document.

Remarks

Do not specify the oChildNode parameter when inserting the first child node. If children already exist and you do not specify the oChildNode parameter, the oNewNode 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.

Example

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

<SCRIPT>
function insertElement()
{
var nod=document.createElement("LI");
oUL1.insertBefore(nod, oLIYellow);
nod.innerText="Orange";
}
</SCRIPT>
</HEAD>
<BODY>
<SPAN onclick=insertElement()>Click <B>HERE</B> to add an item to the following list.</SPAN>
<UL id="oUL1">
<LI id="oLIRed">Red</LI>
<LI id="oLIYellow">Yellow</LI>
<LI id="oLIBlue">Blue</LI>
</UL>
</BODY>
This feature requires Microsoft® Internet Explorer 5 or later. Click the following icon to install the latest version. Then reload this page to view the sample.

Standards Information

This method is defined in World Wide Web Consortium (W3C) Document Object Model (DOM) Level 1 Non-Microsoft link.

Applies To

A, ACRONYM, ADDRESS, attribute, B, BDO, BIG, BLOCKQUOTE, BODY, BUTTON, CAPTION, CENTER, CITE, CODE, COL, COLGROUP, COMMENT, DD, DEL, DFN, DIR, DIV, DL, DT, EM, FIELDSET, FONT, FORM, FRAMESET, HEAD, hn, HTML, I, IFRAME, INPUT type=button, INPUT type=checkbox, INPUT type=file, INPUT type=image, INPUT type=password, INPUT type=radio, INPUT type=reset, INPUT type=submit, INPUT type=text, INS, KBD, LABEL, LEGEND, LI, LISTING, MAP, MARQUEE, MENU, nextID, OBJECT, OL, OPTION, P, PLAINTEXT, PRE, Q, S, SAMP, SELECT, SMALL, SPAN, STRIKE, STRONG, SUB, SUP, TABLE, TBODY, TD, TEXTAREA, TFOOT, TH, THEAD, TR, TT, U, UL, VAR, XMP

See Also

About the W3C Document Object Model