document.createElement() is used to create new HTML elements dynamically using JavaScript.
Instead of writing HTML manually, we generate UI components through JS.
const div = document.createElement("div");
div.textContent = "Hello World";
document.body.appendChild(div);
This is how modern web apps dynamically build interfaces.
function addParagraph(){
const p = document.createElement("p");
p.textContent = "This paragraph was created using createElement()";
document.getElementById("output1").appendChild(p);
}
4️⃣ Mini Project – Build a Dynamic List UI
function addItem(){
const value = document.getElementById("itemInput").value;
const li = document.createElement("li");
li.textContent = value;
document.getElementById("listOutput").appendChild(li);
}
5️⃣ Adding Attributes & Events
function createButton(){
const btn = document.createElement("button");
btn.textContent = "Dynamic Alert";
btn.addEventListener("click", function(){
alert("This button was created dynamically!");
});
document.getElementById("output2").appendChild(btn);
}
6️⃣ Best Practices
Use createElement for dynamic UI (forms, lists, cards)
Avoid innerHTML when possible (security reasons)
Attach events after creation
Use classList.add() for styling
Group multiple elements using DocumentFragment for performance
const fragment = document.createDocumentFragment();
for(let i=0;i<5;i++){
const div = document.createElement("div");
div.textContent = "Item " + i;
fragment.appendChild(div);
}
document.body.appendChild(fragment);
7️⃣ Why This Is Important?
Modern frameworks like React, Angular, and Vue internally create and manipulate DOM elements.
Understanding createElement helps you understand how UI libraries work internally.