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
<ul id="list"> <li>Existing item</li> </ul>
// Create a new li element.
var newItem = document.createElement("li");
newItem.textContent = "New item";
// Append it to the list.
var list = document.querySelector("#list");
list.appendChild(newItem);
// You can also set attributes and classes before appending.
var link = document.createElement("a");
link.setAttribute("href", "https://example.com");
link.classList.add("external-link");
link.textContent = "External link";
document.body.appendChild(link);
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.