JavaScriptDOM and events

document.createElement()

Creates a new HTML element with the given tag name, ready to be inserted into the page.

Returns
A new element (HTMLElement), not yet attached to the document.
On this page

Example

#
JavaScript
const list = document.querySelector('#tasks')

const item = document.createElement('li')
item.textContent = 'Solve the quiz'
item.classList.add('new')

console.log(item.isConnected)
list.append(item)
console.log(item.isConnected)
console.log(list.lastElementChild)
console.log(list.children.length)
Console
false
true
<li class="new">
2

Definition and usage

#

The document.createElement() method creates a new, empty element, such as li, div, or button. For now it only exists in memory: it won’t show up on the page until you insert it into the document with append(), prepend(), before(), or after().

Before you add the element, you can prepare it: set text through textContent, classes through classList, attributes through setAttribute() or properties (id, href, type), and attach event handlers. Building elements this way is safer than gluing HTML together in a string, since the text is never treated as code.

When adding several elements at once, pass them all to a single append() call, or collect them in a DocumentFragment. The browser will then update the page once instead of multiple times.

Syntax

#
Syntax
document.createElement(tagName)

Parameters

#
  • tagName

    string

    The tag name, e.g. "li", "button", or "img". Case doesn’t matter.

More examples

#
A button with an event handler
JavaScript
const button = document.createElement('button')
button.type = 'button'
button.textContent = 'Show hint'
button.addEventListener('click', () => console.log('Hint: use a for...of loop'))

document.querySelector('#toolbar').append(button)
button.click()
Console
Hint: use a for...of loop
A list built from an array of data
JavaScript
const players = [
  { name: 'Emma', points: 320 },
  { name: 'Jack', points: 280 },
  { name: 'Mia', points: 250 }
]

const items = players.map((player) => {
  const li = document.createElement('li')
  li.textContent = `${player.name}: ${player.points} pts`
  return li
})

document.querySelector('#ranking').append(...items)

console.log(document.querySelectorAll('#ranking li').length)
console.log(document.querySelector('#ranking li').textContent)
Console
3
Emma: 320 pts

Browser support

#

Widely available

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • A new element won’t appear on the page until you insert it, for example with append().
  • Set text through textContent. Then you don’t need to worry about special characters or security.
  • Insert several elements with a single append(...elements) call, instead of adding them one by one in a loop.

Related entries

#

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