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.
const note = document.createElement("p"); note.textContent = "Saved."; document.body.append(note);
Try it
Syntax
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 === nullandisConnected === false. Build the whole subtree first, then insert it once. - Set text safely. Use
textContentfor text from users or servers.innerHTMLparses markup and can run injected code in attributes. - Properties and attributes. Many attributes have properties (
el.id,el.className,el.href). For others usesetAttribute(). Customdata-*values go throughel.dataset. - Unknown names are allowed.
createElement("banana")gives anHTMLUnknownElement. Custom elements need a hyphen ("my-card") and are upgraded if registered. - Namespaces. SVG and MathML elements need
createElementNS(), becausecreateElement("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
DocumentFragmentor by passing several nodes toappend(). - Reusing markup. For repeated, structured pieces, a
<template>orcloneNode()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.