Element. append()
Adds elements or text at the end of an element’s content.
- Returns
undefined- Changes the original
- Yes
Example
#const status = document.querySelector('#status')
const badge = document.createElement('strong')
badge.textContent = 'online'
status.append(' ', badge, ' for 5 minutes')
console.log(status.textContent)
console.log(status.innerHTML)Definition and usage
#The append() method inserts the given elements or strings as the element’s last children. It accepts any number of arguments, and turns strings into text nodes, inserted literally rather than as HTML.
Its older counterpart, appendChild(), accepts only a single node, doesn’t handle strings, and returns the added element. append() returns nothing, but it’s more convenient. The same family includes prepend() (inserts at the start), before() and after() (insert next to the element), and replaceWith().
An element can only be in one place in the document. If you add an element that’s already on the page, it gets moved, not copied. To copy it, use element.cloneNode(true).
Syntax
#element.append(node1, node2, …)
element.append(text)Parameters
#node1…nodeN
elements or strings
Nodes or strings to add at the end, in the given order.
More examples
#const queue = document.querySelector('#queue')
queue.append(queue.firstElementChild)
console.log(Array.from(queue.children, (li) => li.textContent))const box = document.querySelector('#box')
const paragraph = document.createElement('p')
console.log(box.appendChild(paragraph))
console.log(box.append('text'))
console.log(box.childNodes.length)const steps = document.querySelector('#steps')
const first = document.createElement('li')
first.textContent = 'Step 1'
steps.prepend(first)
steps.after('Done!')
console.log(Array.from(steps.children, (li) => li.textContent))
console.log(steps.nextSibling.textContent)Browser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- Add several elements with one call:
append(a, b, c)orappend(...list). - Strings in
append()are inserted as text. If you want to insert HTML code, useinsertAdjacentHTML(). - Adding an existing element moves it. If you need a copy, call
cloneNode(true)first.
Related entries
#- document.createElement()Creates a new HTML element with the given tag name, ready to be inserted into the page.
- Element.remove()Removes an element from the document along with all of its content.
- Node.cloneNode()Creates a copy of a node. With the argument true, it also copies all the content, meaning every element and text inside.
- Element.insertAdjacentHTML()Parses a string as HTML and inserts the resulting elements at a chosen position relative to an element.
- Node.textContentReads or sets all of an element’s text, without HTML markup.
- Array.prototype.push()Adds elements to the end of an array and returns its new length.
Spotted a mistake or missing an example? Write to us.