Module 7: DOM and Browser APIs
The DOM and Selecting Elements
Understand the document tree and select nodes to read or update a page.
The Document Object Model (DOM) represents an HTML document as a tree of nodes. Browser JavaScript can select elements, read their content, update attributes, attach event listeners, and create or remove nodes.
<h1 id="page-title">Welcome</h1>
<p class="status">Ready</p>
const title = document.querySelector("#page-title");
const status = document.querySelector(".status");
console.log(title?.textContent);
console.log(status?.textContent);
querySelector returns the first match or null; querySelectorAll returns a static NodeList of all matches. Check that an element exists before using it if the script may run on pages where the selector is absent.
Script timing#
Use a script with defer, a module script, or run code after the relevant DOM has been parsed. Otherwise, a query can return null simply because the HTML element has not been created yet.
Content and attributes#
Use textContent for plain text. Use getAttribute/setAttribute for attributes, and use properties such as input.value when working with form controls. Avoid using innerHTML for untrusted strings.
Practice#
Create a small HTML page with a heading and a paragraph. Select both from JavaScript and log their text. Then handle the case where the heading is missing.