DOM Manipulation in JavaScript
Understanding DOM Manipulation in JavaScript
1. What is the DOM?
DOM stands for Document Object Model.
When a web page loads, the browser creates a structured representation of the HTML document called the DOM.
JavaScript can use the DOM to:
- Access HTML elements
- Change content
- Change styles
- Add or remove elements
Example:
document.getElementById("title").innerText = "Hello JavaScript";
2. Selecting HTML Elements
getElementById()
let element = document.getElementById("myElement");
getElementsByClassName()
let elements = document.getElementsByClassName("box");
querySelector()
let element = document.querySelector("#title");
3. Changing HTML Content
document.getElementById("message").innerText = "Welcome to JavaScript";
4. Changing Styles
document.getElementById("title").style.color = "red";
5. Creating New Elements
let li = document.createElement("li");
li.innerText = "New Item";
6. Real-Life Example: Dynamic To-Do List Application
This application allows users to:
- Add tasks
- Display tasks dynamically
index.html
<!DOCTYPE html>
<html>
<head>
<title>To Do List</title>
</head>
<body>
<h2>To-Do List</h2>
<input type="text" id="task" placeholder="Enter task">
<button onclick="addTask()">Add Task</button>
<ul id="taskList"></ul>
<script src="app.js"></script>
</body>
</html>
Run Code
app.js
function addTask(){
let task = document.getElementById("task").value;
let li = document.createElement("li");
li.innerText = task;
let list = document.getElementById("taskList");
list.appendChild(li);
document.getElementById("task").value = "";
}
Run Code
7. How This Example Works
- User enters a task.
- When Add Task is clicked, the function runs.
- JavaScript creates a new
<li>element. - The task is added to the list dynamically.
8. Practice Exercise
Create a Notes Application.
Features:
- Add notes
- Display notes
9. What Students Learned
- What the DOM is
- Selecting HTML elements
- Modifying HTML content
- Creating new elements dynamically
Next Chapter
Chapter 9: Events in JavaScript with Real-Life Example: Interactive Color Changer