document.createElement()
| Since: | DOM Level 1(1998) |
|---|
Creates a new HTML element with the specified tag name. The created element is not yet added to the DOM, so you need to append it separately.
Syntax
var element = document.createElement("tagName");
Arguments
| Argument | Description |
|---|---|
| tagName | Specifies the tag name of the HTML element to create as a string. Case-insensitive. |
Return Value
Returns the newly created HTML element (an Element object). At this point, it has not been added to the DOM.
Sample Code
sample_createElement.html
<ul id="list"> <li>Existing item</li> </ul> <div id="fighters"></div> <table id="roster"> <thead><tr><th>Name</th><th>Style</th></tr></thead> <tbody id="roster-body"></tbody> </table>
sample_createElement.js
// Pattern 1: Basic usage
var newItem = document.createElement("li");
newItem.textContent = "New item";
var list = document.getElementById("list");
list.appendChild(newItem);
// Pattern 2: Set attributes and classes before appending to the DOM
var fighters = document.getElementById("fighters");
var names = ["Yagami Iori", "Kusanagi Kyo", "Terry Bogard"];
names.forEach(function(name) {
var btn = document.createElement("button");
btn.type = "button";
btn.className = "fighter-btn";
btn.setAttribute("data-name", name);
btn.textContent = name;
fighters.appendChild(btn);
});
// Pattern 3: Build nested elements and append them in one shot
var tbody = document.getElementById("roster-body");
var roster = [
{ name: "Yagami Iori", style: "Yagami-ryu Old Fighting Style" },
{ name: "Kusanagi Kyo", style: "Kusanagi-ryu Old Fighting Style" },
{ name: "Terry Bogard", style: "Southtown" },
{ name: "Blue Mary", style: "Freelance Agent" }
];
roster.forEach(function(fighter) {
var tr = document.createElement("tr");
var tdName = document.createElement("td");
tdName.textContent = fighter.name;
tr.appendChild(tdName);
var tdStyle = document.createElement("td");
tdStyle.textContent = fighter.style;
tr.appendChild(tdStyle);
tbody.appendChild(tr); // Append the finished tr element to tbody.
});
Description
document.createElement() is a method that creates a new HTML element. The created element exists only in memory and is not yet displayed on the page. To display it on the page, you need to add it as a child of an existing element using a method such as parentElement.appendChild().
Before adding an element to the DOM, you can freely customize it — for example, set its text with element.textContent, set attributes with element.setAttribute(), or add CSS classes with element.classList.
Browser Compatibility
4 or earlier ×
5 or earlier ×
Android Browser
37+ ○
4 or earlier ×
Chrome Android
36+ ○
17 or earlier ×
Firefox Android
79+ ○
3 or earlier ×If you find any errors or copyright issues, please contact us.