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

MCA - Java Script - Unit 3 - The Document Object

Uploaded by

surajpawar0229
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 views28 pages

MCA - Java Script - Unit 3 - The Document Object

Uploaded by

surajpawar0229
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

Java Script

The Document
Object
SELF LEARNING MATERIAL

SEM - III (005)

MCA
UNIT-3 THE DOCUMENT OBJECT
TABLE OF CONTENTS

3.1 Introduction
3.2 The Document Object
3.2.1 Writing to Documents
3.3 Document Related Functions
3.4 Forms and Forms-Based Data
3.4.1 The Form Object
3.4.2 Working with Form Elements and their Properties
3.4.3 Event Related with Form
3.5 Let’s Sum Up
3.6 Case Study
3.7 Terminal Questions
3.8 Answers
3.9 Assignment
3.10 References

Learning Objectives
• To understand the document object.
• To explain the document related functions.
• To analyze the forms and forms-based data like the forms object, working with
form elements and their properties, and event related with form.
NOTES

3.1
Introduction
Understanding the Document Object Model (DOM) is critical in web
development because it provides an interface for scripts to dynamically
access and alter the information, structure, and style of HTML documents.
One of the most important aspects of DOM manipulation is the ability to
dynamically write to documents. Using JavaScript to generate, change, or
remove information within an HTML document, developers may construct
interactive and responsive web pages.

Document-related functions extend the possibilities of DOM manipulation.


These methods give developers the ability to navigate the DOM tree, access
individual components, change their properties, and execute different
actions on the document structure. Mastering these capabilities enables
developers to construct dynamic and interesting online experiences in
which information may be modified in real-time based on user interactions
or other events.

Forms are essential for gathering user input and communicating with them
on web pages. The Form Object incorporates HTML form behavior and
characteristics, allowing developers to interact with them programmatically.
Working with Form components and their attributes digs further into this

01
NOTES topic, examining the many attributes and techniques for controlling form
components like as input fields, buttons, checkboxes, and dropdowns.
Understanding these attributes is critical for verifying user input, adjusting
form behavior, and providing a pleasant user experience.

Furthermore, event-based interactions with forms offer an extra degree of


interactivity to online applications. Form submissions, input changes, and
button clicks are examples of events that activate actions or functions, allowing
developers to dynamically respond to user activity. Developers may utilize
event handling technologies to check form data, change form components,
display error warnings, and conduct other activities based on user input,
improving the usability and usefulness of online forms.

In summary, competency in DOM manipulation, document-related functions,


form objects, form element attributes, and form-related event handling
provides developers with the abilities to design dynamic, interactive, and user-
friendly online applications.

3.2
The Document Object
The page Object Model (DOM) visualizes the
structure of an HTML or XML page as a tree of STUDY NOTE
objects. The Document Object is at the center of The Document object
the DOM, acting as the tree’s root and providing is crucial in web
access to the document’s content and structure. development, present
Understanding the Document Object is vital in nearly all JavaScript-
for modifying web pages dynamically using based projects, with
JavaScript. over 98% of websites
using its functionalities
The Role of the Document Object
for accessing and
The Document Object is a Document interface manipulating HTML
object that may be accessed via JavaScript’s documents dynamically.
document global variable. This object has a variety
of attributes and methods that allow developers
to interact with and alter the components inside the HTML document.

Key Properties of the Document Object


● documentElement: Represents the root element of the document (usually
the <html> tag).
● body: Refers to the <body> element of the document, where most of the
visible content resides.
02
● head: Refers to the <head> element, which contains meta-information about
the document.
NOTES
● title: Gets or sets the title of the document as specified in the <title> tag.
● URL: Provides the URL of the document.
● forms: Returns a collection of all the forms present in the document.
● images: Returns a collection of all the images present in the document.
● links: Returns a collection of all the hyperlinks in the document.

Key Methods of the Document Object

Key Methods of the Document Object

getElementById(id)

getElementsByClassName(className)

getElementsByTagName(tagName)

querySelector(selector)

querySelectorAll(selector)

createElement(tagName)

createTextNode(text)

appendChild(node)

removeChild(node)

write(content)

Fig 1: Key Methods of the Document Object

● getElementById(id): Returns the element with the specified ID.


● getElementsByClassName(className): Returns a collection of elements with
the specified class name.
● getElementsByTagName(tagName): Returns a collection of elements with the
specified tag name.
● querySelector(selector): Returns the first element that matches the specified
CSS selector.
● querySelectorAll(selector): Returns a collection of all elements that match the
specified CSS selector.
● createElement(tagName): Creates an element with the specified tag name.
● createTextNode(text): Creates a text node with the specified text content.
● appendChild(node): Adds a node to the end of the list of children of a specified
parent node.
03
NOTES ● removeChild(node): Removes a specified child node from the document.
● write(content): Writes HTML or text to the document.

3.2.1. Writing to Documents:

The Document Object Model (DOM) in web development provides a key function
called “writing to documents,” which allows for dynamic content production and
manipulation within an HTML document. This method involves utilizing JavaScript
to insert, alter, or edit content on a web page, resulting in interactive and responsive
user experiences. There are various ways available for writing to documents, each
tailored to distinct contexts and requirements.

The [Link]() Method


The [Link]() function is the most straightforward way to add content
to a document. This approach inserts HTML or JavaScript code straight into the
document stream. It is frequently utilized at the first loading of the document to
generate dynamic content.

Syntax:
[Link](content);

Parameters:
● content: A string containing the HTML or text to be written to the document.
Example:
[Link](“<h1>Welcome to My Website</h1>”);
[Link](“<p>This content was written using document.
write().</p>”);

Considerations:
● Timing: The [Link]() function can only be used while the document is
still loading. If called after the document has finished loading, it will overwrite
the whole document and force it to be refreshed.
● Performance: Excessive usage of [Link]() might cause performance
concerns since it causes the browser to re-parse and redraw the page.
● Security: If sufficient sanitization is not done, directly publishing user-generated
text via [Link]() may expose the application to cross-site scripting
(XSS) attacks.

The innerHTML Property


The innerHTML attribute of an element is a more versatile and widely used
mechanism for adding content to pages after the first load. This attribute enables
developers to set or retrieve HTML content within an element.

Syntax:
[Link] = content;

Parameters:
● content: A string containing the HTML or text to be written inside the element.
04
Example:
NOTES
[Link](“content”).innerHTML = “<h2>Dynamic
Content</h2><p>This content was added using innerHTML.</p>”;

Advantages:
● Timing: innerHTML can be utilized at any moment after the document has
loaded, allowing for greater flexibility than [Link]().
● Targeted Updates: It allows you to update certain areas of the content without
changing the entire page.

Considerations:
● Performance: While typically efficient, frequent updates to big volumes of
material can have an influence on performance.
● Security: Same as with the [Link] prevent XSS attacks, it is necessary to
sanitize any user-generated information before using write().

The textContent and innerText Properties


● The textContent and innerText features are useful for writing plain text into
documents. These attributes set or retrieve an element’s text content, without
interpreting it as HTML.
Syntax:
[Link] = text;

Parameters:
● text: A string containing the text to be written inside the element.
Example:
[Link](“message”).textContent = “This is
plain text content.”;

Advantages:
● Security: Because these characteristics do not parse HTML elements, they
automatically prevent XSS attacks by treating information as plain text.
● Performance: TextContent updates are often quicker and more efficient than
simple text changes.

Appending and Inserting Content


AppendChild(), insertBefore(), and createElement() let developers to dynamically
insert or add material without overwriting existing content. These technologies
provide for better control over the placement and organization of new information.

Example:
let newParagraph = [Link](“p”);
[Link] = “This paragraph was created and
appended using createElement and appendChild.”;
[Link](newParagraph);

05
NOTES Writing to documents is an essential component of web development, allowing for
the construction of dynamic, interactive web pages. Developers may successfully
modify and update web page content by learning and using methods such as
[Link](), innerHTML, textContent, and DOM manipulation techniques.
Each technique has its use cases, benefits, and concerns, thus it is crucial to pick
the proper strategy depending on the individual requirements and context of the
web application.

CHECK YOUR PROGRESS


1. Using innerHTML to update the content of an element can pose a risk of
________ injection.
2. The createElement() method is used to dynamically create ________ elements
in the DOM.
3. The [Link]() method should be preferred for dynamically updating
HTML content.  [True/False]

Activity
Students will analyse the structure of a webpage using the Document Object
Model (DOM) Inspector tool in web browsers. Students will inspect various
elements, noting their hierarchical relationships and properties. Then, they’ll
identify opportunities for dynamic content manipulation using JavaScript.
Finally, students will propose enhancements to the webpage’s interactivity
by suggesting specific DOM manipulation techniques, such as creating new
elements or modifying existing ones, based on their analysis.

3.3
Document Related Functions
Document-related methods in the Document
Object Model (DOM) give developers STUDY NOTE
comprehensive capabilities for interacting JavaScript’s document-
with and manipulating HTML documents. related functions are
These capabilities allow for activities like extensively used, with over
locating items, updating material, and 95% of web developers
responding to user inputs, which improves incorporating methods
the dynamic and interactive aspect of web like getElementById() and
sites. Understanding these capabilities is querySelector() to access and
critical for successful DOM manipulation modify document elements
and web development. dynamically in their projects.
06
Key Document Related Functions:
NOTES
getElementById(id)

getElementsByClassName(className)

getElementsByTagName(tagName)
Document related functions

querySelector(selector)

querySelectorAll(selector)

createElement(tagName)

createTextNode(data)

appendChild(node)

removeChild(node)

replaceChild(newNode, oldNode)

cloneNode(deep)

Fig 2: Document related functions

1. getElementById(id):
● Description: Retrieves the element with the specified ID.
● Syntax: [Link](id)
● Parameters: id (string) - The ID of the element to retrieve.
● Returns: The element object with the specified ID, or null if no such element
exists.
Example
let element = [Link](“header”);
[Link] = “blue”;
2. getElementsByClassName(className):
● Description: Returns a collection of elements with the specified class name.
● Syntax: [Link](className)
● Parameters: className (string) - The class name of the elements to retrieve.
● Returns: A live HTMLCollection of elements with the specified class name.
Example:
let items = [Link](“menu-item”);
for (let i = 0; i < [Link]; i++) {
items[i].[Link] = “yellow”;
}
07
NOTES 3. getElementsByTagName(tagName):
● Description: Returns a collection of elements with the specified tag name.
● Syntax: [Link](tagName)
● Parameters: tagName (string) - The name of the tag of the elements to
retrieve.
● Returns: A live HTMLCollection of elements with the specified tag name.
Example:
let paragraphs = [Link](“p”);
for (let i = 0; i < [Link]; i++) {
paragraphs[i].[Link] = “18px”;
}
4. querySelector(selector)
● Description: Returns the first element that matches a specified CSS selector.
● Syntax: [Link](selector)
● Parameters: selector (string) - A CSS selector string.
● Returns: The first element that matches the selector, or null if no matches
are found.
Example:
let firstItem = [Link](“.list-item”);
[Link] = “bold”;
5. querySelectorAll(selector):
● Description: Returns a static NodeList of all elements that match a specified
CSS selector.
● Syntax: [Link](selector)
● Parameters: selector (string) - A CSS selector string.
● Returns: A static NodeList of all matching elements.
Example:
let allItems = [Link](“.list-item”);
[Link](item => {
[Link] = “red”;
});
6. createElement(tagName):
● Description: Creates a new element with the specified tag name.
● Syntax: [Link](tagName)
● Parameters: tagName (string) - The name of the tag for the new element.
● Returns: The newly created element.
Example:
let newDiv = [Link](“div”);
[Link] = “Hello, World!”;
[Link](newDiv);
08
7. createTextNode(data):
NOTES
● Description: Creates a new text node with the specified text content.
● Syntax: [Link](data)
● Parameters: data (string) - The text content for the new text node.
● Returns: The newly created text node.
Example:
let newText = [Link](“This is a text node.”);
[Link](“textContainer”).appendChild(newText);
8. appendChild(node):
● Description: Adds a node to the end of the list of children of a specified
parent node.
● Syntax: [Link](node)
● Parameters: node (Node) - The node to append.
● Returns: The appended node.
Example:
let newItem = [Link](“li”);
[Link] = “New List Item”;
[Link](“myList”).appendChild(newItem);
9. removeChild(node):
● Description: Removes a specified child node from the document.
● Syntax: [Link](node)
● Parameters: node (Node) - The node to remove.
● Returns: The removed node.
Example:
let itemToRemove = [Link](“item”);
[Link](itemToRemove);
10. replaceChild(newNode, oldNode):
● Description: Replaces a child node within the document with another node.
● Syntax: [Link](newNode, oldNode)
● Parameters:
● newNode (Node) - The new node to insert.
● oldNode (Node) - The node to be replaced.
● Returns: The replaced node.
Example:
let oldItem = [Link](“oldItem”);
let newItem = [Link](“li”);
[Link] = “Replaced Item”;
[Link](newItem, oldItem);
11. cloneNode(deep):
● Description: Creates a duplicate of the node on which this method was
called.
● Syntax: [Link](deep)
09
NOTES ● Parameters: deep (boolean) - If true, all child nodes and descendants will be
cloned. If false, only the node itself is cloned.
● Returns: The cloned node.
Example:
let listItem = [Link](“item”);
let clonedItem = [Link](true);
[Link](“myList”).appendChild
(clonedItem);

Document-related functions are essential for modifying the DOM and developing
dynamic web applications. These capabilities enable developers to easily access,
edit, and manage components inside an HTML document. Using these technologies,
developers may improve the interactivity and responsiveness of their web pages,
resulting in a better user experience.

CHECK YOUR PROGRESS


4. The querySelector() method returns the first ________ element that matches
a specified CSS selector.
5. The getElementsByClassName() method returns a collection of all elements
with a specific ________.
6. getElementsByClassName() returns a live HTMLCollection, meaning it
updates automatically when the document is changed.  [True/False]

Activity
Students will conduct research on the performance differences between
various document-related functions in JavaScript, such as getElementById(),
querySelector(), and getElementsByClassName(). Students will analyze
factors like browser compatibility, execution speed, and memory usage using
benchmarking tools or performance profiling techniques. Based on their
findings, students will create a comparative report highlighting the strengths and
weaknesses of each function and recommending best practices for optimizing
document-related operations in web development.

3.4
Forms and Forms-based Data
Forms are an essential component of online applications, allowing users to enter
data that may then be transmitted to a server for processing. Understanding how
to use forms and form-based data is critical for developing dynamic and user-
10
friendly online apps. This section discusses many
features of forms, including as the form object, STUDY NOTE
NOTES
form elements and their attributes, and form- Approximately 70% of
related event processing. websites incorporate
JavaScript’s Form
3.4.1. The Form Object:
object methods like
The Form Object offers attributes and methods for submit() and reset() to
working with the <form> element in an HTML page. dynamically manipulate
Each form element in the DOM is represented as form elements,
an instance of the HTMLFormElement interface, improving user
which is descended from the HTMLElement interaction and data
interface. handling efficiency.

Key Properties of the Form Object:


● action: The URL to which the form data will be sent when the form is submitted.
● method: The HTTP method to be used when submitting the form (GET or
POST).
● elements: A collection of all form controls contained in the form.
● name: The name of the form.
● target: The target window or frame where the form results will be displayed.
Example:
<form id=”myForm” action=”/submit” method=”post” target=”_
self”>
<input type=”text” name=”username”>
<input type=”password” name=”password”>
<input type=”submit” value=”Login”>
</form>

JavaScript Example:
let form = [Link](“myForm”);
[Link]([Link]); // Outputs: /submit
[Link]([Link]); // Outputs: post
[Link]([Link]); // Outputs:
HTMLFormControlsCollection(3) [input, input, input]

3.4.2. Working with Form Elements and their Properties:

Form components contain input fields, text areas, checkboxes, radio buttons,
select boxes, and buttons. Each type of form element has unique characteristics
and methods that may be used to improve functionality and user interaction.

Common Form Elements and Their Properties:


● Input Elements (<input>)
{ type: Specifies the type of input element (e.g., text, password, checkbox,
radio, submit, etc.).
11
NOTES Input Elements (<input>)

Textarea Elements (<textarea>)

Select Elements (<select>)

Button Elements (<button>)

Fig 3: Common Form Elements

{ value: The current value of the input element.


{ name: The name of the input element, used to identify the data when the
form is submitted.
{ checked: For checkbox and radio inputs, indicates whether the element is
checked.
Example:
<input type=”text” id=”username” name=”username”
value=”JohnDoe”>
<input type=”checkbox” id=”subscribe” name=”subscribe”
checked>
JavaScript Example:
let username = [Link](“username”).value;
let subscribe = [Link](“subscribe”).
checked;
[Link](username); // Outputs: JohnDoe
[Link](subscribe); // Outputs: true
● Textarea Elements (<textarea>)
{ value: The text contained within the textarea.
{ rows and cols: Define the visible number of lines and the width of the
textarea.
Example:
<textarea id=”comments” name=”comments” rows=”4”
cols=”50”>Enter your comments here...</textarea>
JavaScript Example:
let comments = [Link](“comments”).value;
[Link](comments); // Outputs: Enter your comments
here...
● Select Elements (<select>)
{ value: The value of the selected option.
{ options: A collection of all the option elements contained within the select
element.
12
{ selectedIndex: The index of the currently selected option.
NOTES
Example:
<select id=”country” name=”country”>
<option value=”USA”>United States</option>
<option value=”CAN”>Canada</option>
<option value=”MEX”>Mexico</option>
</select>

JavaScript Example:
let country = [Link](“country”).value;
[Link](country); // Outputs: USA
1. Button Elements (<button>, <input type=”button”>, <input
type=”submit”>)
{ type: Specifies the type of button (button, submit, reset).
{ value: The text or label displayed on the button.
Example:
<button id=”submitBtn” type=”submit”>Submit</button>

JavaScript Example:
let submitBtn = [Link](“submitBtn”).value;
[Link](submitBtn); // Outputs: Submit

3.4.3. Event related with form:

Event handling is essential for developing interactive and responsive forms. Form-
related events include submit, modify, input, and focus.

Common Form Events:


● submit: Triggered when a form is submitted. This event can be used to perform
validation or prevent the default form submission.
Example:
<form id=”loginForm”>
<input type=”text” name=”username”>
<input type=”password” name=”password”>
<input type=”submit” value=”Login”>
</form>
● change: Triggered when the value of an input, select, or textarea element is
changed.
Example:
<input type=”text” id=”username” name=”username”>
[Link](“username”).
addEventListener(“change”, function() {
[Link](“Username changed to: “ + [Link]);
});
13
NOTES ● input: Triggered every time the value of an input or textarea changes.
Example:
<input type=”text” id=”username” name=”username”>
[Link](“username”).addEventListener
(“input”, function() {
[Link](“Current username: “ + [Link]);
});
● focus and blur: Triggered when an element gains or loses focus, respectively.
Example:
<input type=”text” id=”username” name=”username”>
[Link](“username”).addEventListener
(“focus”, function() {
[Link](“Username input focused”);
});
[Link](“username”).addEventListener(“blur”,
function() {
[Link](“Username input lost focus”);
});

Forms are essential components of online applications, allowing users to interact


and gather data. Developers may construct dynamic, interactive, and user-friendly
forms by knowing the form object, form components and their characteristics, as
well as form event management. Mastery of these ideas ensures that forms not
only perform properly but also deliver a consistent user experience.

CHECK YOUR PROGRESS


7. The required attribute in form elements specifies that the input must be
________ before submitting the form.
8. The autofocus attribute in form elements automatically focuses on the input
when the ________ loads.
9. The form attribute of an input element specifies the action to be performed
when the form is submitted.  [True/False]

Activity
Students will conduct a comparative analysis of event handling techniques in
JavaScript forms, focusing on traditional event listeners versus modern event
delegation. Students will research and experiment with both approaches,
observing factors such as code readability, performance, and scalability. Through
hands-on exercises and case studies, students will evaluate the effectiveness
of each technique in handling various form-related events like input validation,
submission handling, and dynamic form updates. Finally, they will present
their findings, discussing the advantages and limitations of each approach and
recommending best practices for event handling in JavaScript forms.
14
3.5 NOTES
Let’s Sum Up
● Represents the entire HTML or XML document as a tree of objects accessible
via the DOM.
● Involves dynamically generating or modifying content within an HTML document
using JavaScript.
● Directly writes HTML or JavaScript code to the document stream, typically
used during initial page load.
● Allows setting or retrieving HTML content inside an element, useful for dynamic
content updates.
● Sets or retrieves the text content of an element, treating it as plain text without
interpreting HTML.
● Adds a node to the end of the list of children of a specified parent node.
● Retrieves the element with the specified ID, providing a way to access specific
elements.
● Returns a collection of elements with the specified class name.
● Returns a collection of elements with the specified tag name.
● Returns the first element that matches a specified CSS selector.
● Returns a static NodeList of all elements matching a specified CSS selector.
● Creates a new element with the specified tag name, useful for adding new
elements to the DOM.
● Creates a new text node with specified text content.
● Removes a specified child node from the document.
● Replaces a child node within the document with another node.
● Represents an HTML form element, providing properties and methods to
interact with it.
● Includes various input fields, text areas, checkboxes, radio buttons, and buttons,
each with specific properties.
● Key properties include type, value, name, checked, and more, varying by
element type.
● Common events like submit, change, input, focus, and blur facilitate interaction
and validation.
● Enables dynamic responses to user input, enhancing interactivity and user
experience.

15
NOTES
3.6
Case Study
Infosys’s Integration of JavaScript for Improved User Experience
Wipro, a leading global information technology, consulting, and business process
services company, decided to upgrade their internal web application used for
employee management. The application, built several years ago, lacked modern
features for dynamic content and responsive user interaction, resulting in a
subpar user experience. This case study explores how Wipro leveraged advanced
DOM manipulation techniques and forms-based data handling to resolve these
issues.

Wipro’s employee management system faced several challenges. Firstly, the


application relied heavily on server-side rendering, resulting in static content that
required full-page reloads for updates. Secondly, forms were cumbersome, with
limited client-side validation, leading to frequent errors and incomplete submissions.
Thirdly, the lack of dynamic updates and real-time feedback diminished the user
experience, making the system less efficient and harder to use.

Wipro’s development team identified key areas for improvement, focusing on


utilizing modern JavaScript techniques for DOM manipulation and enhancing form
functionalities. They implemented innerHTML and textContent to enable dynamic
content updates. For instance, updating employee details in real-time without
requiring full-page reloads improved the responsiveness of the application.

For example, the line [Link](“employeeName”).innerHTML


= “John Doe”; dynamically updated the employee name displayed on the page.
The team also revamped the forms using the HTMLFormElement properties and
methods. They added client-side validation using addEventListener for input and
change events, reducing errors and improving data integrity. For instance, they
prevented form submission if validation failed by using [Link]() in the
submit event listener. This ensured that only valid data was submitted, enhancing
the overall integrity of the data collected.

Furthermore, by utilizing event handling for form elements, Wipro’s developers


created a more interactive user experience. Real-time validation feedback and
dynamic field updates ensured users were promptly informed of errors or changes.
For example, when a department was selected from a dropdown menu, the selected
department was displayed in real-time, enhancing user interaction and satisfaction.

The upgraded application demonstrated significant improvements. Employees


could now manage data faster due to dynamic content updates and real-time form
validation. The interactive elements and immediate feedback reduced frustration
and errors, leading to higher user satisfaction. Additionally, improved form handling
and validation ensured higher quality data submission, enhancing data integrity.
16
Questions:
NOTES
1. How did the implementation of innerHTML and textContent improve the
responsiveness of Wipro’s web application?
2. What specific benefits did Wipro gain from adding client-side form validation
using addEventListener for input and change events?

3.7
Terminal Questions
SHORT ANSWER QUESTIONS
1. How does the Document Object Model (DOM) represent the structure of an
HTML document, and why is this representation crucial for web development?
2. In what situations would using [Link]() be considered a poor practice,
and what alternatives can provide better solutions?
3. Why might textContent be a safer alternative to innerHTML in certain scenarios.

LONG ANSWER QUESTIONS


1. Provide a detailed analysis of how createElement() and appendChild() can be
used to build complex, dynamic user interfaces. Include examples demonstrating
both simple and advanced use cases.
2. Examine the significance of the Form Object in enhancing form functionality.
Discuss how its properties and methods can be used to create interactive,
user-friendly forms.
3. Discuss the importance of client-side form validation in maintaining data
integrity and enhancing user experience. Provide examples of common
validation techniques and their implementation.

MCQ QUESTIONS
1. Which of the following accurately describes the Document Object Model
(DOM)?
a) It represents the logical structure of documents and the way a document
is accessed and manipulated
b) It is a programming interface for HTML documents that enables scripting
languages to interact with the structure of the web page
c) It provides methods and properties to dynamically modify the content and
structure of web documents
d) All of the above

17
NOTES 2. What is the primary purpose of the `[Link]()` method in JavaScript?
a) To append new elements to the document
b) To directly write HTML or text to the document stream
c) To create a new document object
d) To modify existing elements in the document
3. Which of the following methods is commonly used to update the content of an
element without the risk of script injection?
a) `innerHTML`
b) `textContent`
c) `createElement()`
d) `appendChild()`
4. How does the `appendChild()` method differ from the `innerHTML` property in
terms of updating the DOM?
a) `appendChild()` adds a new child node to the end of the specified parent
node, while `innerHTML` replaces the content of the parent node.
b) `appendChild()` replaces the content of the parent node, while `innerHTML`
adds a new child node to the end of the specified parent node.
c) Both methods add new child nodes to the specified parent node in the
same manner.
d) `appendChild()` removes the parent node from the DOM, while `innerHTML`
retains it.
5. Which method is used to retrieve an element by its unique ID from an HTML
document?
a) `getElementById()`
b) `getElementsByClassName()`
c) `getElementsByTagName()`
d) `querySelector()`
6. How does `querySelectorAll()` differ from `getElementsByClassName()`?
a) `querySelectorAll()` returns a collection of elements that match a CSS
selector, while `getElementsByClassName()` returns elements with a
specific class name.
b) `querySelectorAll()` returns a single element that matches a CSS selector,
while `getElementsByClassName()` returns a collection of elements.
c) `querySelectorAll()` returns elements with a specific class name, while
`getElementsByClassName()` returns elements that match a CSS selector.
d) `querySelectorAll()` and `getElementsByClassName()` are functionally
equivalent.
7. Which method is used to dynamically create a new element in the DOM?
a) `createElement()`
b) `appendChild()`
c) `insertBefore()`
d) `removeChild()`
18
8. How can the `innerHTML` property be vulnerable to security risks?
NOTES
a) It can execute JavaScript code directly, leading to script injection attacks.
b) It can expose sensitive data to malicious scripts.
c) It can modify the structure of the DOM unpredictably.
d) It can cause performance issues due to excessive DOM manipulation.
9. Which of the following events is commonly used for form validation and
submission in web applications?
a) `change`
b) `input`
c) `submit`
d) `click`
10. What is the primary purpose of the `addEventListener()` method in the context
of form handling?
a) To create new form elements dynamically
b) To attach event listeners to form elements for responding to user actions
c) To validate form input before submission
d) To remove event listeners from form elements

3.8
Answers
CHECK YOUR PROGRESS
1. Script 6. True
2. HTML 7. Completed
3. False 8. Page
4. HTML 9. False
5. Class name

SHORT ANSWER QUESTIONS


1. The Document Object Model (DOM) is a programming interface that represents
the structure of an HTML document as a hierarchical tree of objects. Each
element in an HTML document, such as <html>, <head>, <body>, and <p>, is
represented as a node in this tree, with parent-child relationships defining the
document’s structure. The DOM provides methods and properties to access,
traverse, and manipulate these nodes dynamically using scripting languages
like JavaScript.
This representation is crucial for web development because it allows developers
to interact with the content and structure of web pages programmatically.
By accessing and modifying DOM elements, developers can dynamically
19
NOTES update page content, respond to user interactions, and create interactive web
applications. Without the DOM, web development would be limited to static
HTML documents, lacking the dynamic and interactive features that modern
users expect.
2. Using [Link]() can be considered a poor practice in modern web
development for several reasons. Firstly, it directly writes HTML or text to the
document stream, which can cause unexpected results if called after the page
has loaded, such as overwriting the entire document. This makes it difficult
to maintain the document’s structure and can lead to errors or unexpected
behavior.
Additionally, [Link]() does not provide a way to interact with the DOM
or modify existing page content dynamically, limiting its usefulness in creating
dynamic web applications. Instead of using [Link](), developers can
use alternative methods like innerHTML, textContent, or DOM manipulation
methods (createElement(), appendChild(), etc.) to dynamically update page
content without disrupting the document’s structure.
3. textContent is often considered a safer alternative to innerHTML in certain
scenarios due to its handling of HTML content as plain text. Unlike innerHTML,
which interprets HTML content and can execute scripts, textContent treats
the content as text without parsing or executing any HTML or scripts. This
makes it less susceptible to cross-site scripting (XSS) attacks, where malicious
scripts are injected into a web page through user input. By using textContent
to update content, developers can mitigate the risk of XSS vulnerabilities and
ensure the security of their web applications.
Additionally, textContent is more efficient than innerHTML for updating large
blocks of text or content that does not contain HTML markup, as it avoids the
overhead of parsing and rendering HTML elements. However, it’s important to
note that textContent is limited to text content and cannot be used to create
or modify HTML elements. In scenarios where HTML markup is necessary,
developers should use innerHTML with caution and implement proper input
validation and sanitization to prevent security vulnerabilities.

LONG ANSWER QUESTIONS


1. The createElement() and appendChild() methods are pivotal in creating dynamic
user interfaces in web development. With createElement(), developers can
generate DOM elements programmatically, while appendChild() facilitates
their insertion into the DOM tree. These methods offer significant flexibility
in constructing intricate and interactive user interfaces on-the-fly. In simpler
scenarios, createElement() is used to create basic HTML elements like <div>,
<p>, <span>, or <button>. For instance, createElement(‘p’) generates a new
paragraph element.
In more complex cases, both methods work in tandem to build entire sections
of a webpage dynamically. This advanced usage involves creating and appending
multiple elements, setting attributes, attaching event listeners, and organizing
elements within the DOM hierarchy. By combining createElement() and
appendChild(), developers can construct interfaces that dynamically respond to

20
user actions or data changes, essential for modern web applications with rich
and interactive user experiences.
NOTES
2. The Form Object in JavaScript serves as a powerful tool for manipulating HTML
forms and their elements, offering properties and methods to enhance form
functionality, validate user input, and create user-friendly interactions. One
crucial property is elements, representing a collection of all form elements
within a form, enabling developers to access and manipulate individual elements
programmatically.
This allows for dynamic interactions, such as iterating through the elements
collection to retrieve user input or customize form behavior based on selections.
Additionally, methods like submit() and reset() enable programmatic control
over form submission and resetting fields, respectively.
Furthermore, the Form Object supports event handling for form elements,
facilitating responses to user actions like input changes or form submissions.
By leveraging the Form Object, developers can create interactive, user-friendly
forms that enhance the overall user experience.
3. Client-side form validation plays a vital role in ensuring data integrity and
improving user experience in web applications. By validating user input before
submission, it reduces the likelihood of invalid or malicious data being sent to
the server, thereby enhancing data quality and integrity.
Common techniques include using the required attribute to mandate fields and
specifying input formats using attributes like pattern or JavaScript validation
functions. This immediate feedback to users allows for error correction before
submission, reducing frustration and streamlining the process.
Ultimately, client-side validation not only maintains data integrity but also
enhances the user experience by providing real-time feedback and preventing
unnecessary form submissions, thus contributing to the overall usability and
efficiency of web applications.

MCQ Answers
1. d) All of the above
2. b) To directly write HTML or text to the document stream
3. b) `textContent`
4. a) `appendChild()` adds a new child node to the end of the specified parent
node, while `innerHTML` replaces the content of the parent node.
5. a) `getElementById()`
6. a) `querySelectorAll()` returns a collection of elements that match a CSS
selector, while `getElementsByClassName()` returns elements with a
specific class name.
7. a) `createElement()`
8. a) It can execute JavaScript code directly, leading to script injection attacks.
9. c) `submit`
10. b) To attach event listeners to form elements for responding to user actions

21
NOTES
3.9
Assignment
MULTIPLE CHOICE QUESTIONS
1. Which property of the Form Object represents the URL to which the form data
will be sent when submitted?
a) `action` b) `method`
c) `elements` d) `target`
2. How does client-side form validation contribute to a better user experience?
a) By reducing server load and speeding up form submission
b) By providing immediate feedback to users and preventing invalid data
submission
c) By simplifying the form layout and improving accessibility
d) By encrypting form data to ensure security
3. Which method is commonly used to dynamically add event listeners to form
elements?
a) `addEventListener()`
b) `removeEventListener()`
c) `setAttribute()`
d) `dispatchEvent()`
4. How can event delegation be used to handle events efficiently in dynamically
generated form elements?
a) By attaching event listeners to each individual form element
b) By using a single event listener on a parent element to handle events for
multiple child elements
c) By delegating event handling to the browser’s default event handler
d) By preventing event bubbling in the DOM hierarchy
5. What is the significance of the `createTextNode()` method in DOM manipulation?
a) It creates a new text node containing the specified text content, which can
be appended to elements in the DOM.
b) It creates a new HTML element with the specified tag name and attributes.
c) It retrieves the text content of an existing element in the DOM.
d) It converts HTML text into plain text for security purposes.
6. Which of the following statements about forms in HTML is true?
a) Forms can only contain input elements.
b) Forms can be nested within other forms.
c) Forms cannot be submitted using the GET method.
d) Forms can only be submitted using JavaScript.
22
7. How does the `reset()` method of the Form Object affect form elements?
NOTES
a) It clears the form of all input data and resets it to its default state.
b) It submits the form data to the server for processing.
c) It disables all form elements to prevent user input.
d) It validates the form input before submission.
8. Which event is triggered when a user interacts with a form element by typing,
clicking, or selecting an option?
a) `change` b) `input`
c) `submit` d) `focus`
9. How can the `target` attribute of the Form Object be used to specify where the
form submission response should be displayed?
a) By setting it to `_blank` to open the response in a new browser tab
b) By setting it to the ID of an iframe element to load the response within the
iframe
c) By setting it to `_parent` to load the response in the parent frame or window
d) By setting it to `_self` to load the response in the same window or frame
10. Which method is used to remove a specific child node from the DOM?
a) `removeChild()`
b) `appendChild()`
c) `createElement()`
d) `replaceChild()`
11. What is the purpose of the `disabled` attribute in form elements?
a) To prevent user input and interaction with the element
b) To specify a default value for the element
c) To hide the element from the user interface
d) To apply styling to the element
12. How does the `selectedIndex` property of a select element differ from the
`value` property?
a) `selectedIndex` returns the index of the selected option, while `value`
returns the value of the selected option.
b) `selectedIndex` returns the value of the selected option, while `value`
returns the index of the selected option.
c) `selectedIndex` returns the text content of the selected option, while
`value` returns the index of the selected option.
d) `selectedIndex` returns the index of the selected option, while `value`
returns the text content of the selected option.
13. What is the purpose of the `method` attribute in an HTML form element?
a) To specify the scripting language used for form validation
b) To define the HTTP method used to submit form data to the server
c) To set the target URL where form data will be sent
d) To determine the encryption method used for securing form data
transmission
23
NOTES 14. Which of the following is NOT a valid event related to form elements?
a) `select` b) `blur`
c) `input` d) `change`
15. How can the `placeholder` attribute be used to enhance user interaction with
form elements?
a) By providing a default value for the element when it is empty
b) By displaying a message that describes the expected input in the element
c) By disabling user input for the element until a certain condition is met
d) By styling the element with a distinctive visual appearance
16. What is the purpose of the `required` attribute in form elements?
a) To specify that the element must be completed by the user before the
form can be submitted
b) To define the default value for the element if no user input is provided
c) To indicate that the element is optional and can be left empty
d) To enforce a specific format for the user input in the element
17. How can the `autofocus` attribute improve the usability of form elements?
a) By automatically submitting the form when the element gains focus
b) By highlighting the element when it is activated by the user
c) By automatically focusing on the element when the page loads
d) By displaying a tooltip with additional information about the element
18. What is the purpose of the `form` attribute in input elements?
a) To specify the scripting language used for form validation
b) To define the default value for the element if no user input is provided
c) To associate the input element with a specific form element elsewhere in
the document
d) To determine the encryption method used for securing form data
transmission
19. How does the `pattern` attribute enhance the validation of input elements?
a) By specifying a regular expression that defines the acceptable format for
user input
b) By restricting the range of valid values for the element to a predefined set
c) By automatically correcting common input errors made by the user
d) By providing a list of suggested values for the user to choose from
20. What role does the `form` attribute play in the accessibility of input elements?
a) It ensures that the input element is visible and interactive to all users
b) It associates the input element with a specific form element elsewhere in
the document, improving navigation for assistive technologies
c) It restricts the input element to a specific range of valid values, preventing
user errors
d) It provides additional styling options for the input element, making it more
visually appealing

24
QUESTIONS
NOTES
1. Describe a scenario where dynamically creating elements with createElement()
and appending them using appendChild() is necessary.
2. How can the properties of the Form Object, such as elements and action, be
used to dynamically alter form behavior?
3. What security concerns should be considered when manipulating the DOM
with innerHTML and how can they be mitigated?
4. How can event delegation improve the efficiency of event handling for dynamic
form elements?
5. Explain how querySelector() and querySelectorAll() can be utilized for selecting
elements more efficiently in complex web pages.

3.10
References
Books:
● [Link]
88icC?hl=en&gbpv=1&dq=javascript&printsec=frontcover
● [Link]
Guide/2weL0iAfrEMC?hl=en&gbpv=1&dq=javascript&printsec=frontcover
● h tt p s : / / w w w. g o o g l e . c o . i n / b o o k s / e d i t i o n / H ow _ Java S c r i p t _ Wo r k s /
rwiJDwAAQBAJ?hl=en&gbpv=1&dq=javascript&printsec=frontcover
● [Link]
Backend/qOV5EAAAQBAJ?hl=en&gbpv=1&dq=javascript&printsec=frontcover
● h tt p s : / / w w w. g o o g l e . c o . i n / b o o k s / e d i t i o n / Java S c r i p t _ by _ E x a m p l e /
zyMUnspbsekC?hl=en&gbpv=1&dq=javascript&printsec=frontcover

Webpages:
● [Link]
● [Link]
Java%20documentation%20can%20be%20generated,option%20in%20
command%20line%20arguments.
● [Link]

25

You might also like