Module 2: The Browser & DOM
Module 2 covers JavaScript running inside the browser — where it gets extra abilities like reading and changing web pages, reacting to clicks, and talking to servers. Module 1's language knowledge is assumed throughout.
The Browser Environment
JavaScript (the language, Module 1)
↓
runs inside the BROWSER
↓
gains access to: document, window, fetch, localStorage...
HTML gives a page its structure, CSS gives it presentation, and JavaScript gives it behavior — the three work together, with JavaScript able to read and change both the HTML and the CSS at any time, live, in response to user actions.
Every browser tab exposes two global objects to your JavaScript: window (the browser
tab itself — size, location, timers, storage) and document (the page's content,
represented as the DOM, covered next).
The DOM Tree
The DOM (Document Object Model) is the browser's live, in-memory representation of your HTML as a tree of objects. JavaScript reads and changes this tree — and the moment it does, the page updates on screen instantly, with no reload.
<body>
<div id="app">
<h1>Title</h1>
<p>Text</p>
</div>
</body>
/* The DOM tree:
document
└── body
└── div#app
├── h1
└── p
*/
Selecting Elements
document.getElementById("title"); // single element, by ID
document.querySelector(".box"); // FIRST match for any CSS selector
document.querySelectorAll(".box"); // ALL matches, as a NodeList
document.querySelectorAll(".box").forEach(box => console.log(box));
// Older methods, still seen in existing code
document.getElementsByClassName("box");
document.getElementsByTagName("p");
querySelector/querySelectorAll are the modern standard — they accept any
CSS selector, so anything already known from writing stylesheets works here too.
Creating, Changing & Removing Elements
let heading = document.querySelector("h1");
heading.textContent = "New Title"; // safest — plain text only
heading.innerHTML = "New <b>Title</b>"; // parses as HTML — careful with untrusted input
let link = document.querySelector("a");
link.setAttribute("href", "/about");
link.getAttribute("href");
let newItem = document.createElement("li");
newItem.textContent = "New list item";
let list = document.querySelector("ul");
list.appendChild(newItem); // add at the end
list.prepend(newItem); // add at the start
newItem.remove(); // remove it
Classes & Styles
let box = document.querySelector(".box");
box.style.backgroundColor = "blue"; // direct style
box.style.display = "none";
// Preferred — toggle CSS classes, keep the actual design in CSS
box.classList.add("active");
box.classList.remove("hidden");
box.classList.toggle("dark-mode");
box.classList.contains("active"); // true/false