English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
appendChild()The purpose of the method is to add a node to the end of the child node list of the specified parent node.
If the given child node is a reference to an existing node in the document, appendChild() moves it from its current position to the new position (see the "More examples" section below).
UsageinsertBefore()The method can insert a new child node before the specified existing child node.
node.appendChild(node)
var newElem = document.createElement("h3 // Create a new h3Element var newContent = document.createTextNode("Hello, nice to meet you!"); // Create some text content newElem.appendChild(newContent); // Add the text node to the newly created h3 document.body.appendChild(newElem); // Add the newly created element and its content to the DOMTest See‹/›
Note:If you need to create a new element with text, remember to create the text as a Text node, then append it to the element, and then append the element to the document.
All browsers fully support the appendChild() method:
Method | |||||
appendChild() | Is | Is | Is | Is | Is |
Parameter | Description |
---|---|
node | The node (usually an element) to be appended to the given parent node |
Return value: | The returned value is the appended child element |
---|---|
DOM version: | DOM level1 |
Create a <p> element and append it to a <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 the text to <p> document.getElementById("demo").appendChild(para);// Append <p> to <div>Test See‹/›
Create a <p> element and append it to the end of the document body:
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 the text to <p> document.body.appendChild(para);// Append <p> to bodyTest See‹/›
This example moves an element from its current position to a new position:
var elem = document.getElementById("myList2").lastElementChild; document.getElementById("myList1).appendChild(elem);Test See‹/›
HTML DOM Reference:node.hasChildNodes() method
HTML DOM Reference:node.insertBefore() 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