JavaScript Document createElement() Method

Beginner
⏱️ 12 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Baseline Widely available
Instance method

What You’ll Learn

document.createElement() is an instance method that creates a new element with the tag name you pass (see MDN Document: createElement()). Learn the lowercase HTML rule, how to set content and attributes, insert nodes with appendChild / insertBefore, the optional options object for customized built-ins, how it compares to createElementNS(), and five try-it labs.

01

Kind

Instance method

02

Arg

localName

03

Returns

HTMLElement

04

Attach

append / insert

05

Name rule

lowercase

06

Status

Baseline

Introduction

Static HTML is great for the first paint. Dynamic pages need JavaScript to build buttons, cards, list items, and alerts after the page loads.

document.createElement(localName) is the standard way to create those nodes. You get a real DOM element — not an HTML string — then set its text, attributes, and listeners before attaching it to the tree.

💡
Create → configure → attach

1) const el = document.createElement("div")
2) Set textContent, className, id, listeners
3) parent.appendChild(el) (or append / insertBefore)

Prefer this over building markup with string concatenation and innerHTML when you control structure and text separately — it avoids accidental HTML injection and keeps nodes easy to update.

Related tutorials: createDocumentFragment(), appendChild(), createAttribute().

Understanding document.createElement()

An instance method on the page’s document object (MDN Document interface).

  • ParameterlocalName: tag name string (for example "div", "button").
  • Return value — a new Element; on HTML documents usually an HTMLElement (MDN).
  • Unknown tags — unrecognized names create an HTMLUnknownElement (MDN).
  • HTML casing — on HTML documents, localName is lowercased before creation (MDN).
  • Detached — the node is not in the page until you insert it.
  • Options — optional object with is or customElementRegistry (not both) for custom elements (MDN).

📝 Syntax

General forms of Document.createElement (MDN):

JavaScript
createElement(localName)
createElement(localName, options)

Parameters

  • localName — string for the element type. Do not use qualified names like "html:a" (MDN). On HTML documents the name is lowercased. In Firefox, Opera, and Chrome, createElement(null) behaves like createElement("null") (MDN).
  • options (optional) — object. Only one of is or customElementRegistry may be set (MDN):
    • is — tag name of a customized built-in defined with customElements.define(..., { extends: "..." }); the element gets an is attribute.
    • customElementRegistry — a CustomElementRegistry for a scoped custom element registry.

Return value

The new Element. For an HTMLDocument (the common case), MDN: a new HTMLElement is returned.

Exceptions

  • InvalidCharacterErrorlocalName is not a valid element name (MDN).
  • NotSupportedError — both is and customElementRegistry are specified (MDN).

MDN basic pattern

JavaScript
const newDiv = document.createElement("div");
const newContent = document.createTextNode("Hi there and greetings!");
newDiv.appendChild(newContent);

const currentDiv = document.getElementById("div1");
document.body.insertBefore(newDiv, currentDiv);

⚡ Quick Reference

GoalCode
Create a divdocument.createElement("div")
Set textel.textContent = "Hello"
Set class / idel.className = "card" / el.id = "x"
Append to bodydocument.body.appendChild(el)
Insert before a nodeparent.insertBefore(el, ref)
Customized built-increateElement("ul", { is: "expanding-list" })
MDN statusBaseline Widely available

🔍 At a Glance

Four facts about document.createElement().

Returns
HTMLElement

typical HTML doc

Name
lowercase

HTML documents

In tree?
not yet

must append

Unknown tag
HTMLUnknownElement

MDN

📋 createElement vs string HTML

createElementinnerHTML string
ResultLive element nodeParsed markup tree
Text safetyEasy with textContentRisk if string is untrusted
ListenersAdd before/after attachMust re-bind after parse
Best forStructured UI from JSTrusted HTML templates

Examples Gallery

Examples follow MDN Document: createElement() and everyday DOM patterns beginners use first.

📚 Getting Started

Create a node, give it text, and insert it into the document.

Example 1 — MDN basic: create, text, insertBefore

Official MDN pattern: build a div, add a text node, insert it before #div1.

JavaScript
function addElement() {
  const newDiv = document.createElement("div");
  const newContent = document.createTextNode("Hi there and greetings!");
  newDiv.appendChild(newContent);

  const currentDiv = document.getElementById("div1");
  document.body.insertBefore(newDiv, currentDiv);
}

addElement();
Try It Yourself

How It Works

createElement builds a detached node; createTextNode adds safe text; insertBefore places it in the live tree before an existing sibling.

Example 2 — Tag names become lowercase (HTML)

On HTML documents, mixed-case tag names are lowercased (MDN).

JavaScript
const el = document.createElement("BUTTON");

console.log(el.tagName);   // "BUTTON" (DOM returns uppercase HTML tag names)
console.log(el.localName); // "button"
console.log(el instanceof HTMLButtonElement); // true
Try It Yourself

How It Works

Creation uses the lowercased local name. HTML element tagName is still reported in uppercase — that is normal for HTML, not a bug.

📈 Practical Patterns

Buttons with events, unknown tags, and the options.is form.

Example 3 — Button with text, class, and click handler

Everyday UI: create a control, style it, listen for clicks, then append.

JavaScript
const btn = document.createElement("button");
btn.type = "button";
btn.className = "primary";
btn.textContent = "Save";
btn.addEventListener("click", () => {
  console.log("Saved!");
});

document.body.appendChild(btn);
console.log(btn.outerHTML);
// <button type="button" class="primary">Save</button>
Try It Yourself

How It Works

Properties and listeners are set on the live object before attach. Using textContent keeps the label as plain text.

Example 4 — Unknown tag → HTMLUnknownElement

MDN: if localName is not recognized, you still get an element — typed as unknown.

JavaScript
const mystery = document.createElement("fancy-widget");

console.log(mystery.localName);                    // "fancy-widget"
console.log(mystery instanceof HTMLUnknownElement); // true
console.log(mystery instanceof HTMLElement);        // true

mystery.textContent = "Custom-looking tag";
document.body.appendChild(mystery);
Try It Yourself

How It Works

Autonomous custom elements (with a hyphen) start as unknown until defined with customElements.define. The node is still insertable and styleable.

Example 5 — Customized built-in with options.is (MDN)

MDN web component pattern: extend a built-in (ul), then create it with { is: "..." }. Support for customized built-ins varies — check compatibility.

JavaScript
class ExpandingList extends HTMLUListElement {
  constructor() {
    super();
    // constructor body omitted for brevity
  }
}

customElements.define("expanding-list", ExpandingList, { extends: "ul" });

const expandingList = document.createElement("ul", { is: "expanding-list" });
console.log(expandingList.getAttribute("is")); // "expanding-list"
console.log(expandingList instanceof ExpandingList); // true where supported
Try It Yourself

How It Works

The first argument is still the built-in tag ("ul"). The is option links it to the custom definition and sets the is attribute (MDN). Some browsers historically allowed a string instead of an options object for compatibility.

🚀 Common Use Cases

  • Dynamic UI — build cards, rows, toasts, and form controls from data.
  • Safer text — pair with textContent instead of untrusted HTML strings.
  • Event wiring — attach listeners on the element object before or after insert.
  • Lists and tables — create many children, optionally via a DocumentFragment.
  • Custom elements — create autonomous tags or customized built-ins (where supported).
  • Not for SVG tags in HTML — use createElementNS for SVG/MathML namespaces.

🧠 How createElement() Works

1

Pass localName

MDN: a tag name string; on HTML documents it is converted to lowercase.

Input
2

Browser builds a node

Returns an HTMLElement, or HTMLUnknownElement if unrecognized.

Create
3

Configure the element

Set text, attributes, classes, and event listeners while detached.

Setup
4

Insert into the DOM

Use appendChild, append, or insertBefore so users can see it.

📝 Notes

  • MDN: Baseline Widely available since July 2015 (* some parts, like options, may vary).
  • Do not pass qualified names such as "html:a" to createElement (MDN).
  • Invalid localName values throw InvalidCharacterError (MDN).
  • Setting both is and customElementRegistry throws NotSupportedError (MDN).
  • Created nodes are detached until you insert them.
  • For SVG or other namespaces, use document.createElementNS() (MDN See also).
  • Related: appendChild(), createDocumentFragment(), createAttribute().

Browser Support

Document.createElement() is Baseline Widely available on MDN (since July 2015). Logos use the shared browser-image-sprite.png sprite from this project. Optional features such as customized built-ins (options.is) may have varying support.

Baseline Widely available

Document.createElement()

Create HTML elements in every major browser — the foundation of dynamic DOM UI.

Baseline Widely available
Google Chrome Supported
Yes
Mozilla Firefox Supported
Yes
Apple Safari Supported
Yes
Microsoft Edge Supported
Yes
Opera Supported
Yes
Internet Explorer Supported (legacy)
Yes
createElement() Wide

Bottom line: Use createElement for HTML nodes, createElementNS for SVG/MathML, and always append the node so it appears in the page.

Conclusion

document.createElement(localName) creates a detached HTML element. Configure it with properties and listeners, then insert it with appendChild, append, or insertBefore. That three-step habit is the core of building dynamic pages without unsafe HTML strings.

Continue with createDocumentFragment(), createElementNS(), or the JavaScript hub.

💡 Best Practices

✅ Do

  • Use textContent for plain text labels
  • Configure the node before appending when possible
  • Batch many inserts with createDocumentFragment()
  • Use createElementNS for SVG / MathML
  • Validate tag names to avoid InvalidCharacterError

❌ Don’t

  • Expect the element to appear without inserting it
  • Pass qualified names like "html:a" (MDN)
  • Inject untrusted HTML with innerHTML when createElement + textContent suffices
  • Set both is and customElementRegistry
  • Use createElement("svg") when you need a real SVG namespace element

Key Takeaways

Knowledge Unlocked

Five things to remember about createElement()

Builds real DOM elements for dynamic UI.

5
Core concepts
🔗02

Attach

append / insert

step 3
📄03

Name

lowercase

HTML
04

Prefer

textContent

safe
🛡05

Status

Baseline

2015

❓ Frequently Asked Questions

MDN: Document.createElement() creates a new element with the given localName (tag name). On an HTML document it returns an HTMLElement (or HTMLUnknownElement if the tag is not recognized).
No. MDN marks Document.createElement() as Baseline Widely available (since July 2015). It is not Deprecated, Experimental, or Non-standard. Some optional features (like customized built-ins via options.is) have varying support.
A new Element. For the usual HTML document case, MDN says an HTMLElement is returned. Unknown tag names yield HTMLUnknownElement.
Yes on HTML documents (MDN). createElement() converts localName to lowercase before creating the element. Do not pass qualified names like "html:a".
Use document.createElementNS(namespaceURI, qualifiedName) when you need an explicit namespace — for example SVG (http://www.w3.org/2000/svg) or MathML. Prefer createElement() for normal HTML tags.
createElement() only builds a detached node. Attach it with appendChild(), append(), prepend(), insertBefore(), or replaceChild() on a parent that is already in the document.
Did you know?

MDN notes that creating an element does not put it on the page by itself. Beginners often call createElement, set textContent, and wonder why nothing appears — until they remember appendChild or append. The node lives in memory first; insertion makes it visible.

Next: createElementNS()

Learn how to create SVG, MathML, and other namespaced elements with createElementNS().

createElementNS() →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful