Session 6
HTML DOM Navigation
HTML DOM interprets an HTML document as a hierarchical tree of nodes. This session focuses on DOM Navigation, which allows JavaScript to traverse this tree using parent-child-sibling relationships. Additionally, this session covers dynamic DOM Manipulation: creating, inserting, and removing HTML elements programmatically without page reloads.
Objectives
- Navigate between DOM nodes using built-in relationship properties
- Dynamically create and attach new HTML elements to the document
- Remove existing elements or child nodes from the DOM tree
- Implement interactive UI updates through hands-on DOM exercises
DOM Navigation Properties
Every DOM node exposes properties to access its relatives in the tree:
| Property | Description | Example |
|---|---|---|
parentNode | Returns the direct parent node | el.parentNode |
childNodes | Returns a NodeList of all direct children | el.childNodes[0] |
firstChild / lastChild | Returns the first/last child node | el.firstChild |
nextSibling / previousSibling | Returns adjacent sibling nodes | el.nextSibling |
Important Notes:
childNodesincludes text nodes (whitespace counts as a node). To skip them, usechildrenor checknodeType === 1.nodeValueextracts the text content of a text node.nodeNamereturns the tag name in UPPERCASE (e.g.,DIV,P).
// Example: Accessing text inside <h3 id="heading1">Hello</h3>
let h3 = document.getElementById("heading1");
console.log(h3.firstChild.nodeValue); // "Hello"
console.log(h3.nodeName); // "H3"
Creating & Adding Elements
- Create Element:
document.createElement("tag") - Create Text Node:
document.createTextNode("text") - Attach Text to Element:
element.appendChild(textNode) - Insert into DOM:
parent.appendChild(newEl)-> Adds as last childparent.insertBefore(newEl, referenceEl)-> Inserts before a specific child
Removing Elements
| Method | Usage | Behavior |
|---|---|---|
element.remove() | Modern, direct | Removes the element itself |
parent.removeChild(child) | Legacy | Removes a specific child from its parent |
Question 1
Problem Statement
Which function on the document object should be used to retrieve a HTML element uniquely?
Answer
document.getElementById(id)
Note:
document.querySelector("#id")also works, butgetElementByIdis faster and specifically designed for unique ID retrieval.
Question 2
Problem Statement
Which JavaScript function can be used to dynamically add a event listener to a HTML element?
Answer
element.addEventListener(eventType, callbackFunction)
OR
parentElement.insertBefore(newElement, referenceElement)
Question 3
Problem Statement
Which method should be used to add a new HTML child element?
Answer
parentElement.appendChild(newElement)
OR
parentElement.insertBefore(newElement, referenceElement)
Question 4
Problem Statement
USe the DOM API, create a product page which shows the prices of a laptop and a cell phone. You may use paragraph tag to wrap these elements. When the user clicks on add button, you should able to add TV with price details and when you click on delete button then cell phone details will be deleted.
Preview (Working)
Product Details
💻 Laptop: $1,200
📱 Cell Phone: $800
Code
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Session 6: DOM Navigation & Manipulation</title>
<style>
body {
font-family: sans-serif;
padding: 20px;
}
.container {
max-width: 600px;
margin: auto;
}
p {
background: #f0f0f0;
padding: 10px;
margin: 8px 0;
border-radius: 4px;
}
button {
padding: 8px 15px;
margin-right: 10px;
cursor: pointer;
}
</style>
</head>
<body>
<div class="container">
<h2>Product Details</h2>
<div id="productList">
<p id="laptop">💻 Laptop: $1,200</p>
<p id="cellphone">📱 Cell Phone: $800</p>
</div>
<br />
<button id="addBtn">Add TV</button>
<button id="deleteBtn">Delete Cell Phone</button>
</div>
<script>
// Add TV using DOM Navigation & Creation
document.getElementById("addBtn").addEventListener("click", () => {
const tvEl = document.createElement("p");
const tvText = document.createTextNode("📺 TV: $1,500");
tvEl.appendChild(tvText);
// Insert before the delete button's container or at end
document.getElementById("productList").appendChild(tvEl);
});
// Delete Cell Phone using removeChild
document
.getElementById("deleteBtn")
.addEventListener("click", () => {
const phone = document.getElementById("cellphone");
if (phone && phone.parentNode) {
phone.parentNode.removeChild(phone);
}
});
</script>
</body>
</html>