KEMBAR78
M2 - Dom | PDF | Document Object Model | Html
0% found this document useful (0 votes)
7 views25 pages

M2 - Dom

FSD VTU MODULE 2
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)
7 views25 pages

M2 - Dom

FSD VTU MODULE 2
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/ 25

FSD [CS305]

MODULE 2

The DOM tree is a model of the web page, Working with the DOM tree, Comparing Techniques,
Cross-site scripting, Defending against cross-site scripting, XSS, Attribute nodes, Examples.

Activity: Write the Javascript program to perform all the operations on the DOM tree like adding
node, deletion of node, use of nodeValue property, traversing the tree.

Document Object Model

The HTML DOM (Document Object Model) is a programming interface that


represents the structure of a web page in a way that programming languages like
JavaScript can understand and manipulate.

Think of it as a tree of objects where each part of your HTML document


(elements, attributes, text) is represented as a node, allowing you to dynamically
change or interact with the content and structure of the page.

What Does the HTML DOM Look Like?

Imagine your webpage as a tree


 The document is the root.
 HTML tags like <html>, <head>, and <body> are branches.
 Attributes, text, and other elements are the leaves.

Why is DOM Required?

The DOM is essential because

 Dynamic Content Updates: Without reloading the page, the DOM allows
content updates (e.g., form validation, AJAX responses).
 User Interaction: It makes your webpage interactive (e.g., responding to
button clicks, form submissions).

Prof. Sunil Kumar K N, Dept. of ISE, CITech


FSD [CS305]

 Flexibility: Developers can add, modify, or remove elements and styles in


real-time.
 Cross-Platform Compatibility: It provides a standard way for scripts to
interact with web documents, ensuring browser compatibility.
How the DOM Works?

The DOM connects your webpage to JavaScript, allowing you to:


 Access elements (like finding an <h1> tag).
 Modify content (like changing the text of a <p> tag).
 React to events (like a button click).
 Create or remove elements dynamically.

Properties of the DOM

 Node-Based: Everything in the DOM is represented as a node (e.g.,


element nodes, text nodes, attribute nodes).
 Hierarchical: The DOM has a parent-child relationship, forming a tree
structure.
 Live: Changes made to the DOM using JavaScript are immediately
reflected on the web page.
 Platform-Independent: It works across different platforms, browsers, and
programming languages.

Prof. Sunil Kumar K N, Dept. of ISE, CITech


FSD [CS305]

HTML to DOM Tress

Prof. Sunil Kumar K N, Dept. of ISE, CITech


FSD [CS305]

Methods to Select HTML Elements in JavaScript

JavaScript provides multiple methods to select HTML elements from the DOM.
The most commonly used methods are:

Method Description

getElementById() Selects an element by its ID.

getElementsByClassName() Selects all elements with a given class name.

getElementsByTagName() Selects all elements with a given tag name.

Selects the first matching element using a CSS


querySelector()
selector.
Selects all matching elements using a CSS
querySelectorAll() selector.

1. document.getElementById() (Select by ID)


 This method selects an element using its unique id.
 Returns a single element.

Example: Changing Text of an Element


<p id="demo">Hello, World!</p>
<button onclick="changeText()">Click Me</button>
<script>
function changeText() {
let element = document.getElementById("demo"); // Select element by ID
element.textContent = "Text Changed!"; // Modify text content
}
</script>

 getElementById("demo") selects the <p> element.


 textContent changes the text inside the element
Prof. Sunil Kumar K N, Dept. of ISE, CITech
FSD [CS305]

2. document.getElementsByClassName() (Select by Class)


 This method selects all elements with a specific class.
 Returns a collection (HTMLCollection) of elements.

Example: Changing the Style of Multiple Elements

<p class="myClass">First Paragraph</p>


<p class="myClass">Second Paragraph</p>
<button onclick="changeColor()">Change Color</button>

<script>

function changeColor() {
let elements = document.getElementsByClassName("myClass"); // Select
elements by class
for (let i = 0; i < elements.length; i++) {
elements[i].style.color = "red"; // Change text color
}
}
</script>
 getElementsByClassName("myClass") selects all <p> elements with
class="myClass".
 A for loop is used to apply changes to all elements.

3. document.querySelector() (Select First Matching Element)


 This method selects the first element that matches a CSS selector.
 It allows more flexible selection compared to getElementById().

Example: Changing Font Size


<p class="example">Hello World</p>
<p class="example">Namaste</p>

Prof. Sunil Kumar K N, Dept. of ISE, CITech


FSD [CS305]

<button onclick="changeSize()">Change Font Size</button>


<script>
function changeSize() {
let element = document.querySelector(".example"); // Select first element
with class 'example'
element.style.fontSize = "20px"; // Change font size
}

</script>
 querySelector(".example") selects the first <p> element with class
"example".
 style.fontSize = "20px" changes its font size.

4. getElementsByTagName(tagName) (Select by Tag Name)


 This method selects all elements with a given tag name (e.g., p, div,
span).
 It returns an HTMLCollection, which is a live collection of elements.
Example: Changing the Background Color of All Paragraphs
<p>First paragraph</p>
<p>Second paragraph</p>
<button onclick="changeBg()">Change Background</button>
<script>
function changeBg() {
let paragraphs = document.getElementsByTagName("p"); // Select all <p>
elements

for (let i = 0; i < paragraphs.length; i++) {


paragraphs[i].style.backgroundColor = "yellow"; // Change background
color
}
}
Prof. Sunil Kumar K N, Dept. of ISE, CITech
FSD [CS305]

</script>
 getElementsByTagName("p") selects all <p> elements.
 The for loop iterates through each <p> and changes the background color.

5. querySelectorAll(selector) (Select Multiple Elements with CSS Selector)


 This method selects all elements matching a CSS selector.
 It returns a NodeList, which is a static collection (does not update when
DOM changes).

Example: Changing Font Size of All Elements with Class "text"


<p class="text">Paragraph 1</p>
<p class="text">Paragraph 2</p>
<button onclick="changeFontSize()">Change Font Size</button>
<script>
function changeFontSize() {
let elements = document.querySelectorAll(".text"); // Select all elements
with class "text"
elements.forEach(element => {
element.style.fontSize = "18px"; // Change font size
});
}
</script>
 querySelectorAll(".text") selects all elements with class="text".
 The forEach() method is used to apply styles to each selected element

Prof. Sunil Kumar K N, Dept. of ISE, CITech


FSD [CS305]

DOM Manipulation
DOM (Document Object Model) manipulation allows us to dynamically change HTML
content, modify CSS styles, and update attributes of HTML elements using JavaScript.

1. Changing HTML Content (innerHTML and textContent)

You can change the text or HTML content of an element using:


 innerHTML → Updates an element’s HTML content (including child
elements).
 textContent → Changes only text, ignoring HTML tags.

Example: Changing Content on Button Click

<html>
<body>
<div id="example1">This is the original content using innerHTML.</div>
<div id="example2">This is the original text content using textContent.</div>
<button onclick="changeContent()">Change Content</button>
</body>
<script>
// Function to change content function
changeContent() {
document.getElementById("example1").innerHTML = "<b>This is changed using
innerHTML!</b>";

document.getElementById("example2").textContent = "This is changed using


textContent!";
}
</script>

</html>
Prof. Sunil Kumar K N, Dept. of ISE, CITech
FSD [CS305]

Output
before

After button click

 innerHTML changes the entire content of an element, including HTML


tags. In this case, we replace the content of the first div with bold text
using <b>.
 textContent changes only the text inside the element, ignoring any HTML
tags. The second div is updated with plain text, without any HTML
formatting.
 The first div shows "This is the original content using innerHTML."
 The second div shows "This is the original text content using
textContent."
 After clicking the "Change Content" button.
 The first div will display "This is changed using innerHTML!" with bold
text.
 The second div will display "This is changed using textContent!" with
plain text.

Prof. Sunil Kumar K N, Dept. of ISE, CITech


FSD [CS305]

2. Setting CSS Styles (style.property)


You can change the appearance of an element dynamically using JavaScript.
Example: Changing Text Color and Background

<p id="styledText">Change my style!</p>


<button onclick="applyStyles()">Apply Styles</button>
<script>
function applyStyles() {
let text = document.getElementById("styledText");
text.style.color = "white"; // Change text color
text.style.backgroundColor = "blue"; // Change background color
text.style.padding = "10px"; // Add padding
text.style.fontSize = "20px"; // Increase font size
}
</script>

Output
Before

After button click

Prof. Sunil Kumar K N, Dept. of ISE, CITech


FSD [CS305]

 JavaScript modifies the inline CSS of the <p> element, changing color,
background, padding, and font size.

3. Modifying Element Attributes (setAttribute() and getAttribute())


You can update or retrieve attributes such as src, href, alt, class, etc.

Example: Changing Image Source and Alt Text


<img id="image" src="old.jpg" alt="Old Image" width="150">
<button onclick="changeImage()">Change Image</button>
<script>
function changeImage() {
let img = document.getElementById("image");
img.setAttribute("src", "new.jpg"); // Change image source
img.setAttribute("alt", "New Image"); // Update alt text

</script>
 The setAttribute() method updates the src to "new.jpg", changing the
displayed image

Output

before

Prof. Sunil Kumar K N, Dept. of ISE, CITech


FSD [CS305]

After button click

Manipulating the DOM with JavaScript is a core aspect of web development.


Understanding how to select, modify, and manipulate DOM elements enables
you to create dynamic, interactive web applications. With the power to change
text, styles, attributes, and even structure in real-time, JavaScript empowers
developers to build rich, user-responsive websites.

Working with DOM Nodes

In JavaScript, the Document Object Model (DOM) represents the structure of an


HTML document as a tree of nodes. Each element, attribute, and piece of text in
an HTML document is a node that can be accessed and manipulated using
JavaScript.
Types of DOM Nodes
1. Element Nodes – Represent HTML elements (e.g., <div>, <p>, <ul>).
2. Attribute Nodes – Represent attributes of elements (e.g., class="box",
id="header").
3. Text Nodes – Represent text within elements (e.g., inside <p>Hello</p>,
"Hello" is a text node).
4. Comment Nodes – Represent HTML comments (e.g., <!-- This is a
comment -->).

Prof. Sunil Kumar K N, Dept. of ISE, CITech


FSD [CS305]

Accessing DOM Nodes

To work with DOM nodes, we can use various methods:


1. document.getElementById(id) – Selects an element by its id.
Ex,
let title = document.getElementById("heading");
console.log(title); // Logs the element with id "heading"

2. document.getElementsByClassName(className) – Selects all elements


with a specific class.
Ex,
let items = document.getElementsByClassName("list-item");
console.log(items[0]); // Logs the first item with class "list-item"

3. document.getElementsByTagName(tagName) – Selects all elements of


a specific tag.
Ex,
let paragraphs = document.getElementsByTagName("p");
console.log(paragraphs.length); // Logs the number of <p> elements

4. document.querySelector(selector) – Selects the first matching element.


Ex,
let firstItem = document.querySelector(".list-item");
console.log(firstItem); // Logs the first element with class "list-item"

5. document.querySelectorAll(selector) – Selects all matching elements.


Ex,
let allItems = document.querySelectorAll(".list-item");
console.log(allItems); // Logs a NodeList of all elements with class "list-item"

Manipulating DOM Nodes


Prof. Sunil Kumar K N, Dept. of ISE, CITech
FSD [CS305]

Once a node is selected, we can modify it.

1. Changing Content (textContent and innerHTML)


Ex,
let title = document.getElementById("heading");
title.textContent = "New Title"; // Changes only text
title.innerHTML = "<span>New Title</span>"; // Supports HTML

2. Changing Attributes (setAttribute and getAttribute)


Ex,
let link = document.getElementById("myLink");
link.setAttribute("href", "https://www.example.com"); // Change URL
console.log(link.getAttribute("href")); // Get attribute value

3. Modifying CSS Styles


Ex,
let box = document.getElementById("box");
box.style.color = "blue"; // Changes text color
box.style.backgroundColor = "lightgray"; // Changes background

Prof. Sunil Kumar K N, Dept. of ISE, CITech


FSD [CS305]

Creating and Appending Nodes


New elements can be created dynamically using JavaScript.

1. Creating and Appending an Element


Ex,
let newPara = document.createElement("p"); // Create a <p> element
newPara.textContent = "This is a new paragraph"; // Add text content
document.body.appendChild(newPara); // Append to the document

2. Removing a Node
Ex,
let removeMe = document.getElementById("removeMe");
removeMe.parentNode.removeChild(removeMe); // Removes the element

3. Replacing an Element
Ex,
let oldPara = document.getElementById("oldText");
let newPara = document.createElement("p");
newPara.textContent = "This is updated text";
oldPara.parentNode.replaceChild(newPara, oldPara);

Traversing the DOM


DOM traversal means navigating through elements in the document tree.

1. Parent Node (parentNode)


Ex,
let child = document.getElementById("child");
console.log(child.parentNode); // Logs the parent element

Prof. Sunil Kumar K N, Dept. of ISE, CITech


FSD [CS305]

2. Child Nodes (childNodes and children)


Ex,
let list = document.getElementById("list");
console.log(list.childNodes); // Logs all child nodes (including text and
comment nodes)
console.log(list.children); // Logs only element nodes

3. First and Last Child


Ex,
console.log(list.firstElementChild.textContent); // Logs first list item
console.log(list.lastElementChild.textContent); // Logs last list item

4. Sibling Nodes (nextElementSibling and previousElementSibling)


Ex,
console.log(child.previousElementSibling); // Logs previous sibling
console.log(child.nextElementSibling); // Logs next sibling

Example
<!DOCTYPE html>
<html lang="en">
<head>
<title>DOM Example</title>
</head>
<body>
<div id="container">
<h1 id="heading">Hello World</h1>
<p>This is a paragraph.</p>
<ul id="list">
<li class="list-item">Item 1</li>
<li class="list-item" id="removeMe">Item 2</li>
Prof. Sunil Kumar K N, Dept. of ISE, CITech
FSD [CS305]

<li class="list-item">Item 3</li>


</ul>

<button onclick="addParagraph()">Add Paragraph</button>


<button onclick="removeItem()">Remove Item 2</button>
</div>

<script>
function addParagraph() {
let newPara = document.createElement("p");
newPara.textContent = "New paragraph added!";
document.getElementById("container").appendChild(newPara);
}

function removeItem() {
let item = document.getElementById("removeMe");
item.parentNode.removeChild(item);
}
</script>
</body>
</html>

Prof. Sunil Kumar K N, Dept. of ISE, CITech


FSD [CS305]

NodeList
A NodeList is an important data structure in the Document Object Model
(DOM). It represents a collection of nodes, usually element nodes such as <p>,
<div>, or <span>. Whenever we perform a query on the document that returns
multiple results, JavaScript stores those results inside a NodeList.

Key Characteristics of NodeList


1. Array-like Object

 NodeList is not a real JavaScript array.


 It has a length property that shows how many elements are present.
 Each item can be accessed using a zero-based index.
 Example: nodeList[0] accesses the first element.

2. Returned by DOM Methods


Some common DOM methods that return NodeLists are:

document.getElementsByTagName('p'); // returns live NodeList


document.getElementsByClassName('box'); // returns live NodeList
document.querySelectorAll('.menu'); // returns static NodeList

3. Not a True Array

 You cannot directly use array methods like map(), filter(), or reduce() on a
NodeList.
 Modern browsers allow forEach() on NodeList, but for older compatibility it is
safer to convert NodeList into a true array using:

let arr = Array.from(nodeList);

Live and Static NodeLists


An essential concept to understand is that not all NodeLists behave the same way. The main
difference is whether they are live or static.

A Live NodeList is connected to the page. If the page's structure changes after the list is
created—for example, if a new element that matches the query is added—the list will
automatically update itself to include that new element.

The getElementsByTagName and getElementsByClassName methods return this type of live list.

Prof. Sunil Kumar K N, Dept. of ISE, CITech


FSD [CS305]

A Static NodeList is a snapshot. When the method runs, it captures which elements match the
query at that exact moment and puts them in the list. Any changes to the page afterward do not
affect the list. The elements in it remain the same. The querySelectorAll method returns this type
of static list.

Because a static list does not change, it can be more efficient to store it in a variable if you need
to use it multiple times in your code.

Note:

1. Live NodeList - Updates automatically when the DOM changes.


2. Static NodeList - Does not update when DOM changes

Accessing Items in a NodeList


To work with a specific element inside a NodeList, you need to access it by its number, or index.
There are two primary ways to do this.

The first way is to use the item() method. You call this method on your NodeList and pass the
index number of the item you want to retrieve. For example, elements.item(0) will return the first
element in the list.

The second way, which is more commonly used, is array syntax. This involves using square
brackets [] with the index number inside them. For example, elements[0] will also return the first
element in the list. Both methods achieve the same result.

It is important to remember that these index numbers start counting at zero. The first item is at
index 0, the second at index 1, and so on.

1. Using item() method

var elements = document.getElementsByClassName('hit');

if (elements.length > 1)

var firstItem = elements.item(0);

• Step 1: Get elements with class hit.


• Step 2: Check if NodeList has items.
• Step 3: Access element using item().

Prof. Sunil Kumar K N, Dept. of ISE, CITech


FSD [CS305]

2. Using Array Syntax

var elements = document.getElementsByClassName('hit');

if (elements.length > 1)

var firstItem = elements[0];

• Step 1: Create NodeList with hit elements.


• Step 2: Verify count using length.
• Step 3: Access first element using [0].

Selecting Elements by Class Attribute: A way to get a NodeList of all elements that have a
specific class. This lets you access or modify multiple elements at once.

var elements = document.getElementsByClassName('hit');

if (elements.length > 2)

var el = elements[2];

el.className = 'cool';

• Access third element in NodeList.


• Change its class attribute to "cool".
• Updates style/presentation dynamically.

Prof. Sunil Kumar K N, Dept. of ISE, CITech


FSD [CS305]

Comparing Techniques for Updating HTML Content in a Webpage

There are multiple ways to add or update HTML content in a webpage. Each method has its
own use cases, advantages, and drawbacks. Choosing the right method depends on
performance, security, and the needs of the project.

Techniques to Update HTML

1. document.write()

 A quick and simple method for beginners.


 Works only while the page is loading.
 Risks: Can overwrite the entire page if used after the page loads and may break
XHTML validation.
 Modern practice: Discouraged, rarely used in current coding.

Example:

document.write("<h1>Hello, World!</h1>");

2. element.innerHTML

 Easiest way to insert or replace large chunks of HTML.


 Faster than creating elements individually with DOM methods for bulk updates.
 Can clear all content of an element in one step.
 Risks: Unsafe for user input (can cause XSS attacks) and may break event handlers
attached to children.

Example:

let div = document.getElementById('content');

div.innerHTML = "<h2>Welcome to JavaScript</h2><p>This is a paragraph.</p>";

Properties to Update Text and HTML Content


Property Use Example
Updates the HTML content inside div.innerHTML =
innerHTML an element. Can include tags. "<h2>Heading</h2><p>Text</p>";

Updates or retrieves visible text div.innerText = "Hello World";


innerText only, ignores HTML tags.

Similar to innerText, but faster and div.textContent = "Hello World";


textContent includes all text (even hidden).

Replaces the entire element, div.outerHTML = "<section>New


outerHTML including its own tag. Section</section>";

Prof. Sunil Kumar K N, Dept. of ISE, CITech


FSD [CS305]

Cross-Site Scripting (XSS)


Cross-Site Scripting (XSS) is a common security vulnerability that occurs when attackers inject
malicious code (usually HTML or JavaScript) into a website. This happens when user input is
not properly validated and is directly displayed on a page.

XSS allows attackers to manipulate a website in ways that can harm both the website owner and
its users. Even seemingly harmless input fields like comments, search bars, or profile forms can
be exploited if not properly handled.

Ways XSS can occur

Attackers insert malicious scripts in various ways:

 Form Inputs and Comment Sections: Scripts can be hidden inside text submitted by
users.
 Uploaded Files: Malicious code can be embedded in images, documents, or other files.
 Third-Party Scripts and Ads: External content, such as ads or widgets, may carry
harmful scripts.

Once the script runs in the browser, it can perform actions on behalf of the user without their
knowledge.

Effects of XSS Attacks

XSS attacks can have serious consequences:

 Steal Sensitive Information: Cookies, session tokens, and other private data can be
captured.
 Impersonate Users: Attackers can hijack sessions and act as the user.
 Perform Unauthorized Actions: For example, making purchases or changing account
settings without permission.
 Spread Malware: Malicious scripts can propagate to other users, infecting them quickly.

In short, XSS can compromise both user privacy and website integrity.

Prof. Sunil Kumar K N, Dept. of ISE, CITech


FSD [CS305]

Defending Against XSS


1. Validate Input

 Restrict input to expected characters and formats.


 Do not allow raw HTML or JavaScript from untrusted sources.
 Validate data before storing in the server and before displaying on the webpage.

2. Escape Data from Server & Database

 Avoid creating DOM elements directly from untrusted data.


 Insert external data as plain text using textContent.
 Escape potentially dangerous characters like <, >, and & before output.

3. Safe Development Practices

 Keep code and content separate in templates.


 Allow scripts, styles, and external content only from trusted sources.
 Sanitize all input and output at every layer: browser → server → database.

Prof. Sunil Kumar K N, Dept. of ISE, CITech


FSD [CS305]

Attribute Nodes

An attribute node is a special type of node in the DOM that represents an attribute of an
HTML element, such as id, class, src, or href.

 In the DOM, everything is a node: elements, text, comments, and attributes.


 Each attribute of an element is treated as an attribute node, which can be accessed,
modified, or removed using JavaScript.
 Attribute nodes are part of the element’s node tree but are not children of the element;
they are associated with the element itself.

Example:

<img id="logo" src="logo.png" alt="Website Logo">


<script>
let image = document.getElementById('logo');
let idAttr = image.getAttributeNode('id'); // Returns the attribute node for 'id'
console.log(idAttr.name); // Output: id
console.log(idAttr.value); // Output: logo
</script>

Every HTML element can have attributes such as id, class, src, href, and more. Attributes
provide extra information about an element and can control its behavior or appearance.

Using JavaScript, we can perform four main actions on attributes:

1. Access an attribute – Read the value of an attribute.


2. Change an attribute – Update an existing attribute with a new value.
3. Add a new attribute – Create a new attribute for an element.
4. Remove an attribute – Delete an attribute from an element.

1. Accessing an Attribute

Use the getAttribute() method to read the value of an attribute.

<img id="logo" src="logo.png" alt="Website Logo">


<script>
let image = document.getElementById('logo');
let srcValue = image.getAttribute('src'); // Access the 'src' attribute
console.log(srcValue); // Output: logo.png
</script>

Prof. Sunil Kumar K N, Dept. of ISE, CITech


FSD [CS305]

2. Changing an Attribute

Use the setAttribute() method to update an attribute’s value.

<script>
image.setAttribute('src', 'new-logo.png'); // Change 'src' to new-logo.png
</script>

3. Adding a New Attribute

If the attribute does not exist, setAttribute() will create it.

<script>
image.setAttribute('title', 'Company Logo'); // Adds a new 'title' attribute
</script>

4. Removing an Attribute

Use the removeAttribute() method to delete an attribute.

<script>
image.removeAttribute('alt'); // Removes the 'alt' attribute
</script>

Note :

1. getAttribute() → read value


2. setAttribute() → change or add value
3. removeAttribute() → delete value

Prof. Sunil Kumar K N, Dept. of ISE, CITech

You might also like