DOM: Document Object Model Basics
The DOM is a programming interface for HTML and XML documents. It represents the page structure as a tree of objects.
What is the DOM?
The DOM is a tree structure representing the HTML document:
Document
โโโ html
โ โโโ head
โ โ โโโ title
โ โ โโโ meta
โ โโโ body
โ โโโ h1
โ โโโ p
โ โโโ div
Accessing the Document
document Object
// The global document object
console.log(document);
console.log(document.title);
console.log(document.URL);
console.log(document.body);
console.log(document.head);
Window Object
// Window is the global object in browsers
console.log(window);
console.log(window.document);
console.log(window.location);
console.log(window.history);
Selecting Elements
getElementById()
const element = document.getElementById("myId");
console.log(element);
querySelector()
// Select first matching element
const element = document.querySelector(".myClass");
const element2 = document.querySelector("#myId");
const element3 = document.querySelector("div > p");
querySelectorAll()
// Select all matching elements
const elements = document.querySelectorAll(".myClass");
console.log(elements.length);
// Iterate
elements.forEach(el => console.log(el));
getElementsByClassName()
const elements = document.getElementsByClassName("myClass");
console.log(elements.length);
getElementsByTagName()
const paragraphs = document.getElementsByTagName("p");
console.log(paragraphs.length);
Element Properties
Content
const element = document.getElementById("myElement");
// Get/set text content
element.textContent = "New text";
console.log(element.textContent);
// Get/set HTML content
element.innerHTML = "<strong>Bold text</strong>";
console.log(element.innerHTML);
// Get/set value (for inputs)
const input = document.getElementById("myInput");
input.value = "New value";
console.log(input.value);
Attributes
const element = document.getElementById("myElement");
// Get attribute
const href = element.getAttribute("href");
// Set attribute
element.setAttribute("href", "https://example.com");
// Check if attribute exists
if (element.hasAttribute("data-id")) {
console.log("Has data-id");
}
// Remove attribute
element.removeAttribute("disabled");
Classes
const element = document.getElementById("myElement");
// Add class
element.classList.add("active");
// Remove class
element.classList.remove("active");
// Toggle class
element.classList.toggle("active");
// Check if has class
if (element.classList.contains("active")) {
console.log("Has active class");
}
// Get all classes
console.log(element.classList);
Styles
const element = document.getElementById("myElement");
// Set inline styles
element.style.color = "red";
element.style.backgroundColor = "blue";
element.style.fontSize = "20px";
// Get computed styles
const styles = window.getComputedStyle(element);
console.log(styles.color);
console.log(styles.backgroundColor);
Navigating the DOM
Parent and Children
const element = document.getElementById("myElement");
// Parent
console.log(element.parentElement);
console.log(element.parentNode);
// Children
console.log(element.children); // HTMLCollection
console.log(element.childNodes); // NodeList (includes text nodes)
console.log(element.firstChild);
console.log(element.lastChild);
console.log(element.firstElementChild);
console.log(element.lastElementChild);
Siblings
const element = document.getElementById("myElement");
// Next sibling
console.log(element.nextSibling); // May be text node
console.log(element.nextElementSibling); // Next element
// Previous sibling
console.log(element.previousSibling);
console.log(element.previousElementSibling);
Creating and Modifying Elements
Creating Elements
// Create element
const newDiv = document.createElement("div");
newDiv.textContent = "Hello";
newDiv.className = "myClass";
// Create text node
const text = document.createTextNode("Some text");
Adding Elements
const parent = document.getElementById("parent");
const newElement = document.createElement("p");
newElement.textContent = "New paragraph";
// Append as last child
parent.appendChild(newElement);
// Insert before specific element
const firstChild = parent.firstElementChild;
parent.insertBefore(newElement, firstChild);
// Append HTML
parent.innerHTML += "<span>New span</span>";
Removing Elements
const element = document.getElementById("myElement");
// Remove element
element.remove();
// Remove from parent
element.parentElement.removeChild(element);
// Clear all children
element.innerHTML = "";
Cloning Elements
const original = document.getElementById("original");
// Shallow clone
const clone = original.cloneNode(false);
// Deep clone (includes children)
const deepClone = original.cloneNode(true);
document.body.appendChild(clone);
Practical Examples
Dynamic List Creation
const items = ["Apple", "Banana", "Orange"];
const ul = document.createElement("ul");
items.forEach(item => {
const li = document.createElement("li");
li.textContent = item;
ul.appendChild(li);
});
document.body.appendChild(ul);
Form Validation
const form = document.getElementById("myForm");
const emailInput = document.getElementById("email");
form.addEventListener("submit", (event) => {
event.preventDefault();
const email = emailInput.value;
if (!email.includes("@")) {
emailInput.classList.add("error");
return;
}
emailInput.classList.remove("error");
form.submit();
});
Toggle Visibility
const button = document.getElementById("toggleBtn");
const content = document.getElementById("content");
button.addEventListener("click", () => {
content.classList.toggle("hidden");
button.textContent = content.classList.contains("hidden")
? "Show"
: "Hide";
});
Search and Filter
const searchInput = document.getElementById("search");
const items = document.querySelectorAll(".item");
searchInput.addEventListener("input", (event) => {
const query = event.target.value.toLowerCase();
items.forEach(item => {
const text = item.textContent.toLowerCase();
item.style.display = text.includes(query) ? "block" : "none";
});
});
Dynamic Table
function createTable(data) {
const table = document.createElement("table");
// Create header
const thead = document.createElement("thead");
const headerRow = document.createElement("tr");
Object.keys(data[0]).forEach(key => {
const th = document.createElement("th");
th.textContent = key;
headerRow.appendChild(th);
});
thead.appendChild(headerRow);
table.appendChild(thead);
// Create body
const tbody = document.createElement("tbody");
data.forEach(row => {
const tr = document.createElement("tr");
Object.values(row).forEach(value => {
const td = document.createElement("td");
td.textContent = value;
tr.appendChild(td);
});
tbody.appendChild(tr);
});
table.appendChild(tbody);
return table;
}
const data = [
{ name: "Alice", age: 30 },
{ name: "Bob", age: 25 }
];
document.body.appendChild(createTable(data));
Performance Tips
Use querySelector Efficiently
// Good - specific selector
const element = document.querySelector("#myId");
// Avoid - overly complex selector
const element = document.querySelector("body > div > div > p.text");
Cache Element References
// Good - cache reference
const element = document.getElementById("myElement");
element.style.color = "red";
element.textContent = "Hello";
// Avoid - repeated queries
document.getElementById("myElement").style.color = "red";
document.getElementById("myElement").textContent = "Hello";
Batch DOM Updates
// Good - batch updates
const fragment = document.createDocumentFragment();
for (let i = 0; i < 1000; i++) {
const li = document.createElement("li");
li.textContent = `Item ${i}`;
fragment.appendChild(li);
}
document.getElementById("list").appendChild(fragment);
// Avoid - individual updates
for (let i = 0; i < 1000; i++) {
const li = document.createElement("li");
li.textContent = `Item ${i}`;
document.getElementById("list").appendChild(li); // Reflow each time
}
Summary
- DOM: tree structure representing HTML
- document: global object for accessing DOM
- querySelector: select elements with CSS selectors
- textContent: get/set text
- innerHTML: get/set HTML
- classList: manage CSS classes
- style: set inline styles
- appendChild: add elements
- remove: delete elements
- Performance: cache references, batch updates
Related Resources
Official Documentation
Next Steps
- Selecting Elements: querySelector, getElementById, etc.
- Event Handling: addEventListener and Event Objects
- Modifying DOM: Creating, Updating, Deleting Elements
Comments