[go: up one dir, main page]

0% found this document useful (0 votes)
2 views29 pages

Fs Module2

The Document Object Model (DOM) is a programming interface for web documents that represents the structure of HTML or XML documents as a tree of nodes. JavaScript interacts with the DOM to manipulate content, structure, and styling dynamically, allowing for event handling, CSS manipulation, and the creation or removal of elements. Key methods for selecting elements include getElementById(), getElementsByClassName(), and querySelector(), each serving different purposes for element selection.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views29 pages

Fs Module2

The Document Object Model (DOM) is a programming interface for web documents that represents the structure of HTML or XML documents as a tree of nodes. JavaScript interacts with the DOM to manipulate content, structure, and styling dynamically, allowing for event handling, CSS manipulation, and the creation or removal of elements. Key methods for selecting elements include getElementById(), getElementsByClassName(), and querySelector(), each serving different purposes for element selection.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

1. Discuss the Document Object Model (DOM) in JavaScript? Explain its significance.

Document Object Model (DOM) in JavaScript

The Document Object Model (DOM) is a programming interface for web documents. It
represents the structure of an HTML or XML document as a tree-like structure where each
element, attribute, and piece of text is a node.

JavaScript interacts with the DOM to dynamically manipulate the content, structure, and
styling of a web page.

Structure of the DOM

The DOM is structured as a tree, starting with the document object at the root:

Document

├── <html>

│ ├── <head>

│ │ ├── <title>...</title>

│ │ ├── <meta>...</meta>

│ ├── <body>

│ ├── <h1>...</h1>

│ ├── <p>...</p>

│ ├── <div>

│ ├── <ul>

│ ├── <li>...</li>

│ ├── <li>...</li>

Each HTML element is a node in this hierarchy.

Significance of the DOM in JavaScript

1. Dynamic Content Manipulation

o JavaScript can modify elements, change text, and update styles dynamically.

o Example:
javascript

CopyEdit

document.getElementById("demo").innerHTML = "Hello, World!";

2. Event Handling

o JavaScript can respond to user interactions such as clicks, keypresses, or


mouse movements.

o Example:

javascript

CopyEdit

document.getElementById("btn").addEventListener("click", function() {

alert("Button clicked!");

});

3. CSS Manipulation

o JavaScript can change styles dynamically.

o Example:

javascript

CopyEdit

document.getElementById("box").style.backgroundColor = "blue";

4. Traversing & Searching Elements

o JavaScript can navigate through child and parent elements.

o Example:

javascript

CopyEdit

let parent = document.getElementById("child").parentNode;

5. Creating and Removing Elements

o JavaScript can add or delete elements.

o Example:

javascript
CopyEdit

let newElement = document.createElement("p");

newElement.textContent = "New paragraph";

document.body.appendChild(newElement);

6. Building Interactive Web Apps

o Used in frameworks like React, Angular, and Vue.js for efficient UI updates.

2. Differentiate between getElementById(), getElementsByClassName(), and querySelector()


with examples.

1. getElementById()

• Purpose: Selects a single element based on its unique id attribute.

• Syntax: document.getElementById('idName')

• Returns: The element object if found; otherwise, null.Stack Overflow

Example:

html

CopyEdit

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>getElementById Example</title>

</head>

<body>

<div id="uniqueElement">Hello World!</div>

<script>

var element = document.getElementById('uniqueElement');

console.log(element.textContent); // Output: Hello World!


</script>

</body>

</html>

Key Points:

• The id should be unique within the document.

• Direct and fast selection method.

• Only available on the document object.

2. getElementsByClassName()

• Purpose: Selects all elements that have a specific class name.

• Syntax: document.getElementsByClassName('className')

• Returns: A live HTMLCollection of elements.The freeCodeCamp


Forum+5Medium+5Treehouse+5

Example:

html

CopyEdit

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>getElementsByClassName Example</title>

</head>

<body>

<p class="text">Paragraph 1</p>

<p class="text">Paragraph 2</p>

<script>

var elements = document.getElementsByClassName('text');


console.log(elements.length); // Output: 2

console.log(elements[0].textContent); // Output: Paragraph 1

</script>

</body>

</html>

Key Points:

• Returns a live collection; changes in the DOM are reflected in the collection.
Treehouse+2Stack Overflow+2Medium+2

• Can be called on any element, not just document.

• Does not include the dot (.) prefix when specifying the class name.

3. querySelector()

• Purpose: Selects the first element that matches a specified CSS selector.

• Syntax: document.querySelector('selector')

• Returns: The first matching element, or null if no match is found.

Example:

html

CopyEdit

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>querySelector Example</title>

</head>

<body>

<p class="text">Paragraph 1</p>

<p class="text">Paragraph 2</p>


<script>

var element = document.querySelector('.text');

console.log(element.textContent); // Output: Paragraph 1

</script>

</body>

</html>

Key Points:

• Uses CSS selectors; for classes, include the dot (.) prefix.

• Returns only the first matching element.Stack Overflow

• Can be called on any element.

3. How can you change the text content of an HTML element using JavaScript? Write a code
snippet.

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Change Text Content Example</title>

</head>

<body>

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

<script>

// Select the element by its ID

var paragraph = document.getElementById('myParagraph');

// Change the text content

paragraph.textContent = 'Updated text using JavaScript.';

</script>
</body>

</html>

4. What are the different types of DOM nodes? Explain with examples.

he primary types of DOM nodes include:

1. Element Nodes

2. Text Nodes

3. Comment Nodes

4. Attribute Nodes

5. Document Nodes

Let's explore each of these node types with explanations and examples.

1. Element Nodes

Element nodes represent HTML or XML elements. Each HTML tag in a document
corresponds to an element node. These nodes can have child nodes, including other
element nodes, text nodes, or comment nodes.The Modern JavaScript Tutorial+1MDN Web
Docs+1

Example:

Consider the following HTML snippet:

html

CopyEdit

<div>

<p>Hello, World!</p>

</div>

In this example:

• The <div> tag is an element node.

• The <p> tag is also an element node, which is a child of the <div> node.

2. Text Nodes
Text nodes represent the text content within elements. They are always contained within
element nodes and cannot have any child nodes.

Example:

From the previous HTML snippet:

• The text "Hello, World!" inside the <p> tag is a text node.

Here, the <p> element node contains a single text node with the content "Hello, World!".

3. Comment Nodes

Comment nodes represent comments in the HTML or XML document. They are used to
insert comments that are not displayed in the browser but can be seen in the source code.
MDN Web Docs+2The Modern JavaScript Tutorial+2DigitalOcean+2

Example:

html

CopyEdit

<!-- This is a comment -->

<p>Visible text</p>

In this example:TutorialsPoint+2The Modern JavaScript Tutorial+2MDN Web Docs+2

• The <!-- This is a comment --> is a comment node.

• The <p> tag is an element node containing a text node with the content "Visible
text".

4. Attribute Nodes

Attribute nodes represent the attributes of an element. In the DOM, attributes are
considered nodes associated with element nodes. However, in modern DOM
implementations, attributes are typically accessed directly as properties of element nodes
rather than as separate attribute nodes.DigitalOcean

Example:

html

CopyEdit

<a href="https://www.example.com">Visit Example</a>


In this example:

• The <a> tag is an element node.

• The href attribute (href="https://www.example.com") is an attribute node associated


with the <a> element.

To access the href attribute in JavaScript:

javascript

CopyEdit

var link = document.querySelector('a');

console.log(link.getAttribute('href')); // Outputs: https://www.example.com

5. Document Nodes

The document node represents the entire HTML or XML document. It serves as the root of
the DOM tree, and all other nodes are descendants of this node.

Example:

In a web page, the document object in JavaScript is the document node. You can access
elements within the document using this node:

javascript

CopyEdit

var title = document.title;

console.log(title); // Outputs the title of the document

5.Discuss event delegation in JavaScript. Why is it useful? Explain different ways to select
elements in the DOM. Provide examples using JavaScript.

Event Delegation in JavaScript is a technique where a single event listener is attached to a


parent element to manage events for its current and future child elements. This approach
utilizes event bubbling, where events propagate from the target element up to the parent
elements. By using event delegation, you can efficiently handle events, especially in dynamic
content scenarios, leading to improved performance and simplified code management.

Example of Event Delegation:

javascript
CopyEdit

document.getElementById('parent').addEventListener('click', function(event) {

if (event.target && event.target.matches('.child')) {

console.log('Child element clicked:', event.target.textContent);

});

In this example, a click event listener is added to the parent element with the ID parent.
When any child element with the class child is clicked, the event is captured by the parent,
and the specific child element can be identified using event.target.

Methods to Select DOM Elements:

1. getElementById(): Selects a single element by its unique ID.LinkedIn

javascript

CopyEdit

var element = document.getElementById('uniqueId');

2. getElementsByClassName(): Selects all elements with a specific class name,


returning an HTMLCollection.

javascript

CopyEdit

var elements = document.getElementsByClassName('className');

3. getElementsByTagName(): Selects all elements with a specific tag name, returning


an HTMLCollection.

javascript

CopyEdit

var elements = document.getElementsByTagName('div');

4. querySelector(): Selects the first element that matches a specified CSS selector.

javascript

CopyEdit

var element = document.querySelector('.myClass');


5. querySelectorAll(): Selects all elements that match a specified CSS selector, returning
a NodeList.

javascript

CopyEdit

var elements = document.querySelectorAll('div.myClass');

6. Describe how to add, remove, and modify attributes of an element using JavaScript

In JavaScript, you can manipulate an element's attributes using the following methods:

1. Adding or Modifying Attributes:

o setAttribute(name, value): Sets or updates the specified attribute with the


given value.MDN Web Docs+18 Hobbies JavaScript Blog+1

javascript

CopyEdit

var element = document.getElementById('example');

element.setAttribute('class', 'newClass'); // Adds or updates the 'class' attribute

o Direct Property Assignment: For certain standard attributes, you can set
them directly as properties of the element.

javascript

CopyEdit

element.id = 'newId'; // Sets the 'id' attribute

Note: Direct assignment is generally more efficient and is recommended for standard
attributes.

2. Removing Attributes:

o removeAttribute(name): Removes the specified attribute from the element.


MDN Web Docs

javascript

CopyEdit

element.removeAttribute('class'); // Removes the 'class' attribute


o Setting Property to null or undefined: For certain attributes, setting their
corresponding property to null or undefined can remove the attribute.8
Hobbies JavaScript Blog

javascript

CopyEdit

element.id = null; // Removes the 'id' attribute

Note: This method may not work for all attributes and is generally less reliable than
removeAttribute().

Example:

html

CopyEdit

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Attribute Manipulation Example</title>

</head>

<body>

<div id="example">Hello World!</div>

<script>

var element = document.getElementById('example');

// Add or modify attributes

element.setAttribute('class', 'newClass'); // Adds 'class' attribute with value


'newClass'

element.id = 'newId'; // Changes 'id' from 'example' to 'newId'

// Remove attributes
element.removeAttribute('class'); // Removes the 'class' attribute

element.id = null; // Removes the 'id' attribute

</script>

</body>

</html>

Key Points:

• Use setAttribute() to add or update attributes, especially for non-standard attributes.

• Direct property assignment is preferred for standard attributes due to better


performance.

• Use removeAttribute() to remove an attribute reliably.MDN Web Docs+2MDN Web


Docs+2W3Schools.com+2

• Be cautious when setting properties to null or undefined, as this approach may not
work consistently across all attributes.

By understanding and utilizing these methods, you can effectively manage the attributes
of HTML elements using JavaScript.

7. Explain different type of event listeners in JavaScript? Write a program that listens for
a button click event and changes the background color of a div.
In JavaScript, event listeners are functions that wait for specific events to occur on
elements, such as clicks, mouse movements, or key presses. When the event occurs,
the listener executes a specified function. This mechanism enables interactive and
dynamic web pages.
Types of Event Listeners
JavaScript provides various types of event listeners to handle different user
interactions:
1. Mouse Events: Triggered by mouse actions.
o click: Fires when an element is clicked.
o dblclick: Fires when an element is double-clicked.
o mousedown: Fires when a mouse button is pressed over an element.
o mouseup: Fires when a mouse button is released over an element.
o mousemove: Fires when the mouse is moved over an element.
o mouseover: Fires when the mouse enters an element.
o mouseout: Fires when the mouse leaves an element.
2. Keyboard Events: Triggered by keyboard actions.
o keydown: Fires when a key is pressed down.
o keyup: Fires when a key is released.
o keypress: Fires when a key is pressed and released.
3. Form Events: Triggered by form interactions.
o submit: Fires when a form is submitted.
o change: Fires when the value of an input element changes.
o focus: Fires when an element gains focus.
o blur: Fires when an element loses focus.
4. Window Events: Triggered by window actions.
o load: Fires when the whole page has loaded.
o resize: Fires when the window is resized.
o scroll: Fires when the document is scrolled.
o unload: Fires when the page is unloaded.
These event listeners can be attached to elements using the addEventListener()
method, which allows multiple events to be handled on a single element without
overwriting existing event handlers. MDN Web Docs
Example: Changing Background Color on Button Click
The following example demonstrates how to use an event listener to change the
background color of a <div> element when a button is clicked:
html
CopyEdit
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Change Background Color</title>
<style>
#colorBox {
width: 200px;
height: 200px;
background-color: lightgray;
margin-top: 20px;
}
</style>
</head>
<body>
<button id="changeColorBtn">Change Color</button>
<div id="colorBox"></div>

<script>
// Select the button and div elements
var button = document.getElementById('changeColorBtn');
var colorBox = document.getElementById('colorBox');
// Function to generate a random color
function getRandomColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}

// Add click event listener to the button


button.addEventListener('click', function() {
// Change the background color of the div
colorBox.style.backgroundColor = getRandomColor();
});
</script>
</body>
</html>

8. Discuss different types of JavaScript events with examples.

In JavaScript, events are actions or occurrences that happen in the browser, which can
be triggered by user interactions or by the browser itself. Developers can respond to
these events by defining event handlers or listeners. GeeksforGeeksWikipedia

There are several categories of events in JavaScript:

1. User Interface (UI) Events: Triggered by interactions with the browser window.
DataFlair

o load: Fires when the whole page has loaded, including all dependent
resources such as stylesheets and images. Example:

javascript

CopyEdit

window.addEventListener('load', function() {

console.log('Page fully loaded');

});

o resize: Fires when the document view (window) has been resized. Example:

javascript
CopyEdit

window.addEventListener('resize', function() {

console.log('Window resized');

});

2. Focus and Blur Events: Triggered when an element gains or loses focus.

o focus: Fires when an element gains focus. Example:

javascript

CopyEdit

var inputField = document.getElementById('myInput');

inputField.addEventListener('focus', function() {

console.log('Input field focused');

});

o blur: Fires when an element loses focus. Example:

javascript

CopyEdit

inputField.addEventListener('blur', function() {

console.log('Input field lost focus');

});

3. Mouse Events: Triggered by mouse actions.

o click: Fires when a pointing device button (such as a mouse's primary button)
is clicked. Example:

javascript

CopyEdit

var button = document.getElementById('myButton');

button.addEventListener('click', function() {

console.log('Button clicked');

});

o dblclick: Fires when a pointing device button is double-clicked.


o mousedown: Fires when a pointing device button is pressed down.

o mouseup: Fires when a pointing device button is released.

o mousemove: Fires when a pointing device is moved over an element.

o mouseover: Fires when the pointing device is moved onto an element.

o mouseout: Fires when the pointing device is moved off an element.

4. Keyboard Events: Triggered by keyboard actions.

o keydown: Fires when a key is pressed down. Example:

javascript

CopyEdit

document.addEventListener('keydown', function(event) {

console.log('Key pressed: ' + event.key);

});

o keyup: Fires when a key is released.MDN Web Docs+2MDN Web


Docs+2Wikipedia+2

o keypress: Fires when a key is pressed and released.

5. Form Events: Triggered by actions on form elements.

o submit: Fires when a form is submitted. Example:

javascript

CopyEdit

var form = document.getElementById('myForm');

form.addEventListener('submit', function(event) {

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

console.log('Form submitted');

});

o change: Fires when the value of an element has been changed.

o focus: Fires when an element gains focus.

o blur: Fires when an element loses focus.

6. Clipboard Events: Triggered by actions related to the clipboard.


o copy: Fires when content is copied. Example:

javascript

CopyEdit

document.addEventListener('copy', function() {

console.log('Content copied');

});

o cut: Fires when content is cut.

o paste: Fires when content is pasted.

7. Media Events: Triggered by media elements like <audio> and <video>.

o play: Fires when media playback starts. Example:

javascript

CopyEdit

var video = document.getElementById('myVideo');

video.addEventListener('play', function() {

console.log('Video started playing');

});

o pause: Fires when media playback is paused.

o ended: Fires when media playback reaches the end.DataFlair

o volumechange: Fires when the volume is changed.

8. Drag Events: Triggered by drag-and-drop actions.

o dragstart: Fires when the user starts dragging an element. Example:

javascript

CopyEdit

var draggable = document.getElementById('draggable');

draggable.addEventListener('dragstart', function() {

9. Write a JavaScript program that dynamically adds a list of items to an HTML page and
attaches a click event to each item using event delegation.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Dynamic List with Event Delegation</title>
<style>
#itemList {
list-style-type: none;
padding: 0;
}
#itemList li {
padding: 8px;
background-color: #f2f2f2;
margin-top: 5px;
cursor: pointer;
}
#itemList li:hover {
background-color: #e0e0e0;
}
</style>
</head>
<body>
<button id="addItemBtn">Add Item</button>
<ul id="itemList">
<!-- List items will be added here -->
</ul>

<script>
document.addEventListener('DOMContentLoaded', function() {
var itemList = document.getElementById('itemList');
var addItemBtn = document.getElementById('addItemBtn');
var itemCount = 0;

// Function to add a new item to the list


function addItem() {
itemCount++;
var newItem = document.createElement('li');
newItem.textContent = 'Item ' + itemCount;
itemList.appendChild(newItem);
}

// Attach click event listener to the "Add Item" button


addItemBtn.addEventListener('click', addItem);

// Attach event listener to the ul element for event delegation


itemList.addEventListener('click', function(event) {
// Check if the clicked element is an li
if (event.target && event.target.nodeName === 'LI') {
alert(event.target.textContent + ' clicked');
}
});
});
</script>
</body>
</html>
10. Create an object student with properties: name (string), grade (number), subjects
(array), displayInfo() (method to log the student's details) Write a script to
dynamically add a passed property to the student object, with a value of true or false
based on their grade. Create a loop to log all keys and values of the student object

// Step 1: Create the student object


const student = {
name: 'John Doe',
grade: 85,
subjects: ['Mathematics', 'Science', 'History'],
displayInfo: function() {
console.log(`Name: ${this.name}`);
console.log(`Grade: ${this.grade}`);
console.log(`Subjects: ${this.subjects.join(', ')}`);
}
};

// Step 2: Dynamically add the 'passed' property based on the grade


student.passed = student.grade >= 50;

// Step 3: Loop through the object to log all keys and values
for (const key in student) {
if (student.hasOwnProperty(key)) {
console.log(`${key}: ${student[key]}`);
}
}
11. Create a button in your HTML with the text "Click Me". Add an event listener to log
"Button clicked!" to the console when the button is clicked. Select an image and add
a mouseover event listener to change its sliding three different images.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Interactive Elements</title>
<style>
#slideshow {
width: 300px;
height: 200px;
}
</style>
</head>
<body>
<button id="clickMeBtn">Click Me</button>
<br><br>
<img id="slideshow" src="image1.jpg" alt="Slideshow Image">

<script src="script.js"></script>
</body>
</html>
12. Write a JavaScript program to select a
element with id="demo" and change its text content to "Hello, VTU Students!" when
a button is clicked.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Change Paragraph Text</title>
</head>
<body>
<p id="demo">Original text.</p>
<button id="changeTextBtn">Click Me</button>

<script>
// Select the button and paragraph elements
const changeTextBtn = document.getElementById('changeTextBtn');
const demoParagraph = document.getElementById('demo');
// Function to change the text content of the paragraph
function changeText() {
demoParagraph.textContent = 'Hello, VTU Students!';
}

// Attach event listener to the button


changeTextBtn.addEventListener('click', changeText);
</script>
</body>
</html>

13.Write a JavaScript function that changes the src attribute of an <img> element when a
button is clicked

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Change Image Source</title>

</head>

<body>

<!-- Image Element -->

<img id="myImage" src="image1.jpg" alt="Image" width="300">

<!-- Button to Change Image -->

<button id="changeImageButton">Change Image</button>

<script>

// JavaScript to change the image source

document.getElementById('changeImageButton').addEventListener('click', function() {

var imageElement = document.getElementById('myImage');

// Check the current src and toggle to the other image


if (imageElement.src.endsWith('image1.jpg')) {

imageElement.src = 'image2.jpg';

} else {

imageElement.src = 'image1.jpg';

});

</script>

</body>

</html>

14. Create a JavaScript program that adds a new

item to an existing

list when a button is clicked. Also, provide a button to remove the last item from the list.

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Dynamic List Manipulation</title>

</head>

<body>

<ul id="itemList">

<!-- List items will be added here -->

</ul>

<button id="addItem">Add Item</button>

<button id="removeItem">Remove Last Item</button>

<script src="script.js"></script>

</body>

</html>
15. Write a JavaScript program that listens for a double-click event on a
element and changes its background color to yellow.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Double-Click to Change Background</title>
<style>
#colorBox {
width: 200px;
height: 100px;
background-color: lightgray;
text-align: center;
line-height: 100px;
user-select: none; /* Prevent text selection */
}
</style>
</head>
<body>
<div id="colorBox">Double-click me!</div>

<script>
// JavaScript code will be added here
</script>
</body>
</html>
16. Create a JavaScript program where clicking on any list item inside a
dynamically changes its text color, without adding event listeners to each item
individually.

1. HTML Structure:
o Create a <ul> element containing multiple <li> items.
html
CopyEdit
<ul id="itemList">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
</ul>
2. JavaScript Functionality:
o Select the <ul> element using getElementById.
o Attach a single click event listener to the <ul>.
o Within the event handler, check if the clicked element is an <li>.
o If it is, change its text color.
javascript
CopyEdit
document.addEventListener('DOMContentLoaded', function() {
const itemList = document.getElementById('itemList');

itemList.addEventListener('click', function(event) {
// Check if the clicked element is an <li>
if (event.target && event.target.nodeName === 'LI') {
event.target.style.color = 'blue'; // Change text color to blue
}
});
});
Explanation:
• Event Delegation:
o By adding the event listener to the <ul> parent, you can manage events for all
current and future <li> children. This is efficient and simplifies code
maintenance.
• Event Handling:
o The event.target property identifies the specific element that was clicked. By
checking event.target.nodeName === 'LI', you ensure that the event handler
only responds when an <li> is clicked.
o The style.color property is then used to change the text color of the clicked
<li>.How To Code School
Considerations:
• Styling Reset:
o If you want only one <li> to have the changed color at a time, consider
resetting the color of all <li> elements before applying the new color:
javascript
CopyEdit
document.addEventListener('DOMContentLoaded', function() {
const itemList = document.getElementById('itemList');

itemList.addEventListener('click', function(event) {
if (event.target && event.target.nodeName === 'LI') {
// Reset color for all <li> elements
const items = itemList.getElementsByTagName('li');
for (let item of items) {
item.style.color = ''; // Reset to default color
}
// Set color for the clicked <li>
event.target.style.color = 'blue';
}
});
});
• CSS Classes:
o For more maintainable styling, consider adding and removing CSS classes
instead of directly manipulating inline styles. Define a CSS class for the
desired text color and toggle this class on the clicked <li>:
css
CopyEdit
.highlight {
color: blue;
}
javascript
CopyEdit
document.addEventListener('DOMContentLoaded', function() {
const itemList = document.getElementById('itemList');

itemList.addEventListener('click', function(event) {
if (event.target && event.target.nodeName === 'LI') {
// Remove 'highlight' class from all <li> elements
const items = itemList.getElementsByTagName('li');
for (let item of items) {
item.classList.remove('highlight');
}
// Add 'highlight' class to the clicked <li>
event.target.classList.add('highlight');
}
});
});

17. Write a JavaScript program that changes the text color of a

element when the mouse hovers over it and restores the original color when the mouse
moves away.

<!DOCTYPE html>

<html lang="en">
<head>

<meta charset="UTF-8">

<title>Hover to Change Text Color</title>

</head>

<body>

<p id="textParagraph">Hover over this text to change its color.</p>

<script>

// JavaScript code will be added here

</script>

</body>

</html>

18. Create a simple form with a text input and a submit button. Write a JavaScript function
that prevents form submission if the input field is empty and displays an error message.

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Form Validation</title>

<style>

.error-message {

color: red;

display: none;

</style>

</head>

<body>

<form id="myForm">
<label for="userInput">Enter something:</label>

<input type="text" id="userInput" name="userInput">

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

<p id="errorMessage" class="error-message">This field cannot be empty.</p>

</form>

<script>

// JavaScript code will be added here

</script>

</body>

</html>

19. Create a textarea where users can type text. Implement a JavaScript function that
displays the remaining characters (limit: 100) below the textarea.

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Textarea Character Counter</title>

<style>

#charCount {

font-size: 0.9em;

color: #555;

#charCount.warning {

color: red;

</style>

</head>
<body>

<label for="userInput">Type your text (max 100 characters):</label>

<textarea id="userInput" rows="4" cols="50" maxlength="100"></textarea>

<div id="charCount">100 characters remaining</div>

<script>

// JavaScript code will be added here

</script>

</body>

</html>

You might also like