Home >Web Front-end >JS Tutorial >DOM Manipulation in JavaScript
Date: December 14, 2024
Welcome to Day 7 of your JavaScript learning journey! Today’s topic focuses on DOM Manipulation, one of the most exciting aspects of JavaScript. With DOM manipulation, you can dynamically update, add, or remove elements from a webpage, making it interactive and user-friendly. By the end of today’s lesson, you’ll also create a simple To-Do List project to put your knowledge into practice.
The Document Object Model (DOM) is a programming interface for web documents. It represents the structure of an HTML document as a tree of objects, allowing you to access and manipulate elements programmatically using JavaScript.
Here’s an example of how the DOM represents HTML:
<html> <body> <h1>Welcome</h1> <p>This is a paragraph.</p> </body> </html>
The DOM tree for the above would look like this:
Document └── html └── body ├── h1 └── p
You can access elements in the DOM using several methods:
let title = document.getElementById("title"); console.log(title); // Logs the element with ID "title"
let items = document.getElementsByClassName("item"); console.log(items); // Logs all elements with class "item"
let firstItem = document.querySelector(".item"); // First element with class "item" let allItems = document.querySelectorAll(".item"); // All elements with class "item"
You can update the text or HTML inside an element using:
let title = document.getElementById("title"); title.innerText = "Updated Title"; // Changes visible text title.innerHTML = "<strong>Updated Title</strong>"; // Adds HTML formatting
You can directly modify the CSS styles of an element.
let title = document.getElementById("title"); title.style.color = "blue"; title.style.fontSize = "24px";
let box = document.getElementById("box"); box.classList.add("highlight"); // Adds a class box.classList.remove("highlight"); // Removes a class
Events allow you to make your web pages interactive. Here are some common event types and how to handle them.
In your HTML:
<button onclick="alert('Button Clicked!')">Click Me</button>
This approach is preferred as it separates JavaScript from HTML.
let button = document.getElementById("btn"); button.addEventListener("click", function () { alert("Button Clicked!"); });
Example:
<html> <body> <h1>Welcome</h1> <p>This is a paragraph.</p> </body> </html>
Let’s combine what you’ve learned into a simple To-Do List application.
Document └── html └── body ├── h1 └── p
Tomorrow, on Day 8, we’ll explore Error Handling and Debugging, learning how to handle unexpected issues in your JavaScript code. See you then!
The above is the detailed content of DOM Manipulation in JavaScript. For more information, please follow other related articles on the PHP Chinese website!