The Document Object Model (DOM) is the foundation of dynamic and interactive web pages, allowing developers to programmatically interact with a webpage’s structure and content. “JavaScript DOM Manipulation” is your comprehensive guide to mastering this essential technology. https://www.amazon.com/dp/B0DR3G43B9 or CAN https://www.amazon.ca/dp/B0DR3G43B9
This book begins by introducing the basics of the DOM tree, covering topics like parent-child relationships, node types, and DOM traversal methods. As you progress, you’ll learn to effectively select elements using methods like getElementById and querySelector, and to modify their content, attributes, and styles dynamically. The book also delves into advanced topics such as event handling, delegation, and custom events, providing a well-rounded understanding of how to create interactive user experiences.
Each chapter is packed with real-world examples, coding exercises, and multiple-choice quizzes to solidify your knowledge. You’ll discover how to create, append, and remove elements, manage browser events efficiently, and integrate DOM manipulation techniques with browser APIs like localStorage and fetch. By the end of this book, you’ll be equipped with practical skills to optimize performance, streamline code, and handle complex user interactions with ease.
Whether you’re a beginner stepping into web development or an experienced developer looking to refine your JavaScript skills, this book provides actionable insights for mastering DOM manipulation. With a focus on hands-on learning, “JavaScript DOM Manipulation” ensures you can apply what you learn immediately, bridging the gap between theory and real-world application.
JavaScript Handbook JavaScript DOM Manipulation
Summary
“JavaScript DOM Manipulation” offers an in-depth guide to understanding and mastering the DOM, a critical aspect of modern web development. From learning the fundamentals of DOM traversal and manipulation to implementing advanced techniques like event delegation and browser API integration, this book equips readers with the skills to create dynamic, interactive web applications.
Designed for developers of all levels, this book combines theory with practical application, featuring coding exercises, quizzes, and real-world examples. By the end, readers will have the confidence to apply DOM manipulation techniques in any project, building seamless and engaging user experiences.
Introduction
Welcome to “JavaScript DOM Manipulation”, your ultimate guide to mastering one of the most dynamic aspects of modern web development. This book is designed to empower developers of all skill levels by providing a clear and comprehensive understanding of the Document Object Model (DOM)—the backbone of dynamic, interactive web pages.
Through hands-on exercises, detailed explanations, and practical examples, you’ll learn how to traverse, select, modify, and optimize DOM elements effectively. This book will guide you step-by-step, from the basics of the DOM tree to advanced topics such as event delegation, custom events, and browser API integration.
Whether you’re a beginner building your first website or an experienced developer looking to refine your skills, this book offers actionable insights to help you create seamless user experiences. Get ready to unlock the full potential of JavaScript and transform the way you interact with web technologies.
JavaScript: DOM Tree and Traversal
The Document Object Model (DOM) represents a web page as a hierarchical tree of nodes. Understanding the DOM and how to traverse it is fundamental for dynamically interacting with the content and structure of a webpage.
Introduction to the DOM
The Document Object Model (DOM) is a programming interface for HTML and XML documents. It defines the structure of a document and how scripts can access and manipulate it. When a web page is loaded, the browser creates a DOM that can be modified using JavaScript.
Understanding the DOM Tree Structure
The DOM represents the page as a hierarchical tree:
- Document (root of the DOM)
- html element
- head element
- title, meta, link elements, etc.
- body element
- header, nav, section, div, p, img, etc.
- head element
- html element
Each element in the DOM is a node, and these nodes have relationships to each other—parent-child, siblings, ancestors, and descendants.
Node Types
Common node types include:
- Element nodes: Represent HTML elements (e.g., <div>, <p>, <ul>).
- Text nodes: Represent the text inside elements.
- Comment nodes: Represent HTML comments (<!– comment –>).
- Document node: The root node representing the entire document.
You can check a node’s type using nodeType:
- 1 = Element
- 3 = Text node
- 8 = Comment
- 9 = Document
Parent, Child, and Sibling Relationships
- Parent Node: The element that directly contains another node.
Example: <body> is the parent of <div> if <div> is inside <body>. - Child Nodes: Nodes that are directly contained within another node.
Example: <li> elements are children of a <ul>. - Sibling Nodes: Nodes that share the same parent.
Example: Two <li> elements inside the same <ul> are siblings.
DOM Traversal Methods
There are several properties and methods to navigate the DOM tree:
- Parent Node Access
- node.parentNode
- element.parentElement
- Child Node Access
- node.childNodes (NodeList including text nodes and comments)
- element.children (HTMLCollection of only element nodes)
- element.firstChild, element.lastChild (include text nodes)
- element.firstElementChild, element.lastElementChild (element nodes only)
- Sibling Access
- node.previousSibling / node.nextSibling (might include text nodes)
- element.previousElementSibling / element.nextElementSibling (elements only)
- Other Useful Methods
- document.getElementById()
- document.querySelector()
- document.querySelectorAll()
- element.closest(selector)
- element.matches(selector)
Example:
const ul = document.querySelector(‘ul’);
console.log(ul.parentNode); // Logs the parent of the <ul>, typically the <body>
console.log(ul.children); // Logs all element children of the <ul>
Selecting Nodes
You can select elements using:
- ID: document.getElementById(‘myId’)
- Class: document.getElementsByClassName(‘myClass’)
- Tag: document.getElementsByTagName(‘div’)
- CSS Selectors: document.querySelector(‘.myClass’), document.querySelectorAll(‘p’)
Modifying the DOM
Once you’ve accessed a node, you can modify it:
- Changing text: element.textContent = ‘New text’
- Changing HTML: element.innerHTML = ‘<strong>Bold text</strong>’
- Adding or Removing Elements:
- element.appendChild(node)
- element.removeChild(node)
- element.insertBefore(newNode, referenceNode)
Example:
const p = document.createElement(‘p’);
p.textContent = ‘This is a new paragraph.’;
document.body.appendChild(p);
Multiple Choice Questions with Answers
Question 1
What is the DOM?
- A) A database management system
- B) A programming interface for HTML and XML documents
- C) A JavaScript framework
- D) A CSS preprocessor
Answer: B) A programming interface for HTML and XML documents.
Explanation: The DOM allows JavaScript to access and manipulate the structure of a webpage.
Question 2
Which of these returns the first element that matches a CSS selector?
- A) document.getElementById()
- B) document.querySelector()
- C) document.querySelectorAll()
- D) document.getElementsByTagName()
Answer: B) document.querySelector()
Explanation: querySelector() returns the first matching element.
Question 3
Which property would you use to get the parent element of a node?
- A) node.childNodes
- B) node.parentNode
- C) node.nextSibling
- D) node.firstChild
Answer: B) node.parentNode
Explanation: parentNode refers to the node that is the parent of the current node.
Question 4
document.getElementById(‘header’) returns what?
- A) A single element
- B) A NodeList
- C) An HTMLCollection
- D) A string
Answer: A) A single element
Explanation: getElementById() returns a single element or null if not found.
Question 5
Which of the following includes text nodes?
- A) element.children
- B) element.childNodes
- C) element.querySelectorAll()
- D) element.getElementsByTagName()
Answer: B) element.childNodes
Explanation: childNodes includes all child nodes, including text and comment nodes.
Question 6
To get all paragraph elements inside a <div>, which method is best?
- A) div.getElementsByTagName(‘p’)
- B) div.getElementById(‘p’)
- C) div.querySelector(‘#p’)
- D) div.appendChild(‘p’)
Answer: A) div.getElementsByTagName(‘p’)
Explanation: getElementsByTagName() returns all matching elements inside the given element.
Question 7
Which property references the node’s first element child (ignoring text nodes)?
- A) element.firstChild
- B) element.firstElementChild
- C) element.previousElementSibling
- D) element.lastElementChild
Answer: B) element.firstElementChild
Explanation: firstElementChild returns the first child that is an element, not a text node.
Question 8
How do you remove a child node?
- A) element.removeChild(child)
- B) element.deleteChild(child)
- C) element.destroyChild(child)
- D) element.parentNode(child)
Answer: A) element.removeChild(child)
Explanation: removeChild() is used to remove a specified child node.
Question 9
Which node type number represents an Element node?
- A) 1
- B) 3
- C) 8
- D) 9
Answer: A) 1
Explanation: nodeType of 1 represents an Element node.
Question 10
What does document.documentElement represent?
- A) The head element
- B) The root <html> element
- C) The body element
- D) The title element
Answer: B) The root <html> element
Explanation: document.documentElement returns the <html> element.
Question 11
element.nextElementSibling returns:
- A) The next node (including text) in the same parent
- B) The next element node in the same parent
- C) The next child node of the element
- D) The parent node of the element
Answer: B) The next element node in the same parent
Question 12
document.createElement(‘div’):
- A) Selects an existing <div> element
- B) Creates a new <div> element in memory
- C) Inserts a new <div> directly into the DOM
- D) Returns a list of <div> elements
Answer: B) Creates a new <div> element in memory
Question 13
Which of the following returns an HTMLCollection?
- A) document.querySelectorAll(‘.class’)
- B) document.getElementsByClassName(‘class’)
- C) document.querySelector(‘.class’)
- D) document.createElement(‘div’)
Answer: B) document.getElementsByClassName(‘class’)
Question 14
nodeType of 3 represents:
- A) Element node
- B) Text node
- C) Comment node
- D) Document node
Answer: B) Text node
Question 15
How do you replace an existing node with a new node?
- A) parentElement.replaceNode(newNode, oldNode)
- B) parentElement.replaceChild(newNode, oldNode)
- C) parentElement.changeNode(oldNode, newNode)
- D) parentElement.setChild(newNode, oldNode)
Answer: B) parentElement.replaceChild(newNode, oldNode)
Question 16
To move from a child node to its parent, use:
- A) node.parentNode
- B) node.childNodes
- C) node.nextSibling
- D) node.ownerDocument
Answer: A) node.parentNode
Question 17
Which method returns a NodeList instead of an HTMLCollection?
- A) document.getElementsByTagName()
- B) document.getElementsByClassName()
- C) document.querySelectorAll()
- D) document.getElementById()
Answer: C) document.querySelectorAll()
Question 18
Which property returns all child elements of an element node (no text nodes)?
- A) element.childNodes
- B) element.children
- C) element.querySelectorAll(‘*’)
- D) element.textContent
Answer: B) element.children
Question 19
element.innerHTML = ‘Hello!’:
- A) Gets the HTML content
- B) Sets the HTML content
- C) Removes the element
- D) Appends a new child
Answer: B) Sets the HTML content
Question 20
document.body returns:
- A) The <body> element
- B) The <head> element
- C) The <html> element
- D) The <div> element
Answer: A) The <body> element
Coding Exercises with Full Solutions
Exercise 1: Accessing Parent Node
Task: Select a <li> element and log its parent’s tag name.
HTML:
<ul id=”list”>
<li>Item 1</li>
<li id=”secondItem”>Item 2</li>
<li>Item 3</li>
</ul>
Solution:
const secondItem = document.getElementById(‘secondItem’);
console.log(secondItem.parentNode.tagName);
// Output: UL
Explanation:
parentNode returns the <ul> element that contains <li id=”secondItem”>.
Exercise 2: Accessing Children
Task: Get all direct children of a <ul> and log their text content.
Solution:
const ul = document.getElementById(‘list’);
const children = ul.children; // HTMLCollection
for (let i = 0; i < children.length; i++) {
console.log(children[i].textContent);
}
Explanation:
ul.children returns only element nodes. Iterating through them logs their text.
Exercise 3: Accessing Siblings
Task: Select the second <li> and log the text of its next sibling element.
Solution:
const secondItem = document.getElementById(‘secondItem’);
const nextSibling = secondItem.nextElementSibling;
console.log(nextSibling.textContent);
// Output: Item 3
Explanation:
nextElementSibling gives the next <li> in the list.
Exercise 4: Creating and Appending Elements
Task: Create a new <li> element and append it to the <ul>.
Solution:
const newLi = document.createElement(‘li’);
newLi.textContent = ‘Item 4’;
ul.appendChild(newLi);
Explanation:
document.createElement(‘li’) creates a new <li> which we then append to the existing <ul>.
Exercise 5: Removing an Element
Task: Remove the second <li> from the <ul>.
Solution:
ul.removeChild(secondItem);
Explanation:
removeChild() removes the specified child node from the parent node.
Exercise 6: Replacing a Node
Task: Replace the first <li> with a new <li> element containing “New Item 1”.
Solution:
const firstLi = ul.children[0];
const replacementLi = document.createElement(‘li’);
replacementLi.textContent = ‘New Item 1’;
ul.replaceChild(replacementLi, firstLi);
Explanation:
replaceChild() replaces the existing first <li> with replacementLi.
Exercise 7: Selecting Elements by CSS Selector
Task: Use querySelector() to select the first <li> in the <ul> and log its text.
Solution:
const firstListItem = document.querySelector(‘#list li’);
console.log(firstListItem.textContent);
Explanation:
querySelector(‘#list li’) selects the first <li> inside #list.
Exercise 8: Counting Child Nodes
Task: Log how many child nodes (including text nodes) the <ul> has.
Solution:
console.log(ul.childNodes.length);
Explanation:
childNodes includes text and comment nodes, so the count might be different than children.length.
Exercise 9: Navigating Up and Down the DOM Tree
Task: From the third <li>, access its parent <ul> and then find the first <li>.
Solution:
const thirdLi = ul.children[2]; // Assuming Item 3 is at index 2
const parentUl = thirdLi.parentNode;
const firstLiAgain = parentUl.firstElementChild;
console.log(firstLiAgain.textContent);
// Output: New Item 1 (if replaced previously)
Explanation:
We move up to the <ul> from the third <li> and then get the first child <li> of that <ul>.
Exercise 10: Modifying Inner HTML
Task: Change the inner HTML of the <ul> to have three <li> items: “A”, “B”, “C”.
Solution:
ul.innerHTML = `
<li>A</li>
<li>B</li>
<li>C</li>
`;
Explanation:
innerHTML replaces the entire content of <ul> with the specified HTML string.
This comprehensive guide and exercises cover everything you need to know about the DOM tree, traversal, and manipulation in JavaScript. You can now confidently navigate and modify the DOM for dynamic, interactive web pages.