Embark on a journey of knowledge! Take the quiz and earn valuable credits.
Take A QuizChallenge yourself and boost your learning! Start the quiz now to earn credits.
Take A QuizUnlock your potential! Begin the quiz, answer questions, and accumulate credits along the way.
Take A Quiz
🧱 Introduction: Dynamic
Webpage Construction
Web development isn’t just about displaying static content —
it's about building interactive, dynamic user experiences. With
JavaScript and the DOM, you can:
Whether you’re creating a shopping cart, to-do list, or live
feed, this chapter will teach you how to create, insert, clone, and delete
DOM nodes using JavaScript.
🧩 DOM Creation Toolkit
Overview
Action |
Method |
Create element |
document.createElement() |
Add content |
.textContent,
.innerHTML |
Add attributes |
.setAttribute(),
.classList.add() |
Insert element |
.appendChild(),
.prepend(), .insertBefore() |
Clone element |
.cloneNode(true) |
Remove element |
.remove(), .removeChild() |
Replace element |
.replaceChild() |
✨ 1. Creating Elements with
createElement()
🔹 Syntax:
javascript
const
element = document.createElement('tagName');
🔹 Example:
javascript
const
div = document.createElement('div');
div.textContent
= 'Hello from JS!';
div.classList.add('box');
🔧 2. Setting Attributes
and Content
🧾 Setting content:
javascript
div.textContent
= 'New text'; // Plain text
div.innerHTML
= '<strong>Bold text</strong>'; // HTML tags
🧾 Setting attributes:
javascript
div.setAttribute('id',
'greetingBox');
div.setAttribute('data-index',
'3');
🧾 Styling:
javascript
div.style.backgroundColor
= 'lightblue';
📥 3. Inserting Elements
into the DOM
Once created, elements must be inserted into the live DOM
tree.
🔹 Common Methods:
Method |
Behavior |
appendChild() |
Adds as last child |
prepend() |
Adds as first
child |
insertBefore() |
Adds before a
reference node |
append() |
Adds nodes or
strings (modern) |
🔹 Example:
html
<div
id="container"></div>
javascript
const
container = document.getElementById('container');
const
newP = document.createElement('p');
newP.textContent
= 'This is a paragraph.';
container.appendChild(newP);
🧪 More Insertion Examples
javascript
container.prepend(newP);
// As first child
container.append('Some
text'); // Adds text node
const
referenceNode = document.querySelector('#someItem');
container.insertBefore(newP,
referenceNode); // Before specific node
🧱 4. Cloning DOM Elements
with cloneNode()
🔹 Syntax:
javascript
element.cloneNode(deep)
🔹 Example:
html
<div
class="card">
<h3>Product</h3>
<p>$20</p>
</div>
javascript
const
card = document.querySelector('.card');
const
copy = card.cloneNode(true);
document.body.appendChild(copy);
🗑️ 5. Removing Elements
🔹 Modern Way: .remove()
javascript
const
box = document.getElementById('box');
box.remove();
✅ Clean, simple, and modern.
Works in most browsers.
🔹 Traditional Way:
.removeChild()
javascript
const
parent = document.getElementById('container');
const
child = document.querySelector('.item');
parent.removeChild(child);
Required when you want more control or support for older
browsers.
🔄 6. Replacing Elements
with .replaceChild()
🔹 Syntax:
javascript
parent.replaceChild(newElement, oldElement);
🔹 Example:
html
<ul
id="menu">
<li
id="oldItem">Old</li>
</ul>
javascript
const
newItem = document.createElement('li');
newItem.textContent
= 'New';
const
oldItem = document.getElementById('oldItem');
const
menu = document.getElementById('menu');
menu.replaceChild(newItem,
oldItem);
🔧 Practical Example: Add
Items to a List
🔹 HTML:
html
<ul
id="todoList"></ul>
<button
id="addBtn">Add Task</button>
🔹 JavaScript:
javascript
const
list = document.getElementById('todoList');
const
btn = document.getElementById('addBtn');
btn.addEventListener('click',
() => {
const li = document.createElement('li');
li.textContent = 'New Task';
list.appendChild(li);
});
🎯 Build your first mini
dynamic app!
🧪 Real Use Case: Cloning
and Editing Cards
🔹 HTML:
html
<div
class="card">
<h3>Title</h3>
<p>Description</p>
</div>
🔹 JavaScript:
javascript
const
card = document.querySelector('.card');
for
(let i = 0; i < 3; i++) {
const copy = card.cloneNode(true);
copy.querySelector('h3').textContent = `Card
#${i+1}`;
document.body.appendChild(copy);
}
📐 Summary Table
Task |
Method |
Create element |
createElement() |
Set attributes |
setAttribute(),
.id, .className |
Insert element |
appendChild(),
prepend(), insertBefore() |
Clone element |
cloneNode(true) |
Remove element |
remove(),
removeChild() |
Replace element |
replaceChild() |
🧠 Best Practices
🛠️ Troubleshooting Tips
Issue |
Cause |
Fix |
appendChild not
working |
Element not created
properly |
Check createElement()
and selector |
Duplicates not showing |
Appended to
wrong parent |
Use
console.log() to debug |
Element disappears
after replace |
Replaced instead of
appended |
Double-check logic |
Error: “Not a child of this node” |
removeChild()
on wrong parent |
Use correct
parentNode |
📍 Summary: What You’ve
Learned
Next, we’ll cover events — making everything come
alive with user interaction!
A: The DOM (Document Object Model) is a
tree-like structure that represents your web page. JavaScript can access and
modify this structure to change elements, styles, content, and more—dynamically
and in real-time.
A: Not exactly. The DOM is a Web API provided by
the browser, but JavaScript interacts with it using built-in methods like
getElementById, querySelector, and addEventListener.
Use DOM methods like:
document.getElementById('id')
document.querySelector('.class')
document.querySelector('tag')
element.style.color
= "red";
element.style.backgroundColor
= "yellow";
Or better, toggle CSS classes:
element.classList.add('active');
element.classList.remove('hidden');
const
div = document.createElement('div');
div.textContent = "Hello!";
document.body.appendChild(div);
element.remove();
// Modern way
// OR
element.parentNode.removeChild(element);
// Older method
const
button = document.querySelector('button');
button.addEventListener('click',
function() {
alert('Button clicked!');
});
Please log in to access this content. You will be redirected to the login page shortly.
LoginReady to take your education and career to the next level? Register today and join our growing community of learners and professionals.
Comments(0)