Fs Module2
Fs Module2
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.
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>
o JavaScript can modify elements, change text, and update styles dynamically.
o Example:
javascript
CopyEdit
2. Event Handling
o Example:
javascript
CopyEdit
document.getElementById("btn").addEventListener("click", function() {
alert("Button clicked!");
});
3. CSS Manipulation
o Example:
javascript
CopyEdit
document.getElementById("box").style.backgroundColor = "blue";
o Example:
javascript
CopyEdit
o Example:
javascript
CopyEdit
document.body.appendChild(newElement);
o Used in frameworks like React, Angular, and Vue.js for efficient UI updates.
1. getElementById()
• Syntax: document.getElementById('idName')
Example:
html
CopyEdit
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>getElementById Example</title>
</head>
<body>
<script>
</body>
</html>
Key Points:
2. getElementsByClassName()
• Syntax: document.getElementsByClassName('className')
Example:
html
CopyEdit
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>getElementsByClassName Example</title>
</head>
<body>
<script>
</script>
</body>
</html>
Key Points:
• Returns a live collection; changes in the DOM are reflected in the collection.
Treehouse+2Stack Overflow+2Medium+2
• 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')
Example:
html
CopyEdit
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>querySelector Example</title>
</head>
<body>
</script>
</body>
</html>
Key Points:
• Uses CSS selectors; for classes, include the dot (.) prefix.
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">
</head>
<body>
<script>
</script>
</body>
</html>
4. What are the different types of DOM nodes? Explain with examples.
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:
html
CopyEdit
<div>
<p>Hello, World!</p>
</div>
In this example:
• 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:
• 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
<p>Visible text</p>
• 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
javascript
CopyEdit
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
5.Discuss event delegation in JavaScript. Why is it useful? Explain different ways to select
elements in the DOM. Provide examples using JavaScript.
javascript
CopyEdit
document.getElementById('parent').addEventListener('click', function(event) {
});
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.
javascript
CopyEdit
javascript
CopyEdit
javascript
CopyEdit
4. querySelector(): Selects the first element that matches a specified CSS selector.
javascript
CopyEdit
javascript
CopyEdit
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:
javascript
CopyEdit
o Direct Property Assignment: For certain standard attributes, you can set
them directly as properties of the element.
javascript
CopyEdit
Note: Direct assignment is generally more efficient and is recommended for standard
attributes.
2. Removing Attributes:
javascript
CopyEdit
javascript
CopyEdit
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">
</head>
<body>
<script>
// Remove attributes
element.removeAttribute('class'); // Removes the 'class' attribute
</script>
</body>
</html>
Key Points:
• 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;
}
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
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() {
});
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.
javascript
CopyEdit
inputField.addEventListener('focus', function() {
});
javascript
CopyEdit
inputField.addEventListener('blur', function() {
});
o click: Fires when a pointing device button (such as a mouse's primary button)
is clicked. Example:
javascript
CopyEdit
button.addEventListener('click', function() {
console.log('Button clicked');
});
javascript
CopyEdit
document.addEventListener('keydown', function(event) {
});
javascript
CopyEdit
form.addEventListener('submit', function(event) {
console.log('Form submitted');
});
javascript
CopyEdit
document.addEventListener('copy', function() {
console.log('Content copied');
});
javascript
CopyEdit
video.addEventListener('play', function() {
});
javascript
CopyEdit
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;
// 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!';
}
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">
</head>
<body>
<script>
document.getElementById('changeImageButton').addEventListener('click', function() {
imageElement.src = 'image2.jpg';
} else {
imageElement.src = 'image1.jpg';
});
</script>
</body>
</html>
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">
</head>
<body>
<ul id="itemList">
</ul>
<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');
}
});
});
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">
</head>
<body>
<script>
</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>
<button type="submit">Submit</button>
</form>
<script>
</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">
<style>
#charCount {
font-size: 0.9em;
color: #555;
#charCount.warning {
color: red;
</style>
</head>
<body>
<script>
</script>
</body>
</html>