CSS Prepare

optional · CSS study notes

14. DOM (Document Object Model)

CSS Optional — Paper-II, Section-B · P-II.VI.14 · The bridge between HTML and JavaScript. Expect "explain DOM with a tree diagram" and "write code to access/modify elements".

1. Definition

  • The DOM is a platform- and language-neutral programming interface (W3C; now the WHATWG DOM Living Standard) that represents an HTML or XML document as a tree of objects (nodes), so programs can read and change the document's content, structure and style dynamically.
  • The browser builds the DOM when it parses HTML; JavaScript then works on the DOM, not on the HTML text.
  • History: DOM Level 1 (1998), Level 2 (2000, events and CSS), Level 3 (2004); now a living standard.

2. DOM Tree Example

<html>
  <head><title>Shop</title></head>
  <body>
    <h1 id="title">Products</h1>
    <ul class="list"><li>Pen</li><li>Book</li></ul>
  </body>
</html>
graph TD
    D["document"] --> H["html"]
    H --> HE["head"]
    H --> B["body"]
    HE --> T["title"]
    T --> TT["text: Shop"]
    B --> H1["h1 id=title"]
    H1 --> H1T["text: Products"]
    B --> UL["ul class=list"]
    UL --> L1["li"]
    UL --> L2["li"]
    L1 --> L1T["text: Pen"]
    L2 --> L2T["text: Book"]

Relationships: html is the root element; head and body are siblings and children of html; body is the parent of h1 and ul.

3. Node Types

NodeExamplenodeType
DocumentThe whole page (document object)9
Elementh1, ul, li1
Attributeid="title"2
Text"Products"3
CommentAn HTML comment8

4. Accessing Elements

document.getElementById("title");            // one element by id
document.getElementsByClassName("list");     // live HTMLCollection
document.getElementsByTagName("li");         // live HTMLCollection
document.querySelector("ul.list li");        // first match (CSS selector)
document.querySelectorAll("li");             // static NodeList of all matches

5. Traversing the Tree

parentNode, childNodes (includes text nodes), children (elements only), firstChild/firstElementChild, lastChild, nextSibling/nextElementSibling, previousSibling.

6. Modifying the DOM

const h1 = document.getElementById("title");
h1.textContent = "Our Products";          // change text (safe)
h1.innerHTML = "Our <em>Products</em>";   // change HTML (beware XSS)
h1.style.color = "green";                 // inline style
h1.classList.add("highlight");            // add CSS class
h1.setAttribute("title", "Heading");      // attributes

const li = document.createElement("li");  // create
li.textContent = "Pencil";
document.querySelector(".list").appendChild(li);   // insert
document.querySelector(".list").removeChild(li);   // remove (or li.remove())

7. Worked Example — A Mini To-Do List

<input id="task"><button id="add">Add</button>
<ul id="todo"></ul>
<script>
document.getElementById("add").addEventListener("click", () => {
  const text = document.getElementById("task").value.trim();
  if (!text) return;
  const li = document.createElement("li");
  li.textContent = text;
  li.addEventListener("click", () => li.remove());  // click to delete
  document.getElementById("todo").appendChild(li);
  document.getElementById("task").value = "";
});
</script>

8. DOM vs BOM; Virtual DOM

  • BOM (Browser Object Model): browser-level objects — window, navigator, location, history, screen. Not standardized as one spec; the DOM (window.document) is part of it.
  • Virtual DOM (React): an in-memory copy of the DOM; changes are computed there and only the differences are applied to the real DOM, reducing slow re-rendering.

9. XML DOM vs SAX Parsing

PointDOM parserSAX parser
ApproachLoads whole document into a tree in memoryEvent-based, reads sequentially
MemoryHighLow
Navigation / modificationRandom access; can modifyForward-only; read-only
Best forSmall/medium documents needing editsVery large files, streaming

🎯 CSS Exam Angle

Define the DOM, draw the tree for a small snippet (label parent/child/sibling), list node types, then show access and modification code. The to-do list shows a real use case in a few lines.

⚠️ MCQ Traps

  • The DOM is an interface/model, not a programming language and not the HTML source.
  • getElementsBy... returns a live collection; querySelectorAll returns a static NodeList.
  • childNodes includes text (whitespace) nodes; children only elements.
  • innerHTML parses HTML (XSS risk with user input); textContent treats it as plain text.
  • document is the root node; html is the root element.

✅ Self-Check (with Answers)

Q1. Define the DOM and why JavaScript needs it.

Ans: The DOM is a tree-structured object representation of an HTML/XML document with a standard API. JavaScript cannot edit raw HTML text in the browser; it reads and changes the page by manipulating DOM nodes, which the browser re-renders.

Q2. Write code to turn every paragraph's text red.

Ans: document.querySelectorAll("p").forEach(p => p.style.color = "red");

Q3. What is the difference between innerHTML and textContent?

Ans: innerHTML gets/sets HTML markup, which the browser parses (dangerous with untrusted input — XSS); textContent gets/sets plain text only, which is safer and faster.

Q4. In <ul><li>A</li><li>B</li></ul>, what are the parent, children and siblings?

Ans: ul is the parent of both li elements; the li elements are children of ul and siblings of each other; each li is the parent of its text node.

Q5. When would you use SAX instead of DOM for XML?

Ans: For very large XML files or streams where loading the whole tree into memory is impractical and only sequential, read-only processing is needed.

📜 Past-Paper Questions & MCQs (CSS 2016–2026)

2022 · Paper-II · Q8(b) · 6 marks (DOM part)

Q. Explain in detail the Document Object Model (DOM). Also discuss XML and RSS.

Ans.

  • DOM is a programming interface that represents an HTML or XML document as a tree of objects (nodes), so scripts can read and change its structure, content and style.
  • Node types: document node (the root), element nodes (<div>), attribute nodes, text nodes and comment nodes.
document
 └─ html
     ├─ head ─ title ─ "My Page"
     └─ body ─ h1 ─ "Hello"
             └─ p (class="note") ─ "Text"
  • Common methods: getElementById(), getElementsByClassName(), querySelector(), createElement(), appendChild(), removeChild(), setAttribute(), and properties such as innerHTML and style.
  • Uses: dynamic pages, event handling (click, submit), form validation and AJAX updates.
  • XML and RSS are discussed on their own pages (XML and RSS).

MCQs

2025 P-II · Q15. What is DOM?

  • (A) Hierarchy of objects in ASP.NET
  • (B) Application programming interface
  • (C) Convention for representing and interacting with objects in HTML documents ✅
  • (D) Language-dependent application programming
  • Answer: (C).
  • Why: the Document Object Model is a language-neutral, platform-neutral tree of objects that represents an HTML or XML document so scripts can read and change it. It is not specific to ASP.NET or to one language. (It is exposed through an API, but "application programming interface" alone is too general to define it.)