The JavaScript createElement() method
The createElement() method creates a new element in memory. document.createElement("div") makes a fresh <div> that isn't on the page yet — you set its content and attributes, then insert it with appendChild(). It's the safe way to build elements from data, with no HTML-injection risk.
Overview
createElement() builds a new element node. You pass the tag name — "div", "li", "button" — and get back a real element you can work with. At this point it exists only in memory; it won't appear until you attach it to the document with appendChild() or prepend().
The standard rhythm is create, configure, append. Create the element, set its textContent, add classes via classList, set attributes with setAttribute(), then drop it into the page. This is how you turn an array of data into a list of DOM elements — often inside a forEach() loop.
Why bother when innerHTML can build markup from a string? Safety and clarity. Setting textContent on a created element can't inject scripts, so user-provided data is safe by default, whereas dropping untrusted strings into innerHTML risks XSS. For dynamic, data-driven UI, createElement() is the dependable choice. For better performance when adding many nodes, build them into a DocumentFragment first and append once.
Syntax
const el = document.createElement(tagName)
const li = document.createElement("li");
li.textContent = "New item";
li.classList.add("item");
list.appendChild(li); // now it's on the page
Parameters
The createElement() method accepts the following parameters.
| Parameter | Description |
|---|---|
tagName |
The tag name of the element to create, e.g. "div", "li", "button". |
Example
<ul id="list"></ul>
<script>
const fruits = ['Apple', 'Banana', 'Cherry'];
const list = document.getElementById('list');
fruits.forEach(name => {
const li = document.createElement('li');
li.textContent = name;
list.appendChild(li);
});
</script>
Best practices
- Follow the create-configure-append pattern: build it, set its content/attributes, then insert it.
- Prefer setting textContent over innerHTML for user data to avoid injection risks.
- Append many nodes via a
DocumentFragmentto avoid repeated reflows. - Remember the element isn't visible until you attach it with appendChild() or similar.
Frequently asked questions
How do I create a new element in JavaScript?
document.createElement("tag"), configure it, then add it to the page with appendChild().Why doesn't my created element show up?
container.appendChild(el).Should I use createElement() or innerHTML?
createElement() with textContent is safer for user data and clearer for complex structures; innerHTML is quicker for static markup but risky with untrusted input.How do I add many elements efficiently?
DocumentFragment and append the fragment once, so the page only reflows a single time.