Skip to lesson content
Web Technologies › Level 16
LEVEL 16 · BROWSER

DOM and Browser Programming

Inspect the document tree and make targeted, understandable page updates.

🌳 DOM tree🔎 Selection🛠️ Live updates🧪 Lab + MCQs
01

Learning Objectives

Tree

Identify elements, text nodes and relationships.

Selection

Choose selectors and handle a missing match.

Updates

Use targeted text, property and node operations.

Usability

Keep labels, status and focus meaningful after changes.

02

DOM — The Browser’s Document Tree

Workshop preview tree
document

The loaded page document.

ul preview

The collection container.

li → article

One workshop card.

h4 + p

Its title and explanatory text.

03

document, window and the Browser Environment

const preview = document.getElementById("preview");
console.log(window.innerWidth);
console.log(preview !== null);
04

Initialize After the Required Elements Exist

function initPreview() {
  const preview = document.getElementById("preview");
  if (!preview) return;
  // Set up this preview once.
}
if (document.readyState === "loading") {
  document.addEventListener("DOMContentLoaded", initPreview, { once: true });
} else {
  initPreview();
}
05

Select One Element and Check the Result

const preview = document.getElementById("preview");
const firstTitle = preview?.querySelector(".card-title");
if (firstTitle) {
  firstTitle.textContent = "HTML Workshop";
}
06

Select Many — Static and Live Collections

const before = preview.querySelectorAll(".card");
// Insert another card here.
const after = preview.querySelectorAll(".card");
console.log(before.length, after.length);
const titles = Array.from(after, card =>
  card.querySelector(".card-title").textContent
);
07

textContent — Update Text Deliberately

const title = card.querySelector(".card-title");
title.textContent = userSuppliedTitle;
// Literal text, not parsed HTML markup.
08

Attributes and Properties — Related, Not Identical

button.disabled = cards.length === 0;
button.setAttribute("aria-pressed", highlighted ? "true" : "false");
console.log(input.value); // current user entry
console.log(input.getAttribute("value")); // attribute representation
09

dataset — Small Data Attributes

card.dataset.cardId = "card-1";
console.log(card.dataset.cardId); // "card-1"
// HTML representation: data-card-id="card-1"
10

classList and Styles — Keep Presentation in CSS

card.classList.toggle("is-highlighted", highlighted);
badge.hidden = !highlighted;
// CSS controls the actual border and badge presentation.
const resolvedColor = getComputedStyle(card).color;
11

Create, Populate and Insert Nodes

const item = document.createElement("li");
const article = document.createElement("article");
const title = document.createElement("h4");
title.className = "card-title";
title.textContent = "HTML Workshop";
article.append(title);
item.append(article);
preview.append(item);
12

Traverse the Tree — Elements or All Nodes?

const title = card.querySelector(".card-title");
const owner = title.closest("article");
console.log(owner === card); // true in this structure
console.log(preview.children.length); // current element children
13

Remove and Replace — Understand What Survives

const cardItem = card.closest("li");
cardItem.remove();
// The item is detached; a variable may still refer to it.

preview.replaceChildren(); // clear only this container
14

DOM Changes, Focus and Feedback

status.textContent = "Card removed. Two cards remain.";
if (remainingCards.length > 0) {
  selector.focus();
} else {
  titleInput.focus();
}
15

Browser Measurements and Persistence

const box = card.getBoundingClientRect();
console.log(box.width, box.height);
console.log(box.top); // viewport-relative position
16

Premium Visualizer — A DOM Update Journey

Follow a fixed card-creation example through selection, creation, population, insertion and inspection. Use the approved timeline and playback controls. This visualizer explains the operations; the live lab below performs actual preview updates.

DOM UPDATE TRACE
Step 1 of 5
STEP 01

Find the intended preview region

Use a fixed ID and check that the preview exists.

document.getElementById("preview")

What is happening?

A null result must be handled. The operation stays scoped to the preview, not the global page shell.

17

Premium Interactive — Live DOM Card Editor

Preview is ready.

Live preview

    Last operation

    Current DOM snapshot

    18

    Debugging — Structure, Timing and Current State

    Selection

    Check IDs, selectors, scope and null results.

    Timing

    Check whether the required nodes exist at initialization.

    Text

    Inspect the leaf updated and whether markup was unintentionally parsed.

    State

    Check disabled controls, pressed state, focus and current counts.

    19

    Interview Questions — Flip to Explain

    QUESTION

    Does a DOM update rewrite the original HTML file?

    Click or press Enter to explain
    ANSWER

    No. It changes the live document instance. Repository or server persistence requires a separate deliberate mechanism.

    QUESTION

    What does querySelector return when no element matches?

    Click or press Enter to explain
    ANSWER

    Null. Check it before accessing properties; an invalid selector can instead throw a SyntaxError.

    QUESTION

    Is querySelectorAll a live collection?

    Click or press Enter to explain
    ANSWER

    No. Its NodeList membership is static. Query again to include newly inserted matching elements.

    QUESTION

    Why use textContent for a user-provided title?

    Click or press Enter to explain
    ANSWER

    It supplies literal text rather than parsing markup. Target the heading so unrelated article children survive.

    QUESTION

    Does disabled="false" enable a button?

    Click or press Enter to explain
    ANSWER

    No. A boolean disabled attribute is active when present. Set the disabled property to false or remove the attribute.

    QUESTION

    What does append do with a node already in the document?

    Click or press Enter to explain
    ANSWER

    It moves that node to the new location rather than automatically cloning it.

    QUESTION

    Does remove erase every JavaScript reference?

    Click or press Enter to explain
    ANSWER

    No. The node is disconnected, but existing references can still point to that object.

    QUESTION

    What should happen after removing the last selected card?

    Click or press Enter to explain
    ANSWER

    Show a clear empty state, disable actions requiring a selection and preserve a usable focus path, such as the title field for adding a card.

    20

    MCQ Practice — Explain the Live Document

    PRACTICE

    1. Which object is the main entry point for this page’s document tree?

    PRACTICE

    2. What argument belongs in getElementById for id="preview"?

    PRACTICE

    3. What does a valid querySelector return with no match?

    PRACTICE

    4. Which collection has static query-time membership?

    PRACTICE

    5. Which property supplies literal user text to a title?

    PRACTICE

    6. What happens when textContent is set on an entire article?

    PRACTICE

    7. How do you enable a disabled native button?

    PRACTICE

    8. What type is dataset.cardId?

    PRACTICE

    9. Which method changes one class token without replacing all class names?

    PRACTICE

    10. What does appending an already connected node normally do?

    PRACTICE

    11. What does element.remove do?

    PRACTICE

    12. Which statement fits the live editor’s persistence?

    21

    Extra Practice — Check Specific DOM Operations

    Literal markup

    Save a title containing tags as typed text. Expected: the brackets appear literally; no nested strong element is created.

    Insertion

    Add one card to the three starting cards. Expected: four list items and a unique generated ID.

    Highlight

    Toggle twice. Expected: class and badge turn on, then off; aria-pressed follows the selected state.

    Leaf update

    Edit a heading. Expected: its note and generated ID remain available.

    Empty state

    Remove every card. Expected: count zero, clear empty message and disabled selection actions.

    Rebuild

    Reset after editing and removing. Expected: three original unhighlighted cards.

    Static query

    • Save querySelectorAll results, insert a card, then query again.
    • Expected: saved membership stays unchanged; fresh membership includes the addition.

    Keyboard path

    Use Tab and native buttons to remove the last card, then add one. Expected: focus remains on a useful surviving control.

    22

    Quick Revision

    DOM: The live document tree can differ from source HTML.
    Select: Use the correct selector API and check a missing match.
    Collections: Distinguish static snapshots from live membership.
    Text: Update a leaf with literal textContent.
    Properties: Current state and attribute representation can differ.
    Identity: Use generated IDs rather than editable titles.
    Classes: Synchronize CSS state and meaningful feedback.
    Insert: Creation and connection are separate operations.
    Remove: Detachment does not erase every reference.
    Review: Test focus, status, rendering and persistence expectations.
    23

    Glossary — Flip to Learn

    TERM

    DOM

    Click to see meaning
    DEFINITION

    DOM

    The object representation and APIs for the document tree.

    TERM

    Node

    Click to see meaning
    DEFINITION

    Node

    An object in the document tree, such as an element or text node.

    TERM

    Element

    Click to see meaning
    DEFINITION

    Element

    A node representing an HTML or other markup element.

    TERM

    Selector

    Click to see meaning
    DEFINITION

    Selector

    A pattern used to identify matching elements.

    TERM

    NodeList

    Click to see meaning
    DEFINITION

    NodeList

    A collection of nodes; querySelectorAll supplies a static one.

    TERM

    Attribute

    Click to see meaning
    DEFINITION

    Attribute

    A named value in an element’s attribute representation.

    TERM

    Property

    Click to see meaning
    DEFINITION

    Property

    A field on a DOM object that may expose current state.

    TERM

    Dataset

    Click to see meaning
    DEFINITION

    Dataset

    The string-valued interface to an element’s data attributes.

    TERM

    Detached node

    Click to see meaning
    DEFINITION

    Detached node

    A node disconnected from the document or its previous parent.

    TERM

    Focus

    Click to see meaning
    DEFINITION

    Focus

    The current target for keyboard interaction in the document.

    24

    Final Challenge — A Scoped Preview Editor

    • Build a labeled card editor with a list preview.
    • Generate stable IDs, set user text with textContent, and create semantic list items containing articles.
    • Add, edit, highlight and remove cards without replacing unrelated page content.
    • Keep a six-card teaching limit, title and note limits, synchronized disabled/pressed states and a clear zero-card outcome.
    • Target the title and note for edits.
    • Use a fresh query for the inspector.
    • Announce a concise result and choose a useful focus target when removing the last selected card.
    • Test literal angle brackets, duplicate titles, a rejected blank title, six-card capacity, removal to zero, addition after zero and reset.
    • Inspect node structure, visible text, class state and keyboard behavior.
    • State explicitly whether the data persists after reload.
    • Success criterion: explain each update in terms of selection, node/property changes and connection to the live document.
    • Level 17 will deepen events, propagation and form validation.
    25

    Level 16 Complete?

    Before marking complete, create a scoped preview update, distinguish text from markup, handle missing selections and demonstrate the empty-state keyboard path. Completion is a local study marker rather than an assessment score.