Understanding the DOM
Contents
Introduction
Accessing Elements
Modifying Elements
Creating Elements
Removing Elements
Projects
Bonus Tip
- Definition: The DOM is a tree-like representation of a webpage's structure, allowing JavaScript to interact with and modify its elements.
-
Elements: Each node in the DOM represents an HTML element (e.g.,
<h1>
,<p>
,<div>
). -
Properties: Elements have properties like
id
,class
,textContent
, andstyle
that can be accessed and modified.
-
document.getElementById(id)
: Retrieves a single element by its unique ID. -
document.getElementsByClassName(className)
: Retrieves a collection of elements with a specific class name. -
document.querySelector(selector)
: Retrieves the first element matching a CSS selector. -
document.querySelectorAll(selector)
: Retrieves all elements matching a CSS selector.
// Get element by ID:
const heading = document.getElementById("main-heading");
heading.textContent = "Hello, world!";
// Get all elements with a class name:
const paragraphs = document.getElementsByClassName("intro-text");
paragraphs[0].style.color = "red";
// Get elements using CSS selectors:
const firstButton = document.querySelector("button");
firstButton.disabled = true;
const allLinks = document.querySelectorAll("a");
allLinks.forEach(link => link.style.textDecoration = "underline");
Modifying Elements:
-
Changing content:
element.textContent = "New text";
element.innerHTML = "<b>New content</b>";
-
Changing attributes:
element.setAttribute("attribute", "value");
element.removeAttribute("attribute");
-
Changing styles:
-
element.style.property = "value";
-
// Change text content:
const description = document.querySelector("p");
description.textContent = "This is a new description.";
// Change HTML content:
const container = document.getElementById("content");
container.innerHTML = "<h2>New Content</h2>";
// Change attributes:
const image = document.querySelector("img");
image.setAttribute("src", "new-image.jpg");
// Change styles:
const heading = document.querySelector("h1");
heading.style.color = "blue";
heading.style.fontSize = "36px";
-
document.createElement(tagName)
: Creates a new element node. -
element.appendChild(newElement)
: Appends a new element as a child of an existing element. -
element.insertBefore(newElement, referenceElement)
: Inserts a new element before a reference element.
// Create a new element:
const newParagraph = document.createElement("p");
newParagraph.textContent = "This is a dynamically created paragraph.";
// Append the element:
const body = document.body;
body.appendChild(newParagraph);
// Insert before an existing element:
const existingElement = document.getElementById("existing-element");
body.insertBefore(newParagraph, existingElement);
-
element.parentNode.removeChild(element)
: Removes an element from the DOM.
const elementToRemove = document.querySelector(".remove-me");
elementToRemove.parentNode.removeChild(elementToRemove);
Projects
Project 1: Interactive To-Do List
const todoList = document.getElementById("todo-list");
const inputField = document.getElementById("new-task");
const addButton = document.getElementById("add-button");
addButton.addEventListener("click", function() {
const newTask = document.createElement("li");
newTask.textContent = inputField.value;
todoList.appendChild(newTask);
inputField.value = ""; // Clear input field
});
todoList.addEventListener("click", function(event) {
if (event.target.tagName === "LI") {
event.target.classList.toggle("completed");
}
});
Project 2: Image Gallery with Lightbox Effect
const images = document.querySelectorAll(".gallery img");
images.forEach(image => {
image.addEventListener("click", function() {
const lightbox = document.createElement("div");
lightbox.classList.add("lightbox");
const img = document.createElement("img");
img.src = this.src;
lightbox.appendChild(img);
document.body.appendChild(lightbox);
lightbox.addEventListener("click", function() {
this.remove();
});
});
});
Project 3: Hamburger Icon Toggle
<!DOCTYPE html>
<html>
<head>
<title>Hamburger Icon Toggle</title>
<style>
.nav-menu {
display: none; /* Initially hidden */
}
.nav-menu.open {
display: block;
}
/* Optional styling for open/closed icon states */
.hamburger-icon.open {
/* Style for open state */
}
</style>
</head>
<body>
<button class="hamburger-icon">โฐ</button>
<nav class="nav-menu">
</nav>
<script>
const hamburgerIcon = document.querySelector(".hamburger-icon");
const navMenu = document.querySelector(".nav-menu");
hamburgerIcon.addEventListener("click", function() {
navMenu.classList.toggle("open");
hamburgerIcon.classList.toggle("open"); // Optionally toggle icon state
});
</script>
</body>
</html>
Bonus Tip
- MDN Web Docs: Comprehensive documentation on DOM manipulation: https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model
- JavaScript30: Practical projects to practice DOM manipulation: https://javascript30.com/
- FreeCodeCamp: Interactive lessons and challenges: https://www.freecodecamp.org/learn/front-end-development-libraries/
- Online Courses: Platforms like Coursera, Udemy, and Codecademy offer courses on JavaScript and DOM manipulation.
- Books: "JavaScript: The Definitive Guide" by David Flanagan and "DOM Enlightenment" by Cody Lindley.
Top comments (0)