JS Learning

DOM Manipulation

Lesson Progress0%

Section 3 of 4

Creating Elements

Creating Elements

Topic Overview

Take your time to understand each concept. Practice with the examples below!

Sometimes you need to add completely new elements to the page - like adding items to a shopping cart or messages to a chat. JavaScript lets you create elements from scratch!

The Creation Process (like building with LEGO):

  • Step 1 - Create the element
const newDiv = document.createElement('div');
const newButton = document.createElement('button');
  • Step 2 - Add content and properties
newButton.textContent = "Click Me!";
newButton.className = "btn btn-primary";
newButton.id = "myButton";
  • Step 3 - Add it to the page
// Add as last child
parentElement.appendChild(newButton);
// Add before another element
parentElement.insertBefore(newButton, existingElement);

Complete example - Adding an item to a list:

const list = document.getElementById('shopping-list');
const newItem = document.createElement('li');
newItem.textContent = "Milk";
list.appendChild(newItem);

Removing elements:

  • element.remove() - Remove the element
  • parentElement.removeChild(childElement) - Remove a child

Creating complex structures:

const card = document.createElement('div');
card.className = 'card';
const title = document.createElement('h3');
title.textContent = 'Card Title';
const content = document.createElement('p');
content.textContent = 'Card content goes here';
card.appendChild(title);
card.appendChild(content);
document.body.appendChild(card);

Real-world uses:

  • Dynamic shopping carts
  • Comment sections
  • Todo lists
  • Chat messages
  • Form fields