JavaScript: createElement
The document.createElement() method creates a new HTML element in memory. You must add it to the document separately.
What you will learn
- How to create an element with a tag name
- How to set its text and attributes
- How to add the new element to the page
Minimal example
const parent = document.querySelector('#parent');
const item = document.createElement('p');
item.textContent = 'Created with JavaScript';
if (parent) parent.appendChild(item);createElement() only creates the node. The last line inserts it as the final child of #parent. Use textContent for plain text instead of assigning untrusted input to innerHTML.
Set attributes and classes
item.id = 'message';
item.className = 'notice';
item.setAttribute('aria-live', 'polite');Common mistakes
- Creating an element does not display it until you append it to the document.
- Use a valid tag name such as
divorli, without angle brackets. - Check that the parent element exists before appending.