intermediate

Create Element Dynamically

Create and append new HTML elements using JavaScript.

Dynamic element creation enables building interactive interfaces without hardcoded HTML. This exercise teaches you DOM manipulation fundamentals for creating rich, dynamic web applications.

📚 Concepts & Theory

Creating DOM elements dynamically is fundamental to building interactive web applications. JavaScript provides methods to create, configure, and insert elements into the page.

Understanding Dynamic Element Creation:

Basic Process:

  • Create element with document.createElement()

  • Configure properties (text, attributes, classes)

  • Insert into DOM with appendChild() or other methods
Step-by-Step:

1. Create Element:

const div = document.createElement("div");
const button = document.createElement("button");
const paragraph = document.createElement("p");

2. Set Content:

div.textContent = "Hello World";
div.innerHTML = "<strong>Bold</strong> text";

3. Add Attributes:

div.id = "myDiv";
div.className = "container";
div.setAttribute("data-id", "123");

4. Add Classes:

div.classList.add("card", "shadow");

5. Insert into DOM:

appendChild() - Add as Last Child:

parentElement.appendChild(newElement);

insertBefore() - Add Before Reference:

parent.insertBefore(newElement, referenceElement);

prepend() - Add as First Child:

parent.prepend(newElement);

append() - Add Multiple:

parent.append(child1, child2, "text");

after()/before() - Sibling Position:

reference.after(newElement);
reference.before(newElement);

Complete Example:

// Create a card element
const card = document.createElement("div");
card.className = "card";

const title = document.createElement("h3");
title.textContent = "Card Title";

const description = document.createElement("p");
description.textContent = "Card description";

card.appendChild(title);
card.appendChild(description);

document.body.appendChild(card);

Modern Alternatives:

insertAdjacentHTML():

parent.insertAdjacentHTML("beforeend", "<div>Hello</div>");

Template Literals + innerHTML:

parent.innerHTML += <div class="card">${title}</div>;
// ⚠️ Recreates all children (slow)

Document Fragments (Performance):

const fragment = document.createDocumentFragment();
for (let i = 0; i < 1000; i++) {
fragment.appendChild(createListItem(i));
}
parent.appendChild(fragment); // Single reflow

🎯 Your Challenge

Create a new paragraph and add it to the page.

📝 Starter Code

JavaScript
// HTML: <div id="container"></div>

function addParagraph(text) {
  // Your code here
}
  • Use document.createElement() to create a new element
  • Pass the HTML tag name as a string (no angle brackets)
  • Set textContent or innerHTML to add content
  • Use appendChild() to add element to the page
  • You need both creation AND insertion

Solution

JavaScript
function addParagraph(text) {
  const p = document.createElement('p');
  p.textContent = text;
  document.getElementById('container').appendChild(p);
}

addParagraph('Hello World');

Explanation

This solution demonstrates the standard process for creating DOM elements: 1) Use document.createElement(tagName) to create a new element node, 2) Configure the element by setting properties like textContent, className, or attributes, 3) Insert it into the DOM using appendChild() or similar methods. The createElement() method creates an element in memory but doesn't add it to the page until you explicitly insert it. This approach is cleaner and safer than innerHTML for dynamic content. Time complexity: O(1) for creation, O(1) for insertion.

⚠️ Common Mistakes to Avoid

  • Creating element but forgetting to append it to DOM
  • Using innerHTML in a loop (recreates all children each time)
  • Not setting textContent or innerHTML (empty elements)
  • Confusing createElement(tag) with getElementById(id)
  • Trying to append the same element twice (moves it, doesn't duplicate)

❓ Frequently Asked Questions

No, it only creates the element in memory. You must insert it with appendChild() or similar methods.
No, createElement() creates one element. Use loops or document fragments for multiple elements.
textContent sets plain text (safe). innerHTML sets HTML markup (potential XSS risk with user input).
Use document fragments to batch insertions and trigger only one DOM reflow.

🔗 Related Exercises