insertBefore method
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.
Syntax:
You can find the related objects in the Supported by objects section below.
Parameters:
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:
|
||||
<head> <script type="text/javascript"> function InsertAsFirstChild () { var what = document.getElementById ("what"); var to = document.getElementById ("to"); to.insertBefore (what, to.firstChild); } </script> </head> <body> <div id="to" style="background:yellow;"> Insert the element before this text. </div> <div id="what">The element to insert</div> <br /><br /> <button onclick="InsertAsFirstChild ();">Insert as the first child!</button> </body> |
||||
|
||||
Did you find this example helpful?
|
Supported by objects:
attribute, document, DocumentFragment, XMLDocument
HTML elements:
a, abbr, acronym, address, b, bdo, big, blink, blockquote, body, button, caption, center, cite, code, col, colgroup, dd, del, dfn, dir, div, dl, dt, em, fieldset, font, form, frameset, h1, h2, h3, h4, h5, h6, head, html, i, img, ins, kbd, keygen, label, legend, li, listing, map, marquee, menu, nobr, noframes, noscript, object, ol, optgroup, option, p, plaintext, pre, q, rt, ruby, s, samp, select, small, span, strike, strong, sub, sup, table, tbody, td, textarea, tfoot, th, thead, tr, tt, u, ul, var, xml, xmp
Related pages:
External links:
User Contributed Comments