When a web browser downloads an HTML document, it parses the markup and constructs an in-memory, object-oriented representation called the Document Object Model (DOM). Through the DOM API, JavaScript acts as the interactive brain of the web page—dynamically altering content, styles, animations, and structures in response to user actions.
Figure 6: Hierarchical DOM Tree structure showing Window -> Document -> HTML -> Head/Body -> Elements & Text Nodes.
window.document).<div>, <h1>, <p>, <button>.href, class, id, src).| Selector Method | Return Type | Syntax Example |
|---|---|---|
document.getElementById(id) |
Single Element (or null) | document.getElementById("main-nav") |
document.querySelector(css) |
First Matching Element | document.querySelector(".card > button.active") |
document.querySelectorAll(css) |
Static NodeList |
document.querySelectorAll("ul.nav-list li") |
document.getElementsByClassName(cls) |
Live HTMLCollection |
document.getElementsByClassName("btn-primary") |
// Selecting single element with CSS selector:
const mainTitle = document.querySelector("#page-heading");
console.log(mainTitle.textContent);
// Selecting all matching elements & iterating:
const menuItems = document.querySelectorAll(".nav-link");
menuItems.forEach((link, idx) => {
console.log(`Link #${idx + 1}: ${link.href}`);
});
Exam Question: "Explain the difference between innerText, textContent, and innerHTML."
textContent: Returns the raw text content of all elements (including hidden elements and <script>). Hyper-fast and secure against XSS.innerText: Returns only human-visible rendered text, respecting CSS styling (ignores display: none). Triggers expensive browser reflow.innerHTML: Returns or parses complete raw HTML markup. Warning: Susceptible to Cross-Site Scripting (XSS) attacks if used with unsanitized user inputs.Now that you know how to select elements, let us modify their attributes, create new elements, and update CSS styles dynamically. Proceed to: JavaScript DOM Manipulation & Mutations →