JavaScript createElement() – Build UI Dynamically

Programmer’s Picnic • DOM Mastery Series

1️⃣ What is createElement()?

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.

2️⃣ How UI is Built Dynamically

Steps:

  1. Create element
  2. Add content
  3. Set attributes / styles
  4. Append to DOM
const button = document.createElement("button"); button.textContent = "Click Me"; button.className = "myButton"; document.body.appendChild(button);

3️⃣ Live Demo – Add Paragraph

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

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.

It is foundational for: