JavaScriptDOM and events

Element.append()

Adds elements or text at the end of an element’s content.

Returns
undefined
Changes the original
Yes
On this page

Example

#
JavaScript
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)
Console
Status: online for 5 minutes
Status: <strong>online</strong> for 5 minutes

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

#
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

#
Adding an existing element moves it
JavaScript
const queue = document.querySelector('#queue')

queue.append(queue.firstElementChild)

console.log(Array.from(queue.children, (li) => li.textContent))
Console
['Jack', 'Mia', 'Emma']
append() versus appendChild()
JavaScript
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)
Console
<p>
undefined
2
prepend() and after()
JavaScript
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)
Console
['Step 1', 'Step 2']
Done!

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) or append(...list).
  • Strings in append() are inserted as text. If you want to insert HTML code, use insertAdjacentHTML().
  • Adding an existing element moves it. If you need a copy, call cloneNode(true) first.

Related entries

#

Spotted a mistake or missing an example? Write to us.