0% found this document useful (0 votes)
14 views44 pages

Selecting and Modifying DOM Elements (5 Tasks) : Assignment 2

The document contains a series of JavaScript assignments focused on DOM manipulation, event handling, error handling, debugging techniques, and template literals. Each section includes specific tasks with corresponding HTML and JavaScript code examples demonstrating how to perform various operations. The assignments aim to enhance understanding of JavaScript functionalities and best practices.

Uploaded by

viishah0810
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views44 pages

Selecting and Modifying DOM Elements (5 Tasks) : Assignment 2

The document contains a series of JavaScript assignments focused on DOM manipulation, event handling, error handling, debugging techniques, and template literals. Each section includes specific tasks with corresponding HTML and JavaScript code examples demonstrating how to perform various operations. The assignments aim to enhance understanding of JavaScript functionalities and best practices.

Uploaded by

viishah0810
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 44

NAME:VIDHI SHAH

ROLL NO:44

ASSIGNMENT 2

--------------------------------------------------------------------------------------------------------
------

1. Selecting and Modifying DOM Elements (5 Tasks)


1. Select a paragraph by its ID and change its text.

2. Change the background color of a button using its class.

3. Select an input field and update its value.

4. Modify the text of the second list item.

5. Select all <h2> tags and change the font size of the first one.

--------------------------------------------------------------------------------------------------------
------

Ans:

<!DOCTYPE html>

<html>

<head>

<title>DOM Manipulation Example</title>

<style>

.myButton {

padding: 10px;

border: none;

color: white;

background-color: gray;

</style>

</head>

<body>
<!-- Task 1: Paragraph with ID -->

<p id="myParagraph">Original paragraph text</p>

<!-- Task 2: Button with class -->

<button class="myButton">Click Me</button>

<!-- Task 3: Input field -->

<br><br>

<input type="text" value="Old value">

<!-- Task 4: List items -->

<ul>

<li>First item</li>

<li>Second item</li>

<li>Third item</li>

</ul>

<!-- Task 5: h2 tags -->

<h2>Heading One</h2>

<h2>Heading Two</h2>

<!-- JavaScript -->


<script>

// Task 1: Change paragraph text

document.getElementById("myParagraph").innerText = "This is the


new text!";

// Task 2: Change background color of button


document.querySelector(".myButton").style.backgroundColor =
"green";

// Task 3: Update input field value

document.querySelector("input").value = "New input value";

// Task 4: Change text of second list item

document.querySelectorAll("li")[1].innerText = "Updated second


item";

// Task 5: Change font size of first h2 tag

document.querySelectorAll("h2")[0].style.fontSize = "30px";

</script>

</body>

</html>

--------------------------------------------------------------------------------------------------------
------

Output:
--------------------------------------------------------------------------------------------------------
------

2. Modifying Elements (5 Tasks)


1. Change the text content of a heading tag.

2. Add a new CSS class to a div element.

3. Set a custom attribute (data-info) to a paragraph.

4. Hide an image element using style.

5. Replace a div's content with bold text.

--------------------------------------------------------------------------------------------------------
------

Ans:

<!DOCTYPE html>

<html>

<head>

<title>Modifying Elements Example</title>


<style>

.highlight {

background-color: yellow;

padding: 10px;

border: 1px solid black;

</style>

</head>

<body>

<!-- Task 1: Heading -->

<h1 id="mainHeading">Original Heading</h1>

<!-- Task 2: Div element -->

<div id="myDiv">This is a simple div.</div>

<!-- Task 3: Paragraph -->

<p id="myPara">This paragraph needs data.</p>

<!-- Task 4: Image -->

<img id="myImage" src="C:\Users\pkesh\OneDrive\Desktop\


ass2\3.jpg" alt="Image">

<!-- Task 5: Div to replace content -->

<div id="replaceDiv">Old content here</div>

<!-- JavaScript -->

<script>
// Task 1: Change heading text

document.getElementById("mainHeading").textContent = "Updated
Heading Text";

// Task 2: Add new CSS class to a div

document.getElementById("myDiv").classList.add("highlight");

// Task 3: Set a custom data attribute

document.getElementById("myPara").setAttribute("data-info", "Extra
information added");

// Task 4: Hide image using style

document.getElementById("myImage").style.display = "none";

// Task 5: Replace div's content with bold text

document.getElementById("replaceDiv").innerHTML = "<b>This is
bold new content</b>";

</script>

</body>

</html>

--------------------------------------------------------------------------------------------------------
------
Output:

--------------------------------------------------------------------------------------------------------
------

Q-3] Event Handling in JavaScript (5 Tasks)

1. Add a click event to a button to display an alert.

2. Handle key press in a text input and log the key.

3. Add a submit event to a form and prevent page reload.

4. Trigger a color change on mouseover of a box.

5. Show a message when the page finishes loading.


------ code

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-


scale=1.0">

<title>JavaScript Event Handling</title>

<style>

.box {

width: 100px;

height: 100px;

background-color: lightblue;

margin: 10px;

display: inline-block;

.form-container {

margin-top: 20px;

#loadingMessage {

color: green;

font-weight: bold;

text-align: center;

display: none; /* Hidden initially */

</style>

</head>

<body>
<h1>JavaScript Event Handling Tasks</h1>

<!-- Task 5: Message on Page Load -->

<p id="loadingMessage">The page has finished loading!</p>

<!-- Task 1: Click Event -->

<button id="alertButton">Click Me</button>

<!-- Task 2: Key Press Event -->

<input type="text" id="keyInput" placeholder="Type


something..." />

<!-- Task 3: Submit Event -->

<div class="form-container">

<form id="exampleForm">

<input type="text" placeholder="Enter your name"


required />

<button type="submit">Submit</button>

</form>

</div>

<!-- Task 4: Mouseover Event -->

<div class="box" id="colorBox"></div>

<script>

// Task 5: Show a message when the page finishes loading

window.addEventListener("load", () => {

const loadingMessage =
document.getElementById("loadingMessage");

loadingMessage.style.display = "block";
});

// Task 1: Add a click event to a button to display an alert

document.getElementById("alertButton").addEventListener("click
", () => {

alert("Button clicked!");

});

// Task 2: Handle key press in a text input and log the key

document.getElementById("keyInput").addEventListener("keypre
ss", (event) => {

console.log(`Key pressed: ${event.key}`);

});

// Task 3: Add a submit event to a form and prevent page reload

document.getElementById("exampleForm").addEventListener("su
bmit", (event) => {

event.preventDefault(); // Prevents the default form


submission behavior

alert("Form submitted without page reload!");

});

// Task 4: Trigger a color change on mouseover of a box

const colorBox = document.getElementById("colorBox");

colorBox.addEventListener("mouseover", () => {

colorBox.style.backgroundColor = "lightgreen";

});
colorBox.addEventListener("mouseout", () => {

colorBox.style.backgroundColor = "lightblue"; // Reset to


original color

});

</script>

</body>

</html>------------ output
-------- change color
----- finish loading

Q-4] try...catch in JavaScript (5 Tasks)


1. Handle a reference error when accessing an undefined
variable.

2. Catch an error when parsing invalid JSON.

3. Handle a thrown custom error.

4. Catch and display an error from a function call.

5. Use try...catch to validate a number from user input.

------ code

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-


scale=1.0">

<title>JavaScript Try...Catch Tasks</title>

</head>

<body>

<h1>JavaScript Try...Catch Examples</h1>

<p>Open the console to see the outputs.</p>

<script>

// Task 1: Handle a reference error when accessing an


undefined variable

try {

console.log(nonExistentVariable); // Undefined variable

} catch (error) {

console.error("Task 1 - Reference Error caught:",


error.message);

}
// Task 2: Catch an error when parsing invalid JSON

try {

const invalidJSON = "{ name: 'John' }"; // Invalid JSON (keys


need double quotes)

JSON.parse(invalidJSON);

} catch (error) {

console.error("Task 2 - JSON Error caught:", error.message);

// Task 3: Handle a thrown custom error

try {

throw new Error("This is a custom error");

} catch (error) {

console.error("Task 3 - Custom Error caught:", error.message);

// Task 4: Catch and display an error from a function call

function riskyFunction() {

throw new Error("An error occurred in riskyFunction");

try {

riskyFunction();

} catch (error) {

console.error("Task 4 - Function Error caught:",


error.message);

// Task 5: Use try...catch to validate a number from user input

function validateNumber(input) {
try {

const number = parseFloat(input);

if (isNaN(number)) {

throw new Error("Input is not a valid number");

console.log("Task 5 - Valid number:", number);

} catch (error) {

console.error("Task 5 - Validation Error caught:",


error.message);

// Example user input (can be dynamic in real-world use)

validateNumber("123"); // Valid input

validateNumber("abc"); // Invalid input

</script>

</body>

</html>

---------- output
---- console log
Q-5. Debugging Techniques in JavaScript (5 Tasks)

1. Use console.log to debug a variable value.

<!DOCTYPE html>

<html>

<head>

<title>console.log Debugging</title>

</head>

<body>

<h1>Debugging with console.log</h1>

<script>

let username = "Alice";

console.log("The value of username is:", username);

</script>

</body>

</html>
2. Use console.error to log an error message.

<!DOCTYPE html>

<html>

<head>

<title>Debugging Task 2 - console.error</title>

</head>

<body>

<h1>Debugging Task 2</h1>

<button onclick="checkAge()">Check Age</button>

<script>

function checkAge()

let age = 5;

if (age < 0)

console.error("Error: Age cannot be negative.");

else
{

console.log("Valid age:", age);

</script>

</body>

</html>

3. Use the debugger statement to pause code execution.

<!DOCTYPE html>

<html>

<head>

<title>Debugging Task 3 - debugger</title>

</head>

<body>

<h1>Debugging Task 3</h1>

<button onclick="calculateTotal()">Run Debug</button>

<script>

function calculateTotal()

{
let price = 100;

let quantity = 2;

// Pause here for debugging

debugger;

let total = price * quantity;

console.log("Total amount:", total);

</script>

</body>

</html>

4. Use console.table to display object data in a table.

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Console Table Debugging</title>


</head>

<body>

<h1>Open the console to see console.table in action</h1>

<script>

const users = [

{ id: 1, name: "Alice", email: "alice@example.com", role: "Admin" },

{ id: 2, name: "Bob", email: "bob@example.com", role: "Editor" },

{ id: 3, name: "Charlie", email: "charlie@example.com", role:


"Viewer" },

{ id: 4, name: "Dana", email: "dana@example.com", role: "Editor" },

];

console.table(users);

</script>

</body>

</html>

5. Display an alert to check script execution order.

<!DOCTYPE html>
<html lang="en">

<head>

<meta charset="UTF-8">

<title>Script Execution Order</title>

</head>

<body>

<h1>JavaScript Debugging: Execution Order</h1>

<script>

alert("Step 1: Script begins");

let x = 5;

alert("Step 2: Variable x is assigned with value " + x);

function displayMessage() {

alert("Step 3: Inside the function displayMessage()");

displayMessage();

alert("Step 4: Script ends");

</script>

</body>

</html>
6. Template Literals in JavaScript (5 Tasks)

1.Create a greeting message using a variable and template literal.

<!DOCTYPE html>
<html lang="en">

<head>

<meta charset="UTF-8">

<title>Template Literal - Greeting</title>

</head>

<body>

<h1>Greeting Message</h1>

<p id="greeting"></p>

<script>

let name = "Alice";

let greeting = `Hello, ${name}! Welcome to the site.`;

document.getElementById("greeting").textContent = greeting;

</script>

</body>

</html>

2. Use template literal to display total price using two variables.

<!DOCTYPE html>

<html lang="en">

<head>
<meta charset="UTF-8">

<title>Template Literal - Total Price</title>

</head>

<body>

<h1>Total Price</h1>

<p id="priceInfo"></p>

<script>

let pricePerItem = 20;

let quantity = 3;

let totalPrice = pricePerItem * quantity;

let message = `You bought ${quantity} items for $${pricePerItem}


each. Total: $${totalPrice}.`;

document.getElementById("priceInfo").textContent = message;

</script>

</body>

</html>

3. Create a multi-line string using backticks.

<!DOCTYPE html>
<html lang="en">

<head>

<meta charset="UTF-8">

<title>Template Literal - Multi-line String</title>

</head>

<body>

<h1>Multi-line String</h1>

<pre id="multilineText"></pre>

<script>

let multiLineMessage = `This is a multi-line string.

Video provides a powerful way


to help you

prove your point. When you click


Online Video,

you can paste in the embed


code for the video

you want to add. You can also


type a keyword

to search online for the video


that best fits

your document.`;

document.getElementById("multilineText").textContent =
multiLineMessage;

</script>

</body>
</html>

4. Build a dynamic HTML structure with template literals.

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Template Literals - Dynamic HTML Structure</title>

<style>

.user-card {

border: 2px solid #007BFF;

border-radius: 10px;

padding: 15px;

width: 250px;

background-color: #f0f8ff;

font-family: Arial, sans-serif;

.user-card h2 {

color: #007BFF;

margin-bottom: 10px;

</style>

</head>
<body>

<h1>User Info Card</h1>

<div id="userContainer"></div>

<script>

let userName = "John Doe";

let userAge = 30;

let userEmail = "john.doe@example.com";

let userCard = `

<div class="user-card">

<h2>${userName}</h2>

<p>Age:${userAge}</p>

<p>Email:${userEmail}</p>

</div>`;

document.getElementById("userContainer").innerHTML = userCard;

</script>

</body>

</html>
5. Print user details using variables inside template literal.

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Template Literals - User Details</title>

</head>

<body>

<h1>User Details</h1>

<p id="userDetails"></p>

<script>

let firstName = "Emma";

let lastName = "Johnson";

let age = 25;

let city = "New York";

let userInfo = `User Info: ${firstName} ${lastName}, Age: ${age},


City: ${city}.`;

document.getElementById("userDetails").textContent = userInfo;

</script>

</body>

</html>
Q-7. Destructuring (5 Tasks)

1. Destructure values from an array into variables.

2. Destructure properties from an object.

3. Rename a destructured property during assignment.

4. Destructure with default values.

5. Extract a nested value from an object.

------- code

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-


scale=1.0">

<title>Destructuring Example</title>

</head>

<body>

<h1>Check the Console for Output</h1>

<script>

// Task 1: Destructure values from an array into variables

const fruits = ["Apple", "Banana", "Cherry"];


const [firstFruit, secondFruit, thirdFruit] = fruits;

console.log(firstFruit); // Output: Apple

console.log(secondFruit); // Output: Banana

console.log(thirdFruit); // Output: Cherry

// Task 2: Destructure properties from an object

const person = { name: "Alice", age: 25, city: "New York" };

const { name, age, city } = person;

console.log(name); // Output: Alice

console.log(age); // Output: 25

console.log(city); // Output: New York

// Task 3: Rename a destructured property during assignment

const car = { brand: "Toyota", model: "Corolla" };

const { brand: carBrand, model: carModel } = car;

console.log(carBrand); // Output: Toyota

console.log(carModel); // Output: Corolla

// Task 4: Destructure with default values

const book = { title: "1984", author: "George Orwell" };

const { title, author, year = 1949 } = book; // Default value


for 'year'

console.log(title); // Output: 1984

console.log(author); // Output: George Orwell

console.log(year); // Output: 1949

// Task 5: Extract a nested value from an object

const student = {

id: 123,
details: {

firstName: "John",

lastName: "Doe",

grades: { math: "A", science: "B" }

};

const { details: { firstName, grades: { math } } } = student;

console.log(firstName); // Output: John

console.log(math); // Output: A

</script>

</body>

</html>

---------- output
Q-8]

------- code

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-


scale=1.0">

<title>Callback Examples</title>

</head>

<body>

<h1>Callback Examples</h1>

<button id="eventButton">Click Me</button>

<script>

// Task 1: Create a function that accepts and runs a callback


function executeTask(taskDescription, callback) {

console.log(`Executing: ${taskDescription}`);

callback(); // Call the provided callback function

executeTask("Demonstration Task", () => {

console.log("Task complete!");

});

// Task 2: Use setTimeout to delay a message

console.log("Waiting for 2 seconds...");

setTimeout(() => {

console.log("This message is delayed by 2 seconds.");

}, 2000);

// Task 3: Use a callback to process array items

function processItems(array, callback) {

array.forEach(item => callback(item));

const items = ["Apple", "Banana", "Cherry"];

processItems(items, (item) => {

console.log(`Processing item: ${item}`);

});

// Task 4: Pass a callback to log data after loading

function fetchData(callback) {

console.log("Fetching data...");

setTimeout(() => {

const data = { id: 101, name: "Sample Item", status:


"Available" };
console.log("Data fetched successfully.");

callback(data); // Pass the fetched data to the callback

}, 1500);

fetchData((data) => {

console.log("Data received:", data);

});

// Task 5: Use a callback in an event listener

const button = document.getElementById("eventButton");

button.addEventListener("click", () => {

console.log("Button clicked! Event listener executed.");

});

</script>

</body>

</html>

--------- output
9. Promises (5 Tasks)

1. Create a Promise that resolves with a message.

2. Use .then() to display a resolved value.

3. Use .catch() to handle a rejected Promise.

4. Chain two .then() calls to transform data.

5. Use Promise.all() with multiple resolved Promises.

ANS:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>JavaScript Promises Tasks</title>

</head>

<body>

<h2>Open the Console (F12) to See the Output of Promises</h2>


<script>

// 1. Create a Promise that resolves with a message

const myPromise = new Promise((resolve, reject) => {

resolve("✅ Promise has been resolved successfully!");

});

// 2. Use .then() to display a resolved value

myPromise.then((message) => {

console.log("Then:", message);

});

// 3. Use .catch() to handle a rejected Promise

const rejectedPromise = new Promise((resolve, reject) => {

reject("❌ Oops! Something went wrong.");

});

rejectedPromise

.then((result) => {

console.log("This won't run:", result);

})

.catch((error) => {

console.log("Catch:", error);

});

// 4. Chain two .then() calls to transform data

const chainPromise = Promise.resolve(10);

chainPromise

.then((num) => {
return num * 2; // 10 * 2 = 20

})

.then((result) => {

console.log("Chained Result:", result); // Output: 20

});

// 5. Use Promise.all() with multiple resolved Promises

const promise1 = Promise.resolve("🌟 First Promise");

const promise2 = Promise.resolve("🚀 Second Promise");

const promise3 = Promise.resolve("🎯 Third Promise");

Promise.all([promise1, promise2, promise3])

.then((values) => {

console.log("Promise.all Result:", values);

});

</script>

</body>

</html>

OUTPUT:
10. Async/Await (5 Tasks)

1. Create an async function that returns a value.

2. Use await to fetch and log data.

3. Use try...catch with await to handle an error.

4. Delay execution using await with a Promise.


5. Await multiple Promises and log the results.

ANS:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Async/Await Tasks</title>

</head>

<body>

<h2>Open the Console (F12) to See Output of Async/Await Tasks</h2>

<script>

// 1. Create an async function that returns a value

async function greetUser() {

return "👋 Hello from async function!";

greetUser().then((msg) => console.log("1. Async Return:", msg));

// 2. Use await to fetch and log data (mocked fetch with Promise)

async function fetchData() {

const fakeFetch = () => {

return new Promise((resolve) => {

setTimeout(() => {

resolve({ data: "📦 Fetched some fake data!" });

}, 1000);

});

};
const result = await fakeFetch();

console.log("2. Awaited Fetch:", result.data);

fetchData();

// 3. Use try...catch with await to handle an error

async function fetchWithError() {

const failingPromise = () => {

return new Promise((_, reject) => {

setTimeout(() => {

reject("❌ Failed to fetch data.");

}, 1000);

});

};

try {

const result = await failingPromise();

console.log(result);

} catch (error) {

console.log("3. Caught Error:", error);

fetchWithError();

// 4. Delay execution using await with a Promise

function delay(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));

async function delayedMessage() {

console.log("4. Waiting 2 seconds...");

await delay(2000);

console.log("⏳ 2 seconds later...");

delayedMessage();

// 5. Await multiple Promises and log the results

async function multiplePromises() {

const p1 = Promise.resolve("✅ Task 1 done");

const p2 = Promise.resolve("✅ Task 2 done");

const p3 = Promise.resolve("✅ Task 3 done");

const results = await Promise.all([p1, p2, p3]);

console.log("5. All Promises Resolved:", results);

multiplePromises();

</script>

</body>

</html>

OUTPUT:

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy