JavaScript: createElement

The document.createElement() method creates a new HTML element in memory. You must add it to the document separately.

What you will learn

Minimal example

const parent = document.querySelector('#parent');
const item = document.createElement('p');
item.textContent = 'Created with JavaScript';
if (parent) parent.appendChild(item);

createElement() only creates the node. The last line inserts it as the final child of #parent. Use textContent for plain text instead of assigning untrusted input to innerHTML.

Set attributes and classes

item.id = 'message';
item.className = 'notice';
item.setAttribute('aria-live', 'polite');

Common mistakes