0% found this document useful (0 votes)
2 views

JS DOM_NEW

The document provides a comprehensive guide on manipulating the Document Object Model (DOM) using JavaScript, covering essential tasks such as changing text content, modifying CSS styles, adding/removing classes, creating/appending elements, and handling events. Each section includes step-by-step exercises with examples to illustrate how to interact with web page elements dynamically. The document emphasizes the importance of these skills for developing interactive and responsive web applications.

Uploaded by

BENAZIR AE
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

JS DOM_NEW

The document provides a comprehensive guide on manipulating the Document Object Model (DOM) using JavaScript, covering essential tasks such as changing text content, modifying CSS styles, adding/removing classes, creating/appending elements, and handling events. Each section includes step-by-step exercises with examples to illustrate how to interact with web page elements dynamically. The document emphasizes the importance of these skills for developing interactive and responsive web applications.

Uploaded by

BENAZIR AE
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 17

JS DOM, EVENTS,

FORMS
In the world of web development, understanding how to manipulate
the Document Object Model (DOM) with JavaScript is crucial. The
DOM represents the structure of a web page, allowing developers to
interact with and modify its content and layout dynamically.
Mastering DOM manipulation enables you to create interactive and
responsive web applications, enhancing user experience significantly.
JavaScript is the primary language used to manipulate the DOM. It
provides powerful methods and properties to select, modify, and
interact with elements on a web page. Whether you want to change
text content, update styles, or handle user interactions, JavaScript
offers the tools you need.
Exercise 1: Changing Text Content
One of the most common tasks in DOM manipulation is changing the
text content of elements. This exercise will guide you through the
process of selecting an element and updating its text content using
JavaScript.
Step-by-Step Guide
1. Select the Element:
Use document.getElementById(), document.querySelector(), or
other selection methods to target the element you want to
modify.
// Example: Selecting an element with the id "example"
let element = document.getElementById("example");
Methods to Select Elements
A. By ID
Use document.getElementById("id") to select an element with a
specific id.
var element = document.getElementById("myId");
B. By Class Name
Use document.getElementsByClassName("className") to select all
elements with a specific class.
var elements = document.getElementsByClassName("myClass");
C. By Tag Name
Use document.getElementsByTagName("tagName") to select all
elements of a specific tag type.
var elements = document.getElementsByTagName("div");
D. By CSS Selectors
Use document.querySelector("cssSelector") to select the first
element that matches a CSS selector.
var element = document.querySelector(".myClass");
var element = document.querySelector("#myId");
 Example Use Case: Select the first element with
class="myClass".
E. By CSS Selectors (Multiple)
Use document.querySelectorAll("cssSelector") to select all elements
matching a CSS selector.
This returns a NodeList.
var elements = document.querySelectorAll(".myClass");
 Example Use Case: Select all elements with class="myClass".
2. Update Text Content: Use the textContent or innerHTML property
to change the text inside the selected element.
// Changing the text content of the selected element
element.textContent = "New Text Content";
Example
Suppose you have the following HTML:
<p id="example">Original Text Content</p>
<button id="changeTextButton">Change Text</button>
You can change the text content of the paragraph when the button is
clicked with the following JavaScript:
// Selecting the button element
let button = document.getElementById("changeTextButton");

// Adding an event listener to the button


button.addEventListener("click", function() {
// Selecting the paragraph element
let paragraph = document.getElementById("example");

// Changing the text content of the paragraph


paragraph.textContent = "New Text Content";
});
In this example, when the user clicks the “Change Text” button, the
text content of the paragraph with the id “example” changes from
“Original Text Content” to “New Text Content”.
Exercise 2: Modifying CSS Styles
Manipulating CSS styles with JavaScript is a powerful way to
dynamically change the appearance of elements on a web page. This
exercise will demonstrate how to access and modify the CSS
properties of DOM elements using JavaScript.
Step-by-Step Guide
1.Select the Element:
Use document.getElementById(), document.querySelector(), or other
selection methods to target the element whose style you want to
change.
// Example: Selecting an element with the id "example"
let element = document.getElementById("example");
2. Modify CSS Styles: Use the style property to set new CSS styles.
// Changing the background color and font size of the selected
element
element.style.backgroundColor = "lightblue";
element.style.fontSize = "20px";
Example
Suppose you have the following HTML:
<p id="example">This is a paragraph.</p>
<button id="changeStyleButton">Change Style</button>
You can change the styles of the paragraph when the button is
clicked with the following JavaScript:
// Selecting the button element
let button = document.getElementById("changeStyleButton");

// Adding an event listener to the button


button.addEventListener("click", function() {
// Selecting the paragraph element
let paragraph = document.getElementById("example");

// Changing the background color and font size of the paragraph


paragraph.style.backgroundColor = "lightblue";
paragraph.style.fontSize = "20px";
});
Exercise 3: Adding and Removing Classes
Adding and removing classes with JavaScript is a versatile way to
apply or remove multiple styles from elements dynamically. This
exercise will guide you through the process of manipulating classes
using JavaScript.
Step-by-Step Guide
1. Select the Element:
Use document.getElementById(), document.querySelector(), or
other selection methods to target the element.
// Example: Selecting an element with the id "example"
let element = document.getElementById("example");
2. Add or Remove Classes: Use classList.add(), classList.remove(),
and classList.toggle() to manipulate the classes of the selected
element.
// Adding a class to the selected element
element.classList.add("new-class");

// Removing a class from the selected element


element.classList.remove("old-class");

// Toggling a class on the selected element


element.classList.toggle("toggle-class");
Example
Suppose you have the following HTML:
<p id="example" class="old-class">This is a paragraph.</p>
<button id="toggleClassButton">Toggle Class</button>
You can add, remove, and toggle classes on the paragraph when the
button is clicked with the following JavaScript:
// Selecting the button element
let button = document.getElementById("toggleClassButton");

// Adding an event listener to the button


button.addEventListener("click", function() {
// Selecting the paragraph element
let paragraph = document.getElementById("example");

// Toggling the class on the paragraph


paragraph.classList.toggle("new-class");
});
Exercise 4: Creating and Appending Elements
Creating and appending new elements to the DOM is essential for
building dynamic and interactive web applications. This exercise will
teach you how to create new elements and add them to the DOM
using JavaScript.
Step-by-Step Guide
1. Create the Element: Use document.createElement() to create a
new element.
// Example: Creating a new paragraph element
let newElement = document.createElement("p");
2. Set Attributes and Content: Use properties
like textContent, innerHTML, or setAttribute() to set the content and
attributes of the new element.
// Setting the text content of the new element
newElement.textContent = "This is a new paragraph.";
// Setting an attribute for the new element
newElement.setAttribute("class", "new-class");
3. Append the Element: Use appendChild() or append() to add the
new element to an existing element in the DOM.
// Selecting the parent element
let parentElement = document.getElementById("parent");

// Appending the new element to the parent element


parentElement.appendChild(newElement);
Example
Suppose you have the following HTML:
<div id="parent">
<p>This is an existing paragraph.</p>
</div>
<button id="addElementButton">Add Element</button>
You can create and append a new paragraph to the div when the
button is clicked with the following JavaScript:
// Selecting the button element
let button = document.getElementById("addElementButton");

// Adding an event listener to the button


button.addEventListener("click", function() {
// Creating a new paragraph element
let newParagraph = document.createElement("p");

// Setting the text content of the new paragraph


newParagraph.textContent = "This is a new paragraph.";

// Selecting the parent element


let parentDiv = document.getElementById("parent");
// Appending the new paragraph to the parent div
parentDiv.appendChild(newParagraph);
});
OUTPUT:
This is an existing paragraph.
This is a new paragraph.
[Add Element Button]
Exercise 5: Removing Elements
Removing elements from the DOM is a common task in web
development, especially when managing dynamic content.
Step-by-Step Guide
1. Select the Element:
Use document.getElementById(), document.querySelector(), or
other selection methods to target the element you want to
remove.
// Example: Selecting an element with the id "example"
let element = document.getElementById("example");
2. Remove the Element: Use the remove() method to remove the
selected element directly, or use removeChild() on the parent
element to remove a specific child element.
// Removing the selected element directly
element.remove();

// Alternatively, removing the selected element via its parent


let parent = document.getElementById("parent");
let child = document.getElementById("example");
parent.removeChild(child);
Example
Suppose you have the following HTML:
<div id="parent">
<p id="example">This is a paragraph to be removed.</p>
</div>
<button id="removeElementButton">Remove Element</button>
// Selecting the button element
let button = document.getElementById("removeElementButton");

// Adding an event listener to the button


button.addEventListener("click", function() {
// Selecting the paragraph element to be removed
let paragraph = document.getElementById("example");

// Removing the paragraph element directly


paragraph.remove();

// Alternatively, you could remove the paragraph via its parent


// let parentDiv = document.getElementById("parent");
// parentDiv.removeChild(paragraph);
});
Exercise 6: Handling Events
Handling events is a fundamental aspect of creating interactive web
applications.
Objective
Add event listeners to elements and handle user interactions.
Step-by-Step Guide
1. Select the Element:
Use document.getElementById(), document.querySelector(), or
other selection methods to target the element to which you
want to add an event listener.
// Example: Selecting a button element with the id "exampleButton"
let button = document.getElementById("exampleButton");
2. Add an Event Listener: Use the addEventListener() method to add
an event listener to the selected element. Specify the event type
(e.g., 'click', 'mouseover') and the function to be executed when the
event occurs.
// Adding a 'click' event listener to the button
button.addEventListener("click", function() {
alert("Button was clicked!");
});
Example
Suppose you have the following HTML:
<button id="exampleButton">Click Me</button>
<p id="message">No interactions yet.</p>
You can update the text content of the paragraph when the button is
clicked with the following JavaScript:
// Selecting the button element
let button = document.getElementById("exampleButton");

// Adding an event listener to the button


button.addEventListener("click", function() {
// Selecting the paragraph element
let message = document.getElementById("message");

// Changing the text content of the paragraph


message.textContent = "Button was clicked!";
});
Event Listeners for Different Event Types
Event listeners can listen for a variety of DOM events:
 Mouse Events: click, dblclick, mousedown, mouseup,
mousemove, mouseover, mouseout, mouseenter, mouseleave
 Keyboard Events: keydown, keyup, keypress
 Form Events: submit, change, focus, blur, input
 Window Events: resize, scroll, load, unload, error
Exercise 7: Traversing the DOM
Navigating through different parts of the DOM tree is crucial for
accessing and manipulating related elements.
Objective
Navigate through the DOM tree to access parent, child, and sibling
elements.
Step-by-Step Guide
1.Select the Element:
Use document.getElementById(), document.querySelector(), or other
selection methods to target the starting element.
// Example: Selecting an element with the id "example"
let element = document.getElementById("example");
2. Traverse to Parent Element: Use
the parentNode or parentElement property to access the parent
element.
// Accessing the parent element
let parent = element.parentNode;
3. Traverse to Child Elements: Use the children property to access
child elements or firstElementChild and lastElementChild to access
the first and last child elements, respectively.
// Accessing the child elements
let children = element.children;

// Accessing the first and last child elements


let firstChild = element.firstElementChild;
let lastChild = element.lastElementChild;
4. Traverse to Sibling Elements: Use
the nextElementSibling and previousElementSibling properties to
access the next and previous sibling elements.
// Accessing the next and previous sibling elements
let nextSibling = element.nextElementSibling;
let previousSibling = element.previousElementSibling;
Example
Suppose you have the following HTML:
<div id="parent">
<p id="example">This is a paragraph.</p>
<p>This is the next paragraph.</p>
</div>
You can traverse the DOM from the paragraph with the id “example”
with the following JavaScript:
// Selecting the element with the id "example"
let element = document.getElementById("example");

// Accessing the parent element


let parent = element.parentNode;
console.log("Parent element:", parent);
// This will log the entire <div id="parent"> element and its content,
including the two <p> elements it contains.
// Accessing the child elements of the parent
let children = parent.children;
console.log("Child elements:", children);
// This will log an HTMLCollection containing the two <p> elements
that are children of the <div id="parent">.

// Accessing the next sibling element


let nextSibling = element.nextElementSibling;
console.log("Next sibling element:", nextSibling);
// This will log the next <p> element, which is <p>This is the next
paragraph.</p>.
In this example, you traverse from the selected paragraph to its
parent, list the child elements of the parent, and access the next
sibling element.
Key Takeaways
 Use parentNode or parentElement to traverse to the parent
element.
 Use children, firstElementChild, and lastElementChild to
traverse to child elements.
 Use nextElementSibling and previousElementSibling to traverse
to sibling elements.
 DOM traversal is essential for accessing and manipulating
related elements in the DOM tree.
By practicing this exercise, you will learn how to navigate through the
DOM tree to access and manipulate related elements, a fundamental
skill for advanced DOM manipulation.
Exercise 8: Manipulating Form Elements
Manipulating form elements is a key aspect of creating interactive
web forms. This exercise will teach you how to access and
manipulate form elements using JavaScript.
Objective
Access and manipulate form elements to handle user input.
Step-by-Step Guide
1.Select the Form Elements:
Use document.getElementById(), document.querySelector(), or other
selection methods to target the form elements.
// Example: Selecting an input element with the id "exampleInput"
let inputElement = document.getElementById("exampleInput");
2. Get and Set Values: Use the value property to get or set the value
of the form element.
// Getting the value of the input element
let inputValue = inputElement.value;

// Setting a new value for the input element


inputElement.value = "New Value";
3. Handle Form Submission: Use an event listener to handle form
submission and prevent the default behavior.
Example
Suppose you have the following HTML:
<form id="exampleForm">
<input type="text" id="exampleInput" value="Initial Value">
<button type="submit">Submit</button>
</form>
<p id="output"></p>
You can manipulate the input value and handle form submission with
the following JavaScript:
// Selecting the input and form elements
let inputElement = document.getElementById("exampleInput");
let form = document.getElementById("exampleForm");

// Adding an event listener to handle form submission


form.addEventListener("submit", function(event) {
event.preventDefault(); // Prevents the default form submission
behavior

// Getting the value of the input element on form submission


let inputValue = inputElement.value;

// Displaying the input value in a paragraph element


let output = document.getElementById("output");
output.textContent = "Form submitted with input value: " +
inputValue;
});
OUPUT:
Form submitted with input value: New Value
Form submitted with input value: Initial Value
HTML CODE: <!DOCTYPE html>
<html>
<head>
<title>Form Submission Example</title>
</head>
<body>
<!-- Form with an input and submit button -->
<form id="exampleForm">
<label for="exampleInput">Enter Value:</label>
<input type="text" id="exampleInput" value="Initial Value">
<button type="submit">Submit</button>
</form>

<!-- Paragraph to display the submitted value -->


<p id="output"></p>

<script>
// Selecting the input and form elements
let inputElement = document.getElementById("exampleInput");
let form = document.getElementById("exampleForm");

// Adding an event listener to handle form submission


form.addEventListener("submit", function(event) {
event.preventDefault(); // Prevents the default form
submission behavior

// Getting the value of the input element on form submission


let inputValue = inputElement.value;

// Displaying the input value in a paragraph element


let output = document.getElementById("output");
output.textContent = "Form submitted with input value: " +
inputValue;
});
</script>
</body>
</html>
OUTPUT

You might also like