Creating Elements
Overview
Sometimes you need to build entirely new HTML structures from scratch using JavaScript (this is exactly what React does under the hood!).
You use document.createElement() to create a raw Node in memory. Then, you configure its classes and text. Finally, you "mount" it to the live page using methods like append() or appendChild().
Syntax
// 1. CREATE the raw element in memory
const newDiv = document.createElement('div');
// 2. CONFIGURE its properties
newDiv.classList.add('card');
newDiv.innerText = "Hello from JS!";
// 3. MOUNT it to the actual DOM
const container = document.querySelector('.container');
container.append(newDiv);const badElement = document.querySelector('.advertisement');
// The modern way to delete an element from the DOM
badElement.remove();Common Pitfalls
- Forgetting Step 3 (Mounting). A very common mistake is creating an element, configuring it perfectly, and then wondering why it isn't showing up on the screen.
createElementonly creates it in the computer's memory. It must be appended to a parent to become visible.
Interview Questions
DocumentFragment and why is it useful?If you need to insert 100 new elements into the DOM, calling append() 100 times causes 100 expensive browser re-renders. A DocumentFragment is a lightweight, invisible container. You append all 100 elements to the fragment in memory, and then append the fragment to the DOM once, causing only 1 re-render.
Real-World Example
Fetching a list of comments from an API and generating a new <li> element for every comment.
comments.forEach(text => {
const li = document.createElement('li');
li.innerText = text;
ul.append(li);
});Check Your Knowledge
Test your understanding of Creating Elements with these quick questions.