[go: up one dir, main page]

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

Chapter 6

The document provides an overview of the Document Object Model (DOM) in JavaScript, explaining its tree-like structure and how it allows for dynamic manipulation of webpage elements. It details the types of nodes in the DOM, methods for selecting and traversing elements, and techniques for creating, removing, and replacing HTML elements. Additionally, it touches on form validation techniques and the different levels of the DOM specification.
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)
13 views44 pages

Chapter 6

The document provides an overview of the Document Object Model (DOM) in JavaScript, explaining its tree-like structure and how it allows for dynamic manipulation of webpage elements. It details the types of nodes in the DOM, methods for selecting and traversing elements, and techniques for creating, removing, and replacing HTML elements. Additionally, it touches on form validation techniques and the different levels of the DOM specification.
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/ 44

Ch-6

Introduction to DOM
What is DOM?
• JavaScript can access all the elements in a webpage making use of Document Object
Model (DOM).
• One of the most unique and useful abilities of JavaScript is its ability to manipulate the
DOM.
• The DOM (or Document Object Model) is a tree-like representation of the contents of a
webpage - a tree of “nodes” with different relationships depending on how they’re
arranged in the HTML document.
• In the DOM, all parts of the document, such as elements, attributes, text, etc. are
organized in a hierarchical tree-like structure; similar to a family tree in real life that
consists of parents and children.
• JavaScript can be used to dynamically add a page's DOM to add, delete, and modify
elements. The DOM represents a document as a tree structure.
• HTML can be viewed as a tree. Every tag is parsed by the browser, and a DOM object is
created. Tags that are inside this tag are considered to be this DOM Object's child
elements.
• In the end you get a hierarchy of objects that have parents and children. In Computer
Science such hierarchies are called Trees.
<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
</head>
<body>
<h1>Mobile OS</h1>
<ul>
<li>Android</li>
<li>iOS</li>
</ul>
</body>
</html>
• The way a document content is accessed and modified is called the Document Object
Model, or DOM.
• The Objects are organized in a hierarchy. This hierarchical structure applies to the
organization of objects in a Web document.
Structure of DOM
• The DOM (Document Object Model) represents the structure of an HTML document as a
tree-like hierarchy. This tree is called the DOM Tree because every element, attribute or
piece of text in the document is represented as a node in the tree.
• Structure of the DOM Tree
• Root Node: The root of the DOM tree is the document object.
• Parent-Child Relationship: Elements in the DOM are connected in a parent-child
hierarchy. For example, the <html> element is the parent of <head> and <body>,
which are its children.
• Siblings: Elements at the same level, such as <h1> and <p> inside a <body>, are
called siblings.
• Each part of the document (elements, attributes, text, etc.) is represented as a node.
Nodes are the fundamental building blocks of the DOM.
• Types of Nodes
• Element Nodes: Represent HTML elements, such as <div>, <p>, or <h1>.
• Example: <h1>Welcome</h1>: An element node representing <h1>.

• Text Nodes: Represent the text inside an element.


• Example: The text "Welcome" inside <h1> is a text node.

• Attribute Nodes: Represent the attributes of an element.


• Example: <a href="https://example.com">: The href attribute is an attribute node.
• Document Node: Represents the entire document. The document object is the root of
the DOM tree.
• Comment Nodes: Represent comments in the document.
• Example: <!-- This is a comment -->.

• Relationship Between Nodes


• Parent Node: A node that contains another node. For instance, <body> is the parent
of <h1>.
• Child Node: A node that is inside another node. For instance, <h1> is a child of
<body>.
• Sibling Nodes: Nodes that share the same parent. For instance, <h1> and <p> inside
<body> are siblings.
Methods for Selecting Elements in DOM
• By ID
• document.getElementById(id)
• Returns the element with the specified id.
• let element = document.getElementById("myId");
• console.log(element);

• By Class Name
• document.getElementsByClassName(className)
• Returns a live HTMLCollection of elements with the specified class name.
• let elements = document.getElementsByClassName("myClass");
• console.log(elements[0]); // Access first element
• By Tag Name
• document.getElementsByTagName(tagName)
• Returns a live HTMLCollection of elements with the specified tag name.
• let elements = document.getElementsByTagName("p");
• console.log(elements.length); // Number of <p> tags

• By Name Attribute
• document.getElementsByName(name)
• Returns a live NodeList of elements with the specified name attribute.
• let elements = document.getElementsByName("username");
• console.log(elements);
Using CSS Selectors
• document.querySelector(selector)
• Returns the first element matching the CSS selector.
• let element = document.querySelector(".myClass");
• document.querySelectorAll(selector)
• Returns a static NodeList of all elements matching the CSS selector.
• let elements = document.querySelectorAll("div > p.highlight");
Method Returns Live/Static Selection Basis

getElementById Single Element Static Id

getElementsByClassName HTML Collection Live Class name

getElementsByTagName HTML Collection Live Tag name

getElementsByName Node List Live Name attribute

querySelector Single Element Static CSS Selector

querySelectorAll Node List Static CSS Selector


Traversing DOM Relationships
• You can navigate elements relative to their positions in the DOM tree:
Traversing to Child Elements
• Once you have a reference to a parent element, you can traverse to its child elements:
 element.firstChild: Gets the first child node (can be an element, text, etc.).
 element.firstElementChild: Gets the first child element (ignores text nodes).
 element.lastChild: Gets the last child node.
 element.lastElementChild: Gets the last child element.
 element.children: Returns a live HTMLCollection of all child elements.

Traversing to Parent Elements


• You can also navigate up the DOM tree to find parent elements:
 element.parentNode: Gets the parent node (can be any node type).
 element.parentElement: Gets the parent element (only element nodes).
Traversing to Sibling Elements
• To navigate between siblings, you can use:
 element.nextSibling: Gets the next sibling node (can be any node type).
 element.nextElementSibling: Gets the next sibling element (ignores text nodes).
 element.previousSibling: Gets the previous sibling node.
 element.previousElementSibling: Gets the previous sibling element.

Traversing All Siblings


• To get all siblings of an element, you can convert the children property of the parent into
an array:
 const siblings = Array.from(parent.children);
Creating New HTML Elements (nodes)
Creating New Elements
• To create new HTML elements in the DOM, you typically use the
document.createElement() method. This method allows you to create an element of a
specified type (e.g., div, p, span, etc.).
• const newDiv = document.createElement("div");
Setting Properties
• Once an element is created, you can set various properties on it, such as its class, id, or
text content. This is done using properties like className, id, and textContent.
• newDiv.className = "child"; // Set the class
• newDiv.textContent = "I am a new child element!"; // Set the text content
Appending the Element to the DOM
• After creating and configuring the new element, you need to append it to an existing
element in the DOM. This is done using the appendChild() method, which adds the new
element as a child of a specified parent element.
• const container = document.getElementById("container");
• container.appendChild(newDiv); // Append the new div to the container
Event Handling
• Often, the creation of new elements is triggered by user interactions, such as clicking a
button. You can use event listeners to respond to these interactions. The
addEventListener() method is used to attach an event handler to an element.
• const button = document.getElementById("addElement");
• button.addEventListener("click", createNewElement); createNewElement on button
click
Creating new HTML Elements- insertBefore()
• This method is used to insert a new node (element) into the DOM tree before a specified
reference node.
• parentNode.insertBefore(newNode, referenceNode);
• parentNode: The parent element that will contain the new node.
• newNode: The new node (element) that you want to insert into the DOM.
• referenceNode: The existing node before which the new node will be inserted. If this
node is null, the new node will be appended to the end of the parent node's child list.
• Note: The insertBefore() method does not return a value. It modifies the DOM directly.
Use Cases
• Inserting new elements in a specific order.
• Adding elements before existing elements based on user interactions (e.g., adding a new
list item before a specific item in a list).
• Dynamically updating content in response to events (e.g., inserting a new comment
before the existing comments).
Removing HTML Elements
remove() Method:
• This method removes the element from the DOM directly.
• Syntax: element.remove();
• const element = document.getElementById("myElement");
• element.remove();
parentNode.removeChild() Method:
• This method removes a specified child node from its parent node.
• Syntax: parentNode.removeChild(childNode);
• const element = document.getElementById("myElement");
• element.parentNode.removeChild(element);
Replacing HTML Elements
Selecting Elements:
• To replace an element, you first need to select it using methods like document.getElementById(),
document.querySelector(), or other DOM traversal methods.
Creating a New Element:
• You can create a new element using document.createElement(). This method allows you to specify the type of
element you want to create (e.g., <p>, <div>, etc.).
Setting Properties:
• After creating a new element, you can set its properties, such as id, class, textContent, or any other attributes
that define its appearance and behavior.
Replacing the Old Element:
• To replace the old element with the new one, you use the replaceChild() method. This method is called on the
parent node of the old element and takes two arguments:
• The new element to be inserted. The old element to be replaced.
HTML DOM NodeList Object
• A NodeList is a collection of nodes that can be returned by various DOM methods. It is
similar to an array but does not have all the array methods. NodeLists are often returned
by methods such as document.querySelectorAll(), getElementsByTagName().
• Collection of Nodes: A NodeList can contain different types of nodes, including elements,
text nodes and comment nodes.
Live vs. Static:
• Live NodeList: Some methods return a live NodeList, meaning it automatically updates
when the document changes (e.g., getElementsByTagName()).
• Static NodeList: Other methods return a static NodeList, which does not change when
the document is modified (e.g., querySelectorAll()).
• Indexing: You can access individual nodes in a NodeList using an index, similar to an array
(e.g., nodeList[0]).
• Length Property: NodeLists have a length property that indicates the number of nodes in
the collection.
• Iteration: You can iterate over a NodeList using a for loop or the forEach method (if it is a
static NodeList).
The DOM Levels
• The W3C DOM specifications are divided into multiple levels where each level contains
some required and optional modules.
• An application can claim support of a level by implementing all the requirements of that
level.
• The Levels of DOM are given below
• Level 0: Supports an interface DOM, which existed before the creation of DOM Level
1. Examples include the Dynamic HTML (DHTML) Object Model or the Netscape
intermediate DOM. Level 0 is not a formal specification published by the W3C, but
rather a shorthand version of what existed before that standardization process.
• Level 1: Includes the Navigation of the DOM (HTML and XML) documents and allows
content manipulation. Elements of the HTML specification are also included in this level.
• Level 2: Supports namespace, filtered views and events.
• Level 3: It has many specifications:
• Core
• Load and Save
• XPath
• Views and formatting
• Requirements
• Validation
level 0
Refers to early implementations of the DOM that existed before the W3C began formal
standardization.
Examples:
Dynamic HTML (DHTML) Object Model.
Netscape intermediate DOM.
It is not an official specification by the W3C, but rather a description of early browser-specific
implementations of document manipulation.
Level 1
Introduced standardized interfaces for navigating and manipulating HTML and XML documents.
Included features from HTML, making it possible to access and modify elements dynamically.
Key Features:
Document traversal: Access nodes and their relationships (e.g., parent, child, sibling).
Content manipulation: Modify elements (e.g., change text, attributes, or styles).
It was the first formal DOM standard defined by W3C.
Level 2
Built upon Level 1, introducing new features for greater functionality.
Key Features:
Namespaces: Support for XML namespaces, which help avoid naming conflicts in XML
documents.
Filtered views: Ability to create views of the document based on specific filters.
Events: Standardized event handling (e.g., mouse clicks, key presses).
Level 3
Expanded the DOM further with additional specifications.
Key Features:
Core: Fundamental DOM manipulations applicable to both HTML and XML.
Load and Save: Ability to programmatically load and save documents.
XPath: Support for XPath, a language used to locate nodes in XML documents.
Views and Formatting: Additional features to manage document presentation.
Requirements: Defined additional structural and functional requirements for
applications.
Validation: Support for validating documents against their schemas.
Create a web page with the following requirements:
Include a <div> element with the ID box that contains placeholder text.
Add three <li> elements inside a <ul> with the class name items, each containing unique
text.
Add two buttons to the page:
The first button should change the text color of the element with the ID box to blue when
clicked.
The second button should remove all <li> elements inside the <ul>.
Write JavaScript to:
Change the text color of the element with the ID box.
Remove all child <li> elements inside the <ul> with the class name items.
Design a web page with the following functionality:
Add a <div> element with the ID container that includes a heading and a paragraph.
Create three <button> elements below the <div>:
The first button should increase the font size of the paragraph inside container.
The second button should hide the paragraph inside container.
The third button should make the paragraph visible again.
Write an external JavaScript file to:
Select the paragraph inside container and adjust its font size.
Toggle the visibility of the paragraph using the other two buttons.
Create a web page with the following requirements:
Add a <div> element with the ID notice that displays a message.
Include a <button> element labeled "Update Message."
Add an input field of type text with the placeholder "Enter new message."
When the button is clicked:
Update the text inside the notice div with the value entered in the input field.
Write an external JavaScript file to:
Fetch the value from the input field and update the text inside the notice div.
Design a web page with the following elements:
Add a <div> element with the ID image-container.
Include an <img> tag inside the image-container with a default image.
Add two buttons below the image:
The first button should replace the image with another image URL.
The second button should reset the image back to its original state.
Write an external JavaScript file to:
Change the image source when the first button is clicked.
Reset the image source to the default when the second button is clicked.
Form Validation in JavaScript
• Form validation is an essential aspect of web development, ensuring that user input is
accurate, complete, and secure. JavaScript provides a robust way to validate forms on the
client-side, reducing the load on servers and improving user experience. In this section,
we'll explore the theory and concepts behind form validation in JavaScript.
• In your form if any of the fields is not valid then the form should not be submitted and
respective error should be shown in the browser.
• Types of Validation
• Client-side validation: Validation performed on the client-side (browser) using
JavaScript.
• Server-side validation: Validation performed on the server-side using server-side
languages like PHP, Python, or Ruby.
Validation Techniques
• Pattern matching: Using regular expressions to match input patterns.
• Length validation: Checking the length of input fields.
• Range validation: Checking if input values fall within a specific range.
• Format validation: Checking if input values conform to a specific format (e.g., email,
phone number).
• Required field validation: Ensuring that required fields are filled.
What is RegEx?
• RegEx, short for Regular Expressions, is a powerful pattern-matching language used to
search, validate and extract data from strings. It's a way to describe a search pattern
using a combination of special characters, literals, and metacharacters.
• RegEx works by matching patterns in a string. You create a pattern, called a regular
expression and then use it to search for matches in a string. The regular expression
engine checks the string against the pattern, and if it finds a match, it returns the
matched text.
• Common RegEx Patterns:
• Email: ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$
• Phone Number: ^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$
• Password: ^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*#?&])[A-Za-z\d@$!%*#?&]{8,}$
• URL: ^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$
• JavaScript has built-in support for RegEx through the RegExp object. You can create a
RegEx pattern using the RegExp constructor or the / syntax.
• // Create a RegEx pattern using the RegExp constructor
• const pattern = new RegExp('^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$');
• // Create a RegEx pattern using the / syntax
• const pattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
• ^ asserts the start of the line.
• [a-zA-Z0-9._%+-]+ matches one or more alphanumeric characters, dots, underscores,
percent signs, plus signs, or hyphens. This is typically used to match the local part of
the email address (before the @ symbol).
• @ matches the @ symbol literally.
• [a-zA-Z0-9.-]+ matches one or more alphanumeric characters, dots, or hyphens. This
is typically used to match the domain name.
• \. matches a period (.) literally. The backslash is used to escape the period because in
regular expressions, a period has a special meaning (it matches any character).
• [a-zA-Z]{2,} matches the domain extension (it must be at least 2 characters long, and
can only contain letters).
• $ asserts the end of the line.
• RegEx is a powerful tool for pattern-matching and data extraction. By understanding the
basics of RegEx, you can create complex patterns to validate and extract data from
strings.
Q1. Write a JavaScript function that validates the registration form in the provided HTML
code. The function should check the following conditions:
The username should be at least 3 characters long and should not contain any special
characters or numbers.
The email should be in a valid format (e.g., example@example.com).
The password should be at least 8 characters long and should contain at least one
uppercase letter, one lowercase letter, and one number.
The confirm password field should match the password field.
If any of these conditions are not met, the function should display an error message next
to the corresponding field. If all conditions are met, the function should prevent the
default form submission behavior and display a success message.

Q2. Create an HTML form that prompts the user to enter a number. When the user submits
the form, validate the input to ensure it is a non-empty and valid number. If the input is
invalid, display an alert message and focus on the input field. If the input is valid, allow the
form to submit.
Cookies in JavaScript
• Cookies are small pieces of data stored on the client-side that can be used to remember
information about the user. You can create, read, and delete cookies using the
document.cookie property.
• Can be used for:
 Session Management: Tracking logins, shopping carts, etc.
 Personalization: Remembering user preferences or settings.
 Analytics: Tracking user behavior for insights.
Cookie Attribute
• expires: Used to maintain the state of a cookie up to the specified date and time.
• document.cookie = 'name=User1; expires=Sun, 19 May 2019 18:04:55 UTC'

• max-age: Used to maintain the state of a cookie up to the specified time in seconds.
• document.cookie = 'name=User1; max-age=3600'

• path: Used to expand the scope of the cookie to all the pages of a website.
• document.cookie = 'name=User1; path="/testFolder"'

• domain: Used to specify the domain for which the cookie is valid.
• document.cookie = 'name=User1; domain="826.a00.myftpupload.com";'
• Thus, it is a small file containing information (data), which a server embeds on a user’s
computer. Each time the same computer requests for a web page from a server, the
server refers to the created cookie for displaying the requested webpage. The size of
cookie depends on browser, but it should not exceed 1kb.
• Some commonly used attributes of cookie are:
• Name attribute
• Represents a variable name and the corresponding value to be stored in cookie.
• Expires attribute
• Specifies a time when a cookie is deleted. It is expressed as unix timestamp.
• Domain attribute
• Represents a domain name (partial or complete) to which a cookie is sent. For
Example, if the value of the valid domain attribute is www.gmail.com , a client
sends the cookie information to the web browser every time the client visits
www.gmail.com.
• Path attribute
• Identifies sites among various paths in the same domain. Setting this attribute to
the server root (/) allows the entire domain to access the information stored in a
cookie.
• Secure attribute
• Restricts browser from sending cookie information over unsecured connections.
The default value of security flag is 0 setting it to 1 allows the cookie to be sent
over a secure HTTP connection.
• Setting a Cookie
• document.cookie = "cookieName=cookieValue; expires=Date; path=Path";
• cookieName: The name of the cookie.
• cookieValue: The value of the cookie.
• expires: The date and time when the cookie expires. If not specified, the cookie will
be deleted when the browser is closed.
• path: The path on the server where the cookie will be available. If not specified, the
cookie will be available on the entire domain.
• Getting a Cookie
• var cookieValue = document.cookie.match(new RegExp('(^| )' + cookieName +
'=([^;]*)'));
• cookieName: The name of the cookie.
• Deleting a Cookie
• document.cookie = "cookieName=; expires=Thu, 12 Dec 2024 12:00:00 UTC;
path=Path";

You might also like