You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
The Document Object Model (DOM) is the browser's in-memory representation of an HTML document. JavaScript can read, modify, add, and remove elements in the DOM, which is how you create dynamic, interactive web pages.
When the browser loads an HTML page, it parses the markup and builds a tree of nodes. Each HTML element becomes a node in this tree. JavaScript interacts with this tree through the global document object.
document
└── html
├── head
│ └── title
└── body
├── h1
├── p
└── div
├── ul
│ ├── li
│ └── li
└── button
const heading = document.getElementById("main-heading");
Returns a single element or null.
// First match
const btn = document.querySelector(".btn-primary");
// All matches (returns a NodeList)
const items = document.querySelectorAll(".list-item");
| Method | Returns |
|---|---|
getElementById(id) | Single element |
querySelector(css) | First matching element |
querySelectorAll(css) | NodeList of all matches |
getElementsByClassName(cls) | HTMLCollection (live) |
getElementsByTagName(tag) | HTMLCollection (live) |
Tip: Prefer
querySelectorandquerySelectorAll— they use CSS selectors and are the most flexible.
const items = document.querySelectorAll(".list-item");
// forEach works on NodeLists
items.forEach((item) => {
console.log(item.textContent);
});
// Or convert to a real array
const itemArray = [...items];
| Property | Description | XSS Safe? |
|---|---|---|
textContent | Get/set the text content (ignores HTML tags) | Yes |
innerHTML | Get/set the HTML content (parses HTML tags) | No — user input can inject scripts |
const heading = document.querySelector("h1");
// Read text
console.log(heading.textContent); // "Hello World"
// Change text
heading.textContent = "New Heading";
// Change HTML (use with caution)
heading.innerHTML = "New <em>Heading</em>";
Security warning: Never insert user-supplied data with
innerHTML. UsetextContentinstead to prevent Cross-Site Scripting (XSS) attacks.
const box = document.querySelector(".box");
box.style.backgroundColor = "blue";
box.style.color = "white";
box.style.padding = "20px";
box.style.borderRadius = "8px";
Note: CSS property names are camelCase in JavaScript (
background-colorbecomesbackgroundColor).
const box = document.querySelector(".box");
box.classList.add("active"); // Add a class
box.classList.remove("hidden"); // Remove a class
box.classList.toggle("expanded"); // Toggle a class
box.classList.contains("active"); // Check for a class — returns boolean
box.classList.replace("old", "new"); // Replace a class
Best practice: Define styles in CSS classes and use
classListto toggle them. This separates concerns and is easier to maintain.
const link = document.querySelector("a");
// Read an attribute
console.log(link.getAttribute("href"));
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.