JS- Introduction to DOM Manipulation
JS- Introduction to DOM Manipulation
HTML
|-- HEAD
| |-- TITLE
|-- BODY
|-- H1
|-- P
|-- DIV
1. getElementById()
This method selects an element based on its id attribute. It's one of the fastest ways to access a single element.
Example
// HTML
<div id="myDiv">Hello, World!</div>
// JavaScript
const element = document.getElementById("myDiv");
console.log(element.textContent); // Outputs: Hello, World!
2. getElementsByClassName()
This method selects all elements with a specified class name and returns a live HTMLCollection.
Example
// HTML
<div class="example">First</div>
<div class="example">Second</div>
// JavaScript
const elements = document.getElementsByClassName("example");
console.log(elements[0].textContent); // Outputs: First
These methods use CSS selectors to find elements. querySelector() selects the first matching element, while
querySelectorAll() selects all matching elements and returns a static NodeList.
Example
// HTML
<div class="example">First</div>
<div class="example">Second</div>
// JavaScript
const firstElement = document.querySelector(".example");
console.log(firstElement.textContent); // Outputs: First
4. getElementsByTagName()
This method selects all elements with a specific tag name, such as <div> , <p> , etc., and returns a live HTMLCollection.
Example
// HTML
<p>Paragraph 1</p>
<p>Paragraph 2</p>
// JavaScript
const paragraphs = document.getElementsByTagName("p");
console.log(paragraphs.length); // Outputs: 2
Summary
In this part, we introduced the DOM and covered the basic methods to access elements within it. Mastering these foundational
concepts is essential for working effectively with the DOM. In the next section, we will dive deeper into modifying and
manipulating elements dynamically.
Introduction
In this part, we will explore how to access and manipulate elements in the DOM using JavaScript. Understanding these
techniques is crucial for creating dynamic, interactive web pages. We will cover methods like getElementById ,
querySelector , and querySelectorAll , along with how to modify element properties and content.
1. getElementById
// HTML
<div id="example-div">Hello, World!</div>
// JavaScript
const element = document.getElementById("example-div");
console.log(element.textContent); // Outputs: Hello, World!
2. getElementsByClassName
The getElementsByClassName method selects elements based on their class name. It returns a live HTMLCollection of
matching elements.
// HTML
<div class="example">Item 1</div>
<div class="example">Item 2</div>
// JavaScript
const elements = document.getElementsByClassName("example");
console.log(elements.length); // Outputs: 2
3. querySelector
The querySelector method returns the first element that matches a specified CSS selector.
// HTML
<div class="example">Hello!</div>
// JavaScript
const element = document.querySelector(".example");
console.log(element.textContent); // Outputs: Hello!
4. querySelectorAll
The querySelectorAll method returns a static NodeList of all elements that match the specified CSS selector.
// HTML
<div class="example">Item 1</div>
<div class="example">Item 2</div>
// JavaScript
const elements = document.querySelectorAll(".example");
elements.forEach(el => console.log(el.textContent));
1. Changing Content
// HTML
<div id="example-div">Original Text</div>
// JavaScript
const element = document.getElementById("example-div");
element.textContent = "Updated Text"; // Updates the content
2. Changing Attributes
Use the setAttribute and getAttribute methods to modify or retrieve element attributes.
// HTML
<img id="example-img" src="image1.jpg" alt="Image">
// JavaScript
const img = document.getElementById("example-img");
img.setAttribute("src", "image2.jpg"); // Changes the image source
// HTML
<div id="example-div" class="highlighted">Content</div>
// JavaScript
const element = document.getElementById("example-div");
element.classList.remove("highlighted");
element.classList.add("new-class");
Summary
In this part, we discussed methods to access DOM elements and manipulate their properties, attributes, and classes. These
foundational skills are essential for working with the DOM and building dynamic web applications. In the next section, we will
delve deeper into event handling and how to respond to user interactions.
Using document.createElement()
The document.createElement() method is used to create new HTML elements. Once created, these elements can be added
to the DOM using methods like appendChild() or append() .
// JavaScript
const newParagraph = document.createElement("p");
newParagraph.textContent = "This is a dynamically added paragraph.";
document.body.appendChild(newParagraph);
In this example, a new <p> element is created and appended to the document body.
Another way to insert elements is by using the innerHTML property. However, this method replaces the existing content of
an element and can potentially expose your application to security risks if not handled carefully.
// JavaScript
document.getElementById("container").innerHTML = "
New Content
This is dynamically added.
";
This approach is useful for adding multiple elements at once but should be used sparingly to maintain security and
performance.
Modifying Attributes
JavaScript allows you to dynamically set, update, and remove attributes of HTML elements.
Using setAttribute()
file:///home/zub/Desktop/Part 3: Accessing and Manipulating DOM Elements.html 1/3
12/25/24, 3:57 PM Part 3: Accessing and Manipulating DOM Elements
// JavaScript
const link = document.querySelector("a");
link.setAttribute("target", "_blank");
In this example, the target attribute is added to a link, causing it to open in a new tab.
Using removeAttribute()
// JavaScript
const img = document.querySelector("img");
img.removeAttribute("alt");
Attributes like id , className , and src can also be accessed and modified directly as properties.
// JavaScript
const header = document.querySelector("h1");
header.id = "main-header";
This approach is often more concise and easier to read than using setAttribute() .
Using cloneNode()
// JavaScript
const originalElement = document.querySelector("div");
The true parameter includes the child nodes of the element being cloned. Set it to false to clone only the element itself.
Replacing Elements
Replacing one element with another is a common operation when updating the DOM dynamically.
Using replaceChild()
The replaceChild() method replaces a child node of a parent element with a new node.
// JavaScript
const newHeading = document.createElement("h2");
newHeading.textContent = "New Heading";
const oldHeading = document.querySelector("h1");
oldHeading.parentNode.replaceChild(newHeading, oldHeading);
Summary
In this section, we explored intermediate DOM manipulation techniques such as creating and appending new elements,
modifying attributes, cloning elements, and replacing elements. These techniques form the foundation for more advanced
interactions and dynamic updates in web applications.
Introduction
Event handling is one of the most critical aspects of DOM manipulation. By listening to user interactions, such as clicks,
keypresses, or mouse movements, you can create interactive and dynamic web applications. In this part, we will dive deep into
how to handle events in JavaScript.
Understanding Events
Events are actions or occurrences that happen in the browser, such as when a user clicks a button, hovers over an element, or
types into a text box. JavaScript provides the ability to listen for these events and respond accordingly.
// JavaScript
const button = document.querySelector("button");
button.addEventListener("click", function() {
alert("Button clicked!");
});
In this example, we select a button element and attach a click event listener to it. When the button is clicked, the alert
message is displayed.
// JavaScript
function handleClick() {
alert("Button clicked!");
}
In this example, the handleClick function is added as an event listener to a button element. The same function is then
removed using removeEventListener .
Event Object
When an event occurs, an event object is automatically passed to the event handler. This object contains information about the
event, such as the target element, event type, and more.
// JavaScript
const button = document.querySelector("button");
button.addEventListener("click", function(event) {
console.log("Event type:", event.type);
console.log("Target element:", event.target);
});
Here, the event object provides details about the click event, such as its type and the target element.
Event Delegation
Event delegation is a technique where you use a single event listener on a parent element to handle events for its child
elements. This is especially useful when dealing with dynamically added elements.
// HTML
Item 1
Item 2
Item 3
// JavaScript
const list = document.getElementById("list");
list.addEventListener("click", function(event) {
if (event.target.tagName === "LI") {
alert(`You clicked on ${event.target.textContent}`);
}
});
In this example, a single click event listener is added to the ul element. The event handler checks if the target element is
an li and responds accordingly.
// HTML
Click Me
// JavaScript
const parent = document.getElementById("parent");
const child = document.getElementById("child");
parent.addEventListener("click", function() {
alert("Parent clicked!");
});
child.addEventListener("click", function(event) {
alert("Button clicked!");
event.stopPropagation();
});
In this example, clicking the button triggers the child event handler but stops the parent event handler from being
executed due to stopPropagation .
// HTML
Go to Example
// JavaScript
const link = document.getElementById("link");
link.addEventListener("click", function(event) {
event.preventDefault();
alert("Link click prevented!");
});
In this example, clicking the link does not navigate to the URL because the default action is prevented using
preventDefault .
Summary
In this part, we explored event handling in JavaScript, including adding and removing event listeners, using the event object,
and implementing techniques like event delegation. We also learned how to stop event propagation and prevent default
actions. These skills form the foundation for building interactive and responsive web applications.
Introduction
Traversing the DOM involves navigating through parent, child, and sibling elements within a document. This section explores how to
navigate and manipulate elements dynamically, allowing for more precise and targeted DOM interactions.
Parent Nodes
You can navigate to an element's parent using the parentNode or parentElement properties.
// HTML
<div id="parent">
<p id="child">Hello, World!</p>
</div>
// JavaScript
const child = document.getElementById("child");
const parent = child.parentNode;
console.log(parent.id); // Outputs: "parent"
Child Nodes
To access an element's children, use the childNodes or children properties. The children property is preferred as it only includes
element nodes (ignoring text and comment nodes).
// HTML
<ul>
<li>Item 1</li>
<li>Item 2</li>
</ul>
// JavaScript
const list = document.querySelector("ul");
const items = list.children;
console.log(items.length); // Outputs: 2
Sibling Nodes
Siblings are elements that share the same parent. You can access them using the nextSibling , previousSibling ,
nextElementSibling , and previousElementSibling properties.
Example: Navigating Siblings
// HTML
<div>First</div>
<div>Second</div>
// JavaScript
const first = document.querySelector("div");
const second = first.nextElementSibling;
console.log(second.textContent); // Outputs: "Second"
Adding Elements
// JavaScript
const newItem = document.createElement("li");
newItem.textContent = "New Item";
const list = document.querySelector("ul");
list.appendChild(newItem);
Removing Elements
// JavaScript
const list = document.querySelector("ul");
const item = list.firstElementChild;
list.removeChild(item);
Replacing Elements
// JavaScript
const list = document.querySelector("ul");
const oldItem = list.firstElementChild;
const newItem = document.createElement("li");
newItem.textContent = "Replaced Item";
list.replaceChild(newItem, oldItem);
Cloning Elements
The cloneNode() method allows you to copy an element. Use the argument true to clone the element along with its children.
// JavaScript
const original = document.querySelector("div");
const clone = original.cloneNode(true);
document.body.appendChild(clone);
Use the textContent property to get or set the textual content of an element.
// JavaScript
const heading = document.querySelector("h1");
console.log(heading.textContent); // Outputs the text inside the
Using innerHTML
The innerHTML property allows you to get or set the HTML content of an element, including tags.
// JavaScript
const container = document.querySelector("div");
container.innerHTML = "<p>New paragraph added!</p>";
Summary
In this section, we explored how to traverse the DOM using parent, child, and sibling relationships, as well as methods to dynamically
modify the DOM by adding, removing, replacing, and cloning elements. Additionally, we covered how to manipulate text content with
textContent and innerHTML . Mastering these techniques is essential for creating interactive and dynamic web applications.
12/25/24, 3:58 PM Part 6: Accessing and Manipulating DOM Elements
Introduction
Events are one of the most powerful aspects of DOM manipulation, enabling developers to make web pages interactive and
dynamic. In this section, we delve into advanced event-handling techniques, including delegation, event propagation, and
custom events, to provide you with a deeper understanding of how events work in JavaScript.
Event Propagation
Event propagation determines how events flow through the DOM tree. There are three phases of event propagation:
1. Capturing Phase: The event travels from the root element to the target element.
2. Target Phase: The event reaches the target element.
3. Bubbling Phase: The event travels back up from the target element to the root element.
By default, most events use the bubbling phase, but you can specify the capturing phase when adding event listeners.
// HTML
Click me!
// JavaScript
const outer = document.querySelector(".outer");
const inner = document.querySelector(".inner");
In this example, the outer div uses the capturing phase, while the inner div uses the bubbling phase. Clicking on the inner
div will trigger both listeners.
Event Delegation
Event delegation is a technique where a single event listener is added to a parent element to handle events on its child
elements. This is particularly useful for dynamically created elements.
// HTML
Item 1
Item 2
Item 3
// JavaScript
const list = document.getElementById("list");
list.addEventListener("click", (event) => {
if (event.target.tagName === "LI") {
alert(`You clicked on ${event.target.textContent}`);
}
});
In this example, clicking on any <li> element triggers the event listener on the parent <ul> , and we use event.target to
identify which <li> was clicked.
Custom Events
JavaScript allows you to create and dispatch custom events using the CustomEvent constructor. Custom events are useful for
creating reusable and modular components.
// JavaScript
const customEvent = new CustomEvent("myCustomEvent", {
detail: { message: "Hello, World!" },
});
target.dispatchEvent(customEvent);
In this example, we create a custom event called myCustomEvent with additional data in the detail property. The event
listener on the target element logs the custom message to the console.
// HTML
Click me
// JavaScript
const link = document.getElementById("link");
link.addEventListener("click", (event) => {
event.preventDefault();
alert("Default navigation prevented!");
});
In this example, clicking on the link does not navigate to the URL because the default behavior is prevented.
Stop Propagation
If you want to stop an event from propagating to parent elements, use the event.stopPropagation() method.
// HTML
Click me!
// JavaScript
const outer = document.querySelector(".outer");
const inner = document.querySelector(".inner");
In this example, clicking the inner div triggers only its event listener because the propagation to the outer div is stopped.
Summary
In this section, we explored advanced event-handling techniques, including event propagation, delegation, custom events, and
preventing or stopping default behaviors. These techniques provide greater flexibility and control over how events are
handled in your web applications.
Getting Attributes
// JavaScript
const link = document.querySelector("a");
const href = link.getAttribute("href");
console.log(href); // Outputs the href attribute value
Setting Attributes
// JavaScript
const link = document.querySelector("a");
link.setAttribute("href", "https://example.com");
link.setAttribute("target", "_blank");
Removing Attributes
// JavaScript
const link = document.querySelector("a");
link.removeAttribute("target");
Data attributes allow you to store extra information on standard, semantic HTML elements. These attributes start with
data- , followed by a custom name. The dataset property makes it easy to interact with these attributes in JavaScript.
// HTML
Click Me
// JavaScript
const button = document.querySelector("button");
const userId = button.dataset.userId;
console.log(userId); // Outputs: 123
button.dataset.role = "admin";
console.log(button.dataset.role); // Outputs: admin
Event Delegation
Event delegation is a technique for improving performance by adding event listeners to parent elements instead of individual
child elements. This is especially useful when dealing with dynamically generated elements.
// HTML
Item 1
Item 2
Item 3
// JavaScript
const list = document.getElementById("list");
list.addEventListener("click", function(event) {
if (event.target.tagName === "LI") {
console.log("You clicked: " + event.target.textContent);
}
});
Custom Events
Custom events allow you to define and dispatch your own events, providing more flexibility for communication within your
application. The CustomEvent constructor is used to create a custom event.
// JavaScript
const myEvent = new CustomEvent("myCustomEvent", {
detail: { message: "Hello, world!" }
});
document.addEventListener("myCustomEvent", function(event) {
console.log(event.detail.message); // Outputs: Hello, world!
});
document.dispatchEvent(myEvent);
Event Propagation
Event propagation describes the order in which event handlers are executed in the DOM tree. It consists of three phases:
Capture phase: The event moves down from the document root to the target element.
Target phase: The event reaches the target element.
Bubbling phase: The event moves back up to the document root.
Controlling Propagation
You can control propagation using the stopPropagation() and stopImmediatePropagation() methods.
// HTML
Click Me
// JavaScript
const outerDiv = document.getElementById("outer");
const innerButton = document.getElementById("inner");
Summary
In this section, we covered how to manage attributes, data attributes, and events in the DOM. You learned to dynamically get,
set, and remove attributes, use the dataset property, handle events efficiently with delegation, and create custom events
for specific use cases. Understanding these techniques enables you to create responsive and interactive web applications.
Cloning Elements
The cloneNode() method allows you to duplicate an existing DOM element. This is useful when you need to create multiple
elements with the same structure and optionally the same content.
// JavaScript
const originalElement = document.querySelector(".item");
const clone = originalElement.cloneNode(true); // true for deep clone
originalElement.parentElement.appendChild(clone);
In this example, cloneNode(true) creates a deep clone of the .item element, including all child elements.
Replacing Nodes
The replaceChild() method is used to replace one child node with another.
// JavaScript
const parent = document.querySelector(".container");
const newElement = document.createElement("div");
newElement.textContent = "I am a replacement.";
const oldElement = document.querySelector(".to-be-replaced");
parent.replaceChild(newElement, oldElement);
Here, the .to-be-replaced element is replaced with a newly created div element.
A DocumentFragment is a lightweight container that allows you to create and manipulate multiple nodes off-screen before
inserting them into the DOM. This is particularly useful for improving performance when adding many elements.
// JavaScript
const fragment = document.createDocumentFragment();
for (let i = 0; i < 5; i++) {
const newDiv = document.createElement("div");
newDiv.textContent = `Div ${i + 1}`;
fragment.appendChild(newDiv);
}
document.body.appendChild(fragment);
This method minimizes reflows and repaints by appending multiple elements to the DOM at once.
Data Attributes
Custom data attributes ( data-* ) allow you to store additional data on HTML elements. They can be accessed and
manipulated using JavaScript.
// HTML
Click Me
// JavaScript
const button = document.getElementById("userButton");
const userId = button.dataset.userId;
console.log(`User ID: ${userId}`);
Here, the dataset property provides access to the data-user-id attribute as a JavaScript property.
Event Delegation
Event delegation leverages the concept of event bubbling, allowing you to attach a single event listener to a parent element
to handle events for its child elements.
// JavaScript
const parentElement = document.querySelector(".parent");
parentElement.addEventListener("click", (event) => {
if (event.target.matches(".child")) {
console.log("Child clicked:", event.target.textContent);
}
});
This approach is efficient and reduces the number of event listeners in your application.
Custom Events
Custom events allow you to define and dispatch your own events. These are useful for building complex, component-based
systems.
// JavaScript
const event = new CustomEvent("myEvent", {
detail: { message: "Hello, World!" }
});
const targetElement = document.querySelector("#target");
targetElement.addEventListener("myEvent", (e) => {
console.log(e.detail.message);
});
targetElement.dispatchEvent(event);
Here, a custom event named myEvent is created and dispatched with additional data.
The preventDefault() method stops the default action associated with an event, such as following a link or submitting a
form.
// JavaScript
const link = document.querySelector("a");
link.addEventListener("click", (event) => {
event.preventDefault();
console.log("Default behavior prevented.");
});
This example demonstrates how to prevent a link from navigating to its href when clicked.
The stopPropagation() method prevents an event from bubbling up or capturing down the DOM tree.
// JavaScript
const outerDiv = document.querySelector(".outer");
const innerDiv = document.querySelector(".inner");
outerDiv.addEventListener("click", () => {
console.log("Outer div clicked");
});
innerDiv.addEventListener("click", (event) => {
event.stopPropagation();
console.log("Inner div clicked");
});
In this example, clicking the inner div logs a message but stops the event from propagating to the outer div .
Summary
In this section, we explored advanced DOM manipulation techniques, including cloning and replacing nodes, using document
fragments, leveraging data attributes, and handling events at an advanced level. These techniques are essential for building
dynamic and efficient web applications.