Skip to content

Session 6

HTML DOM Navigation

Updated View as Markdown

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

Do not copy. Read for understanding and the viva
  • 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:

PropertyDescriptionExample
parentNodeReturns the direct parent nodeel.parentNode
childNodesReturns a NodeList of all direct childrenel.childNodes[0]
firstChild / lastChildReturns the first/last child nodeel.firstChild
nextSibling / previousSiblingReturns adjacent sibling nodesel.nextSibling

Important Notes:

  • childNodes includes text nodes (whitespace counts as a node). To skip them, use children or check nodeType === 1.
  • nodeValue extracts the text content of a text node.
  • nodeName returns 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 child
    • parent.insertBefore(newEl, referenceEl) -> Inserts before a specific child

Removing Elements

MethodUsageBehavior
element.remove()Modern, directRemoves the element itself
parent.removeChild(child)LegacyRemoves a specific child from its parent

Question 1

Problem Statement

Write in lab record

Which function on the document object should be used to retrieve a HTML element uniquely?

Answer

Write in lab record
document.getElementById(id)

Note: document.querySelector("#id") also works, but getElementById is faster and specifically designed for unique ID retrieval.

Question 2

Problem Statement

Write in lab record

Which JavaScript function can be used to dynamically add a event listener to a HTML element?

Answer

Write in lab record
element.addEventListener(eventType, callbackFunction)

OR

parentElement.insertBefore(newElement, referenceElement)

Question 3

Problem Statement

Write in lab record

Which method should be used to add a new HTML child element?

Answer

Write in lab record
parentElement.appendChild(newElement)

OR

parentElement.insertBefore(newElement, referenceElement)

Question 4

Problem Statement

Write in lab record

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)

Do not copy. Read for understanding and the viva

Product Details

💻 Laptop: $1,200

📱 Cell Phone: $800

Code

Write in lab record
product-page.htmlhtml
<!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>
Navigation

Type to search…

↑↓ navigate↵ selectEsc close