English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
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.
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 BODY3Test 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.
All browsers fully support the insertBefore() method:
Method | |||||
insertBefore() | Is | Is | Is | Is | Is |
Parameter | Description |
---|---|
newNode | The node object you want to insert |
existingNode | You 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 |
Return value: | A Node object representing the inserted node |
---|---|
DOM Version: | DOM Level1 |
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 DIVTest 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‹/›
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