Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท DOM: Document and Elements

document.createElement()

Reference for createElement(): build a new HTML element in memory, set its properties, then insert it into the page. Includes options, case rules and pitfalls.

document.createElement() creates a new element with the tag name you give it. The element exists only in memory: it has no parent and is not visible until you insert it with a method such as append() or before().

This is the safest way to build page content from data, because text you assign with textContent is never parsed as HTML.

JavaScript
const note = document.createElement("p");
note.textContent = "Saved.";
document.body.append(note);

Try it

Build a list from data
Nothing appears until you insert it

Syntax

JavaScript
document.createElement(tagName)
document.createElement(tagName, options)
Name Description
tagName The element's local name, such as "div" or "button". In an HTML document it is lowercased automatically.
options Optional object. The is property names a customized built-in element to create, such as { is: "fancy-button" }. Rarely needed.

Return value: a new Element of the matching interface (for example HTMLDivElement or HTMLButtonElement).

Exceptions: an InvalidCharacterError DOMException if tagName is not a valid name, such as "1abc" or "<div>".

Usage notes

  • Detached until inserted. Newly created elements have parentNode === null and isConnected === false. Build the whole subtree first, then insert it once.
  • Set text safely. Use textContent for text from users or servers. innerHTML parses markup and can run injected code in attributes.
  • Properties and attributes. Many attributes have properties (el.id, el.className, el.href). For others use setAttribute(). Custom data-* values go through el.dataset.
  • Unknown names are allowed. createElement("banana") gives an HTMLUnknownElement. Custom elements need a hyphen ("my-card") and are upgraded if registered.
  • Namespaces. SVG and MathML elements need createElementNS(), because createElement("circle") makes an HTML element that will not draw.
  • Event listeners you attach are kept when you insert the element, unlike markup inserted with innerHTML.
  • Many elements? Insert them together with a DocumentFragment or by passing several nodes to append().
  • Reusing markup. For repeated, structured pieces, a <template> or cloneNode() is shorter than rebuilding by hand.

Browser support

Supported in every browser. The options argument with is is supported in current browsers other than Safari-based ones for customized built-ins, so check a compatibility table before using it.