16 JavaScript - Document Object Model or DOM , Typ_241025_142938
16 JavaScript - Document Object Model or DOM , Typ_241025_142938
16.1 INTRODUCTION
16.2 OBJECTIVES
16.8 SUMMARY
16.1 INTRODUCTION
The DOM provides a way for programs, typically written in languages like JavaScript, to
dynamically interact with and manipulate the content, structure, and style of a web page. The
DOM represents the document as a tree of nodes, where each node represents part of the
document. Understanding the different types of nodes is crucial for web developers, as it
allows for deep manipulation and interaction with the structure of web pages.
In the DOM, every element, text, comment, and other parts of an HTML or XML document
is a node of a certain type. Different types of nodes have different roles and characteristics,
and they interact to form the complex structure of web documents.
16.2 OBJECTIVES
After the successful completion of this unit, you will be able to-
● define the Document Object Model
● learn different DOM levels
● write JavaScript code to handle HTML DOM
● be skilled at different DOM interfaces
window.alert("hello UOU");
alert("hello UOUt");
In both cases, the alert function is a property of the window object, and you can call it
directly without explicitly referencing window. You can access window properties directly or
by using window. For instance:
let pageTitle = document.title; // Direct access
let screenWidth = window.screen.width; // Using window
Both of the above examples are correct and will give you the desired result.
Understanding the window object and its properties is essential for working with the BOM
and for building interactive web applications.
16.3.2 Document Object Model the W3C (World Wide Web Consortium) DOM (Document
Object Model) is indeed a critical and standardized programming interface for web
documents. It abstracts the structure of HTML, XML, and XHTML documents into a
tree-like form where each node in the tree corresponds to a part of the document.
The W3C DOM provides a way for programmers to manipulate the structure, style, and
content of web documents dynamically using scripting languages like JavaScript. It allows
developers to access, modify, add, or delete elements and content within a web page, making
it possible to create interactive and dynamic web experiences.
JavaScript can be embedded into HTML documents, and the Document Object Model
(DOM) is a crucial part of the web development process that enhances the power of
JavaScript by allowing it to interact with HTML elements and manipulate the content and
structure of a web page dynamically.
For JavaScript to effectively access and manipulate a document using the Document Object
Model (DOM), the document must conform to a well-defined and logical structure.
The browser builds a Document Object Model (DOM) representing the structure of the web
page. The DOM is a tree-like structure where each node corresponds to an element, attribute,
or piece of text in the HTML or XML document. The properties, methods, and events
available for manipulating and creating web pages are organized into objects within the
DOM. The objects in the Document Object Model (DOM) are accessible via scripting
languages, and JavaScript is the primary scripting language used for this purpose in modern
web browsers. The DOM is essentially an interface that allows scripting languages, like
JavaScript, to interact with the structure, style, and content of web documents. When a web
page is loaded into a browser, the browser goes through several steps to render the page for
the user. One of the key steps involves parsing the HTML document and constructing the
Document Object Model (DOM) representation of the page. Upon loading, every element on
the page gets a reference in the DOM, and JavaScript can use these references to interact with
and manipulate the elements dynamically.
For example (This is what the browser reads)
<html>
<head>
<title>Sample DOM Document</title>
</head>
<body>
<h1>An HTML Document</h1>
<p>This is a <i>simple</i> document.
</body>
</html>
<a>
UOU href
https://uou.ac.in
Whitespace Nodes: These nodes represent spaces, tabs, line breaks, or any other form of
whitespace characters within the markup. They contribute to formatting and indentation but
might not always directly affect the visible content of the page. For example, spaces or line
breaks between HTML elements would be considered whitespace nodes.
Nodes have relationships with each other, creating a tree structure. Elements are nested
within other elements, forming parent-child relationships. For instance, in the HTML:
<div>
<p>Hello, <strong>world!</strong></p>
</div>
The <div> element would be a parent to the <p> element.
The <p> element would be a parent to a text node ("Hello, ") and a <strong> element.
The <strong> element would be a child of the <p> element.
16.5.2 HTML DOM NODE TREE
The HTML Document Object Model (DOM) views HTML documents as tree structures,
commonly referred to as the "Node Tree" or simply the "DOM Tree.”
Source: https://w3schools.sinsixx.com/htmldom/dom_nodetree.asp.htm
The HTML Document Object Model (DOM) provides a structured representation of the
document as a tree of nodes, and through JavaScript, developers have the ability to access,
modify, delete, and create new nodes within this tree.
16.5.3 Node Parents, Children, and Siblings
There is a hierarchical pattern in the nodes of the node tree, with a relationship among
different nodes that has quite a striking similarity with the family tree. Hence it is no surprise
that the terms parent, child, and sibling are used to describe the relationships. The node
directly above another node is called the parent node, while those at the same level are
termed as sibling nodes. Those that are one level directly below another are termed the
children nodes. The topmost node, from where the pattern starts is called the root node of a
node tree. Thus, to summarize-
● Except for the root node, each node has one parent.
● A node can have any number of children.
● Nodes with the same parent are sibling nodes.
The following image illustrates a part of the node tree and the relationship between the nodes:
Source:
https://www.javascripttutorial.net/javascript-dom/document-object-model-in-javascript/
Look at the following HTML fragment:
<html>
<head>
<title>Welcome To UOU</title>
</head>
<body>
<h1>Swayam Course</h1>
<p>Web Technology</p>
</body>
</html>
Example: Get the element with id as “university” from the given document.
document.getElementById("university");
document.getElementsByTagName("p");
Example 2: Retrieve a list of all <p> elements that are descendants (children, grand-children,
etc.) of the element with id="university" from the given document.
document.getElementById("university").getElementsByTagName("p");
document.getElementsByClassName("university");
16.6.2 Property
A property is a value that we can fetch or set, e.g. it can be the name or content of a node. In
the Document Object Model (DOM), properties represent the various attributes,
characteristics, or state of HTML elements or nodes in a web page. These properties are
accessible through JavaScript and can be read or modified to manipulate the elements
dynamically.
Property Description
innerHTML ● represents the HTML content within
an element.
● Allow to access the markup and
content inside an HTML element as a
string.
● Useful for getting change or replace
the content within an element
dynamically.
Example: To get the node name of the body element from a given document.
Following example retrieves the text node value of the <p id="university"> tag from the given
document.
< html>
< body>
< p id="university"> Welcome to UOU </p>
< script type="text/javascript">
x=document.getElementById("university");
document.write(x.firstChild.nodeValue);
< /script>
< /body>
< /html>
if(n.nodeType == 3 /*Node.TEXT_NODE*/
n.data = n.data.toUpperCase();
Example 1
To verify Type of Node
<html>
<head>
<title>JavaScript DOM Nodes - Check Node Type</title>
<script type="text/javascript">
function checkNodeType()
{
var tag = document.getElementById("par1");
var value = tag.nodeType;
if(value == 1)
document.write("This is Element Node Type");
if(value == 2)
document.write("This is Attribute Node Type");
if(value == 3)
document.write("This is Text Node Type");
if(value == 8)
document.write("This is Comment Node Type");
if(value == 9)
document.write("This is Document Node Type");
}
</script>
</head>
<body>
<h3>JavaScript DOM Nodes Examples</h3>
<p id="par1">Welcome to JavaScript DOM</p>
<input type="button" onclick="checkNodeType();" value="Check Node Type">
</body>
</html>
Result
<html>
<head>
<title>JavaScript DOM Nodes - Check Child Nodes</title>
<script type="text/javascript">
function checkNode(value)
{
var tag = document.getElementById(value);
if(tag.hasChildNodes())
{
alert("Node has child nodes");
}
else
{
alert("Node has no child nodes");
}
}
</script>
</head>
<body id="T1">
<h3>JavaScript DOM Nodes Examples</h3>
<p>Click on the button given below to check the child nodes of the BODY element.</p>
<input type="button" onclick="checkNode('T1');" value="Check Child Node">
<p>Click on the button given below to check the child nodes of the INPUT element.</p>
<input type="button" id="T2" onclick="checkNode('T2');" value="Check Child Node">
</body>
</html>
Clicking on ‘check child node’, we get
nodeType: Returns an integer representing the type of the node. Common values include:
Methods:
appendChild(node): Adds a new child node to the end of the list of children for the current
node.
removeChild(node): Removes a child node from the list of children of the current node.
replaceChild(newNode, oldNode): Replaces an old child node with a new child node.
cloneNode(deep): Creates a duplicate of the current node. If deep is true, it also copies all
descendants.
hasChildNodes(): Returns a Boolean indicating whether the node has any child nodes.
parentNode: Returns the parent node of the current node.
nextSibling and previousSibling: Return the next and previous siblings of the current node.
parentNode: Returns the parent node of the current node.
childNodes: Returns a NodeList containing all child nodes of the current node.
The Element interfaces
The Element interface in the DOM (Document Object Model) represents an element in an
HTML or XML document. It extends the more general Node interface and provides specific
properties and methods that are applicable to elements. Common properties/methods are
tagName, attributes, children, innerHTML, etc.
The Attribute Interface
The Attribute interface in the DOM (Document Object Model) represents an attribute of an
HTML or XML element. It provides a way to interact with the attributes of an element and
retrieve information about them. Common properties/methods are name, value, etc.
The Text Interface
The Text interface in the DOM (Document Object Model) represents textual content within
an element. It is a type of node in the DOM tree and extends the more general CharacterData
interface. Common properties/methods are data (or nodeValue), textContent, etc.
Document Interface
The Document interface in the DOM (Document Object Model) represents the entire HTML
or XML document. It is the root of the document object model hierarchy, providing access to
various properties and methods for working with the document. Common properties/methods
are createElement, getElementById, createTextNode, etc.
The DocumentFragment Interface
The DocumentFragment interface in the DOM (Document Object Model) represents a
lightweight or minimal document object. It can be used to group together multiple nodes
without being part of the main document tree. DocumentFragment is often employed when
making multiple DOM manipulations before updating the live document, providing a more
efficient way to work with a collection of nodes without directly affecting the document's
layout.
The Event Interface
The Event interface in the DOM (Document Object Model) represents an event that occurs in
the browser, such as a user action (e.g., a click or a keypress) or changes in the state of an
element. The Event interface provides information about the event and methods to interact
with it. Common properties/methods are type, target, preventDefault, etc.
In this example:
The ThrowDOMException function is triggered by clicking the button.
Inside the function, an attempt is made to create a DOM attribute using
document.createAttribute("123"), where "123" is considered an invalid attribute name.
The code is wrapped in a try-catch block to catch any exception that might be thrown during
the attempt.
If a DOMException is caught, the error code is checked (INVALID_CHARACTER_ERR),
and an alert is shown indicating that the attribute name is invalid.
If the browser does not throw an exception (for example, Internet Explorer before version 9),
a different alert is displayed.
Result will be :
Output:
In this example, we start by creating an array itemsToAdd containing the text for each list
item we want to add. We then obtain a reference to the existing <ul> element by its ID. Next,
we create a DocumentFragment and loop through the itemsToAdd array, creating an <li>
element for each item, setting its text content, and appending it to the DocumentFragment.
Finally, we append the DocumentFragment to the <ul> element, which results in all the new
list items being added to the DOM in a single operation. This approach minimizes reflows
and repaints, enhancing the performance of dynamic content updates.
4. Which of the following is responsible for text content within an HTML or XML
document?
a. Document node
b. Text node
c. Element node
d. Attribute node
5. In the DOM, what type of node represents an attribute of an HTML or XML element?
a. Document node
b. Text node
c. Element node
d. Attribute node
6. What DOM node type is used to store and manipulate textual content within an HTML
or XML document?
a. Document node
b. Text node
c. Element node
d. Attribute node
7. Which DOM node type is used to represent comments in an HTML or XML document?
a. Document node
b. Text node
c. Comment node
d. Attribute node
10. Which DOM node type is used to represent the doctype declaration in an HTML
document?
a. Document node
b. Text node
c. Doctype node
d. Element node
16.8 SUMMARY
In the Document Object Model (DOM), which is a cross-platform and language-independent
interface that treats an XML or HTML document as a tree structure, nodes are the primary
building blocks. Each element, attribute, and piece of text in the document is a node of
different types. In this unit, the main types of nodes you have encountered in the DOM;
Document Node, Element Node, Attribute Node, Text Node, Comment Node and whitespace
nodes etc. In the context of the Document Object Model (DOM), an "interface" is a
specification of methods, properties, and events that a particular type of DOM node must
support You have gone through various DOM interfaces in this unit.
1. (b) Node
2. (b) Document node
3. (c) Element node
4. (b) Text node
5. (d) Attribute node
6. (b) Text node
7. (c) Comment node
8. (b) It is used to group together multiple nodes without being part of the main document
tree.
9. (b) Text node
10. (d) Doctype node