Skip to content

Session 4

JavaScript HTML DOM

Updated View as Markdown

The Document Object Model (DOM) is a W3C-standard, language-independent interface that allows programs and scripts to dynamically access, modify, add, or remove the content, structure, and style of a web document. While the W3C DOM is categorized into Core DOM (all document types), XML DOM, and HTML DOM, this session focuses specifically on the HTML DOM, which is the standard model for HTML documents.

When a browser loads an HTML page, it automatically parses the markup and constructs a hierarchical DOM tree. This tree represents the document’s structure through parent-child node relationships, where:

  • The entire document is a document node
  • Every HTML tag is an element node
  • Text inside elements is a text node
  • HTML comments are comment nodes

The HTML DOM bridges static HTML with dynamic JavaScript by treating every element, attribute, and piece of content as a JavaScript object. This object-oriented representation enables developers to:

  • ✅ Access or locate any element using IDs, tag names, or class names
  • ✅ Modify element content (innerHTML), attributes, and CSS styles on-the-fly
  • ✅ Dynamically create, append, or remove HTML elements
  • ✅ React to user interactions through DOM events (clicks, inputs, loads, etc.)

By leveraging the HTML DOM, you can transform static web pages into highly interactive, real-time applications without requiring page reloads. This session introduces the core DOM programming interface, node navigation techniques, and practical methods for manipulating HTML content and styles using JavaScript.

Objective

Do not copy. Read for understanding and the viva

After completing this session one should be able to:

  • Add, Modify or delete the existing content of HTML elements.
  • Modify a CSS style in the HTML page.
  • React to existing HTML DOM events in page.

DOM Tree (Node Types)

When a browser parses HTML, it builds a node tree:

Node TypeDescriptionExample
documentRoot node of the entire pagedocument
elementHTML tags<div>, <p>, <img>
textContent inside elements"Hello World" inside <p>
attributeElement attributes (treated as nodes in legacy DOM)id="btn", src="img.jpg"
commentHTML comments<!-- hidden -->

Parent-Child-Sibling Relationships

  • <html> → parent of <head> & <body>
  • <body> → parent of <h1> & <p>
  • <h1> & <p> → siblings

Accessing Elements (DOM Methods)

MethodReturnsBest For
document.getElementById("id")Single elementFastest & most reliable
document.getElementsByClassName("class")HTMLCollection (Live)Multiple elements sharing a class
document.getElementsByTagName("tag")HTMLCollection (Live)All elements of a specific tag
document.querySelector("selector")First matching elementModern, CSS-like selectors
document.querySelectorAll("selector")NodeList (static)All matching elements

Modifying Element

Content

element.innerHTML = "<b>New HTML</b>";   // Parses HTML (risk of XSS if user input)
element.textContent = "Plain text only";  // Safer, faster, ignores HTML tags
element.innerText = "Visible text only";  // Respects CSS styling (e.g., hidden elements)

Attributes

// Direct property (works for standard attributes)
img.src = "new.jpg";
link.href = "https://example.com";

// Universal method (works for custom/data attributes)
element.setAttribute("data-role", "admin");
let val = element.getAttribute("data-role");

Styles

// JS uses camelCase for multi-word CSS properties
element.style.backgroundColor = "lightblue";
element.style.fontSize = "18px";
element.style.marginLeft = "20px";

Create & Append Element

let newP = document.createElement("p");          // <p></p>
let txt = document.createTextNode("Hello DOM");  // "Hello DOM"
newP.appendChild(txt);                           // <p>Hello DOM</p>
document.body.appendChild(newP);                 // Adds to end of <body>

Insert at Specific Position

let parent = document.getElementById("container");
let reference = document.getElementById("refItem");
parent.insertBefore(newP, reference); // Inserts newP before reference

Remove Elements

// Modern (recommended)
element.remove(); 

// Legacy (manual's syntax)
parent.removeChild(childElement);

Question 1

Problem Statement

Write in lab record

Design an HTML page using JavaScript as shown below. When Try button is pressed, the Full Name should be shown below the Try button.
(Hint: Use concatenation to get Full Name).
(Please refer to images in lab manual)

Preview (Working)

Do not copy. Read for understanding and the viva

Ex 1: Concatenate Full Name

Code

Write in lab record
button-on-click.htmlhtml
<!doctype html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <title>Session 4: JavaScript DOM Exercises</title>
        <style>
            body {
                font-family: "Segoe UI", sans-serif;
                margin: 20px;
                background: #f4f4f4;
            }
            .exercise {
                background: #fff;
                padding: 20px;
                margin-bottom: 20px;
                border-radius: 8px;
                box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
            }
            input,
            button {
                padding: 8px 12px;
                margin: 5px;
                border: 1px solid #ccc;
                border-radius: 4px;
            }
            button {
                cursor: pointer;
                background: #0056b3;
                color: #fff;
                border: none;
            }
            button:hover {
                background: #003d82;
            }
            img {
                border: 2px solid #333;
                border-radius: 4px;
            }
        </style>
    </head>
    <body>
        <h1 style="text-align: center">
            Session 4: JavaScript HTML DOM Exercises
        </h1>
        <div class="exercise">
            <h2>Ex 1: Concatenate Full Name</h2>
            <input type="text" id="fname" placeholder="First Name" />
            <input type="text" id="lname" placeholder="Last Name" />
            <button id="btnTry">Try</button>
            <p
                id="fullNameOutput"
                style="font-weight: bold; margin-top: 10px"
            ></p>
        </div>

        <script>
            // DOM Access + innerHTML + Concatenation
            document.getElementById("btnTry").onclick = function () {
                const fn = document.getElementById("fname").value;
                const ln = document.getElementById("lname").value;
                document.getElementById("fullNameOutput").innerHTML =
                    `Full Name: ${fn} ${ln}`;
            };
        </script>
    </body>
</html>

Question 2

Problem Statement

Write in lab record

Modify the below snippet of the code to change the src attribute of the image element to “pqr.jpg” using HTML DOM.

<img id="pic" src="old.jpg">
<script>
//Write your code here.
</script>

Preview (Working)

Do not copy. Read for understanding and the viva

Ex 2: Change Image `src`

Dynamic changing

Code

Write in lab record
image-change.htmlhtml
<!doctype html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <title>Session 4: JavaScript DOM Exercises</title>
        <style>
            body {
                font-family: "Segoe UI", sans-serif;
                margin: 20px;
                background: #f4f4f4;
            }
            .exercise {
                background: #fff;
                padding: 20px;
                margin-bottom: 20px;
                border-radius: 8px;
                box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
            }
            input,
            button {
                padding: 8px 12px;
                margin: 5px;
                border: 1px solid #ccc;
                border-radius: 4px;
            }
            button {
                cursor: pointer;
                background: #0056b3;
                color: #fff;
                border: none;
            }
            button:hover {
                background: #003d82;
            }
            img {
                border: 2px solid #333;
                border-radius: 4px;
            }
        </style>
    </head>
    <body>
        <h1 style="text-align: center">
            Session 4: JavaScript HTML DOM Exercises
        </h1>

        <div class="exercise">
            <h2>Ex 2: Change Image `src` Attribute</h2>
            <img
                id="pic"
                src="https://placehold.co/150x100/0000FF/FFFFFF?text=old.jpg"
                alt="Original Image"
            /><br />
            <button id="btnChangeImg">Change to opr.jpg</button>
        </div>

        <script>
            document.getElementById("btnChangeImg").onclick = function () {
                document.getElementById("pic").src =
                    "https://placehold.co/150x100/FF0000/FFFFFF?text=pqr.jpg";
            };
        </script>
    </body>
</html>

Question 3

Problem Statement

Write in lab record

Write the JavaScript code to change the color of the HTML element h2 to green, on click the change color button.

Preview (Working)

Do not copy. Read for understanding and the viva

Ex 3: Change H2 Color

Click button to change my color

Code

Write in lab record
color-change.htmlhtml
<!doctype html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <title>Session 4: JavaScript DOM Exercises</title>
        <style>
            body {
                font-family: "Segoe UI", sans-serif;
                margin: 20px;
                background: #f4f4f4;
            }
            .exercise {
                background: #fff;
                padding: 20px;
                margin-bottom: 20px;
                border-radius: 8px;
                box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
            }
            input,
            button {
                padding: 8px 12px;
                margin: 5px;
                border: 1px solid #ccc;
                border-radius: 4px;
            }
            button {
                cursor: pointer;
                background: #0056b3;
                color: #fff;
                border: none;
            }
            button:hover {
                background: #003d82;
            }
            img {
                border: 2px solid #333;
                border-radius: 4px;
            }
        </style>
    </head>
    <body>
        <h1 style="text-align: center">
            Session 4: JavaScript HTML DOM Exercises
        </h1>
        <div class="exercise">
            <h2>Ex 3: Change H2 Color</h2>
            <h2 id="heading1" style="color: red">
                This heading will turn green
            </h2>
            <button id="btnChangeColor">Change Color</button>
        </div>

        <script>
            document.getElementById("btnChangeColor").onclick = function () {
                document.getElementById("heading1").style.color = "green";
            };
        </script>
    </body>
</html>
Navigation

Type to search…

↑↓ navigate↵ selectEsc close