Creating Elements
Create and insert new DOM elements dynamically — use createElement, textContent, and appendChild to build elements from JavaScript.
Creating Elements
So far you have selected and modified existing elements. Now you will learn to create new elements from scratch and add them to the page dynamically.
The Three Steps
// 1. Create the element
var li = document.createElement('li');
// 2. Add content and attributes
li.textContent = 'New Ninja';
li.className = 'ninja-item';
li.setAttribute('data-level', '5');
// 3. Append to the DOM
document.querySelector('#ninja-list').appendChild(li);
createElement
var div = document.createElement('div');
var p = document.createElement('p');
var a = document.createElement('a');
var img = document.createElement('img');
createElement creates an element in memory. It does not appear on the page until you append it somewhere in the DOM tree.
Appending and Inserting
| Method | Effect |
|---|---|
parent.appendChild(element) | Adds as the last child |
parent.prepend(element) | Adds as the first child |
parent.insertBefore(new, ref) | Inserts before the reference element |
element.remove() | Removes the element from the DOM |
Building a Complete Element
// Create a card element
var card = document.createElement('div');
card.className = 'card';
var title = document.createElement('h3');
title.textContent = 'New Blog Post';
var body = document.createElement('p');
body.textContent = 'This is the blog content.';
var deleteBtn = document.createElement('button');
deleteBtn.textContent = 'Delete';
deleteBtn.addEventListener('click', function(e) {
e.target.parentElement.remove();
});
// Assemble
card.appendChild(title);
card.appendChild(body);
card.appendChild(deleteBtn);
// Add to page
document.querySelector('.blog-list').appendChild(card);
Removing Elements
// Modern way
var item = document.querySelector('.item');
item.remove();
// Older way (for IE support)
var parent = item.parentNode;
parent.removeChild(item);
Key Takeaways
document.createElement(tag)creates a new element in memory- Set content with
textContent, styles withclassName, and attributes withsetAttribute appendChildadds it to the DOM;remove()takes it out- Build complex elements by nesting
appendChildcalls