DOM Manipulation in JavaScript
1. Understanding the DOM
What is the DOM?
DOM (Document Object Model) is a programming interface that allows scripts to access and
manipulate the structure, content, and styling of HTML documents.
It represents the HTML document as a tree-like structure where each element is a node.
DOM Tree Example
Given the HTML:
html
Copy code
<!DOCTYPE html>
<html>
<head><title>Sample Page</title></head>
<body>
<h1 id="header">Welcome</h1>
<p class="text">Hello World!</p>
</body>
</html>
The DOM structure would look like:
less
Copy code
html
├── head
│ └── title
└── body
├── h1#header
└── p.text
2. Selecting Elements: getElementById, querySelector, etc.
1. getElementById()
Selects an element by its ID.
Returns only one element.
javascript
Copy code
let header = document.getElementById("header");
console.log(header.textContent); // Output: Welcome
2. querySelector()
Selects the first matching element based on a CSS selector.
javascript
Copy code
let firstParagraph = document.querySelector(".text");
console.log(firstParagraph.textContent); // Output: Hello World!
3. querySelectorAll()
Selects all elements matching a given CSS selector and returns a NodeList (an array-like
object).
javascript
Copy code
let allParagraphs = document.querySelectorAll("p");
allParagraphs.forEach(p => console.log(p.textContent));
4. getElementsByClassName()
Selects elements by their class name.
Returns a live HTMLCollection.
javascript
Copy code
let textElements = document.getElementsByClassName("text");
console.log(textElements[0].textContent); // Output: Hello World!
5. getElementsByTagName()
Selects elements by their tag name.
Returns an HTMLCollection.
javascript
Copy code
let headings = document.getElementsByTagName("h1");
console.log(headings[0].textContent); // Output: Welcome
3. Modifying Elements: Text, HTML, Styles
1. Modifying Text Content
textContent changes the inner text of an element.
javascript
Copy code
let header = document.getElementById("header");
header.textContent = "Hello, World!";
2. Modifying HTML Content
innerHTML changes the inner HTML structure of an element.
javascript
Copy code
let paragraph = document.querySelector(".text");
paragraph.innerHTML = "<strong>Hello, World!</strong>";
3. Modifying Styles
Use the style property to change CSS directly.
javascript
Copy code
let header = document.getElementById("header");
header.style.color = "blue";
header.style.fontSize = "30px";
4. Event Handling: Listeners, Bubbling, Delegation
1. Adding Event Listeners
The addEventListener() method attaches an event handler to an element.
javascript
Copy code
let button = document.querySelector("#myButton");
button.addEventListener("click", function() {
alert("Button clicked!");
});
2. Removing Event Listeners
Use removeEventListener() to detach an event listener.
javascript
Copy code
function handleClick() {
alert("Button clicked!");
button.addEventListener("click", handleClick);
button.removeEventListener("click", handleClick);
3. Event Bubbling and Capturing
Bubbling: Events propagate from the target element up to the root.
Capturing: Events propagate from the root to the target element.
Default behavior is bubbling.
javascript
Copy code
document.body.addEventListener("click", () => {
console.log("Body clicked");
});
4. Event Delegation
Event delegation allows you to manage events efficiently by assigning a listener to a parent
element and checking the target using event.target.
javascript
Copy code
document.body.addEventListener("click", function(event) {
if (event.target.tagName === "BUTTON") {
alert(`Button ${event.target.textContent} clicked!`);
});
5. Preventing Default Behavior
Use event.preventDefault() to stop the default action of an event.
javascript
Copy code
let link = document.querySelector("a");
link.addEventListener("click", function(event) {
event.preventDefault(); // Prevents the link from navigating
console.log("Link clicked, but navigation prevented.");
});