01 / 21

Creating & Appending
DOM Elements

Learn to dynamically build web page content with JavaScript by creating new elements, configuring them, and inserting them into the Document Object Model.

JavaScript

What Is the DOM?

The Document Object Model is a tree-like representation of your HTML page. Every tag becomes a node in this tree, and JavaScript can read, modify, create, or remove any node at any time.

document <html> <head> <body> <h1> <div> new element?

Why Create Elements Dynamically?

Hard-coding every HTML element is fine for static pages, but modern web apps need to respond to user actions, display fetched data, and build UI on the fly.

User Interaction
Add a new to-do item when a user clicks "Add".
API Data
Build a product card for each item returned from a server.
Conditional UI
Show an error banner only when validation fails.

Key Vocabulary

Node
Any single point in the DOM tree: an element, text, comment, etc.
Element
A specific node type representing an HTML tag such as <div> or <p>.
Parent / Child
A node that contains another is the parent; the contained node is its child.

The Core Pattern

1. CREATE createElement() 2. CONFIGURE textContent, class, etc. 3. APPEND appendChild() const el = document. createElement ( 'p' el. textContent = 'Hello, world!' ; el. classList . add ( 'greeting' document. body . appendChild ( el

document.createElement in Detail

document.createElement(tagName) returns a brand-new element node that is not yet attached to the page. It lives only in memory until you insert it.

// Create a <div> element
const card = document.createElement('div');

// Create an <img> element
const img = document.createElement('img');

// Create a <ul> element
const list = document.createElement('ul');

Configuring the Element

Once created, you can set any property or attribute before inserting it into the DOM:

1
textContent: sets the visible text inside the element.
2
classList.add(): adds one or more CSS classes.
3
setAttribute(name, value): sets any HTML attribute like src, href, or data-*.
4
style.property: applies inline CSS (use sparingly).
const btn = document.createElement('button');
btn.textContent = 'Click Me';
btn.classList.add('primary-btn');
btn.setAttribute('type', 'button');

appendChild vs. append

Both methods insert content into a parent, but they differ in important ways:

appendChild() append()
Accepts One Node only Nodes and strings
Multiple items No Yes
Returns The appended node undefined
Browser support All (incl. IE) Modern only

Other Insertion Methods

prepend()
Inserts before the first child of the parent.
before() / after()
Inserts as a sibling, immediately before or after the target element.
insertBefore()
Classic method: parent.insertBefore(newNode, referenceNode).

How to Apply the Pattern

1
Identify the parent: use querySelector or getElementById to grab the container you want to insert into.
2
Create the element: call document.createElement(tag) with the desired tag name.
3
Set content and attributes: assign textContent, classList, src, href, or any other properties.
4
Append to the parent: call parent.appendChild(element) to make it visible on the page.
5
Repeat or compose: nest elements inside each other before appending for complex structures.

Example 1: Adding a List Item

Add a new <li> to an existing <ul> when the user types a task and clicks "Add".

// HTML: <ul id="tasks"></ul>
// HTML: <input id="taskInput">

const ul = document.getElementById('tasks');
const input = document.getElementById('taskInput');

const li = document.createElement('li');
li.textContent = input.value;
ul.appendChild(li);

Example 2: Building a Card Component

Create a multi-element card from data, then append the whole thing at once:

const card = document.createElement('div');
card.classList.add('card');

const title = document.createElement('h3');
title.textContent = 'Product Name';

const price = document.createElement('p');
price.textContent = '$29.99';

// Compose children into the card
card.appendChild(title);
card.appendChild(price);

// Then add the complete card to the page
document.querySelector('.products').appendChild(card);

Example 3: Looping with forEach

Generate elements from an array of data using a loop:

const fruits = ['Apple', 'Banana', 'Cherry'];
const ul = document.getElementById('fruit-list');

fruits.forEach(function(fruit) {
  const li = document.createElement('li');
  li.textContent = fruit;
  li.classList.add('fruit-item');
  ul.appendChild(li);
});

DocumentFragment for Performance

When adding many elements, each appendChild call triggers the browser to recalculate layout. A DocumentFragment batches them into one operation:

const frag = document.createDocumentFragment();

for (let i = 0; i < 100; i++) {
  const p = document.createElement('p');
  p.textContent = 'Item ' + i;
  frag.appendChild(p);
}

// Single DOM update
document.body.appendChild(frag);

Common Mistakes

✕ Using innerHTML for single elements
innerHTML re-parses the entire container, destroys event listeners, and is slower. Use createElement instead.
✕ createElement outside a loop
Reusing the same variable without calling createElement again just moves the same node instead of creating new ones.
✕ Forgetting to append
Creating an element without appending it means it exists only in memory and never appears on the page.

Method Summary

Method Purpose Returns
createElement(tag) Create a new element node The new element
createTextNode(text) Create a raw text node The text node
appendChild(node) Insert as last child The appended node
append(...nodes) Insert nodes and/or strings undefined
prepend(...nodes) Insert as first child undefined
insertBefore(new, ref) Insert before a reference The inserted node

Question 1 of 5

What does document.createElement('li') return?

Question 2 of 5

Which line of code correctly sets the text content of a newly created paragraph?

Question 3 of 5

You run this code. How many <p> elements appear on the page?

const p = document.createElement('p');
p.textContent = 'Hello';
document.body.appendChild(p);
document.body.appendChild(p);

Question 4 of 5

What is the main advantage of using a DocumentFragment when adding many elements?

Question 5 of 5

Which method inserts a new node before the first child of a parent element?