Chapter 6
Chapter 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>.
• 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
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";