DOM Basics & Event Listeners
The Document Object Model (DOM) is a programming interface for web documents. It represents the page structure so that JavaScript can modify its styling, structure, and content dynamically.
1 Query Selectors & Modifying Elements
JavaScript interacts with page nodes using document queries:
- `document.getElementById(id)`: Selects elements by their unique ID attribute.
- `document.querySelector(selector)`: Selects elements using CSS selector syntax (e.g. `.class`, `#id`, `nav a`).
- `element.innerHTML` / `element.textContent`: Gets or sets text/HTML content.
- `element.style.property`: Directly modifies inline CSS styling values.
2 Binding Event Listeners
To make pages interactive, we bind events (like clicks, form submissions, or keystrokes) to elements using `addEventListener()`. Let's look at how this is structured in JavaScript:
JavaScript — DOM Basics API
▶ Run Code
// Note: In Node.js server environments, the 'document' object is not defined.
// This example displays browser DOM modification syntax:
const btn = {
clickEvent: null,
addEventListener(event, callback) {
if (event === "click") {
this.clickEvent = callback;
}
},
click() {
if (this.clickEvent) this.clickEvent();
}
};
// Simulation of binding element click event in JS
btn.addEventListener("click", () => {
console.log("Button clicked! Dynamic style changes applied.");
});
btn.click(); // Trigger click event
3 Code Challenge
Challenge: Write the JavaScript statements needed to select a button with class `submit-btn`, add a click event listener to it, change its text content to "Submitted!", and update its background color style to green.