JavaScript Reference ยท DOM: Document and Elements
Element.append() and prepend()
Reference for append() and prepend(): insert nodes or text as the last or first children of an element, with differences from appendChild and moving behavior.
append() inserts one or more nodes or strings after the last child of an element. prepend() inserts them before the first child. Strings are turned into text nodes, never parsed as HTML. Both are also available on Document and DocumentFragment.
Each call accepts any number of arguments, mixed freely, and keeps their order.
list.append(item1, item2, "text"); list.prepend(header);
Try it
Syntax
parent.append(...nodesOrStrings) parent.prepend(...nodesOrStrings)
| Name | Description |
|---|---|
nodesOrStrings |
Zero or more Node objects or strings. A string becomes a Text node with exactly that text. Other values are converted to strings. |
Return value: undefined.
Exceptions: a HierarchyRequestError DOMException if the insertion would break the tree rules, for example inserting an element into itself or into one of its own descendants.
Usage notes
- Moves, does not copy. A node that is already in the document is removed from its old place and inserted in the new one. To insert a copy, use
cloneNode(true). - Strings are text.
append("<b>x</b>")shows the tags literally. For HTML strings useinsertAdjacentHTML()with trusted input only. - Several arguments are inserted together in the given order, which is cheaper and tidier than a loop of single insertions. For hundreds of nodes build a
DocumentFragmentfirst. append()versusappendChild().appendChild()accepts exactly one node, returns it, and rejects strings.append()accepts many nodes and strings and returns nothing.- Reverse order surprise. Calling
prepend(a)thenprepend(b)leavesb, a. Callingprepend(a, b)once leavesa, b. - Replacing content.
replaceChildren(...nodes)empties the element and inserts the nodes in one step. - Beside, not inside. To insert next to an element instead, use
before()andafter().
Browser support
Supported by all current browsers. Very old browsers lack these methods and only have appendChild() and insertBefore().