English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

HTML DOM insertBefore() Method

HTML DOM Element Object

insertBefore()The method is used to insert a child node before a specified existing child node.

If the given sub-object is a reference to an existing node in the document, insertBefore() moves it from its current position to the new position (see the 'More Examples' below).

Usageappendchild()The method adds a node to the end of the child node list of the specified parent node.

Syntax:

node.insertBefore(newNode, existingNode)
var newElem = document.createElement("h"3");  // Create a new h3Element
var newContent = document.createTextNode("Hi there");  // Create some text content
newElem.appendChild(newContent);  // Add a text node to the newly created h3
var body = document.body;  // Get BODY
body.insertBefore(newElem, body.childNodes[0]); // Insert H before the first child of BODY3
Test and See‹/›

Note:If you want to create a new element with text, remember to create the text as a Text node, then attach it to the element, and then attach the element to the document.

Browser Compatibility

All browsers fully support the insertBefore() method:

Method
insertBefore()IsIsIsIsIs

Parameter value

ParameterDescription
newNodeThe node object you want to insert
existingNodeYou want to insert a new node as a child of the existing node. If set to null, the insertBefore method will insert newNode at the end

Technical Details

Return value:A Node object representing the inserted node
DOM Version:DOM Level1

More examples

Create a <p> element and insert it into the <div> element:

var para = document.createElement("p");   // Create a <p> node
var txt = document.createTextNode("This is a paragraph.");// Create a text node
para.appendChild(txt);// Append text to <p>
var div = document.getElementById("demo");// Get the DIV with "id=demo"
div.insertBefore(para, div.childNodes[0]);// Insert a P node before the first child of DIV
Test and See‹/›

This example moves an element from its current position to a new position:

var elem = document.getElementById("myList2").lastElementChild;
var list1 = document.getElementById("myList1");
list1.insertBefore(elem, list1.childNodes[0]);
Test and See‹/›

Related References

HTML DOM Reference:node.hasChildNodes() method

HTML DOM Reference:node.appendChild() method

HTML DOM Reference:node.removeChild() method

HTML DOM Reference:node.replaceChild() method

HTML DOM Reference:document.createElement() method

HTML DOM Reference:document.createTextNode() method

HTML DOM Reference:document.adoptNode() method

HTML DOM Reference:document.importNode() method

HTML DOM Element Object