0% found this document useful (0 votes)
6 views24 pages

Lecture JS - Javascript APIs - Part 2

The document provides an introduction to the HTML Document Object Model (DOM), explaining its structure as a tree of objects that represent HTML elements. It details common properties and methods for accessing and manipulating these elements, as well as event handling and DOM traversal techniques using JavaScript. Additionally, it includes examples demonstrating how to create elements, access values, and perform operations on HTML elements using JavaScript.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views24 pages

Lecture JS - Javascript APIs - Part 2

The document provides an introduction to the HTML Document Object Model (DOM), explaining its structure as a tree of objects that represent HTML elements. It details common properties and methods for accessing and manipulating these elements, as well as event handling and DOM traversal techniques using JavaScript. Additionally, it includes examples demonstrating how to create elements, access values, and perform operations on HTML elements using JavaScript.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 24

DOM- Introduction

HTML DOM Tree


The HTML DOM (Document Object Model)
• When a web page is loaded, the browser creates
a Document Object Model of the page.
• The HTML DOM model is constructed as a tree of Objects:
What is HTML DOM?
The HTML DOM is a standard object model
and programming interface for HTML. It defines
• The HTML elements as objects
• The properties of all HTML elements
• The methods to access all HTML elements
• The events for all HTML elements
• In other words: The HTML DOM is a standard for
how to get, change, add, or delete HTML
elements.
Document Object
The document object is the root of the DOM and gives you access to the entire HTML
document.

Common Properties:
 document.body – Returns the <body> element.
 document.head – Returns the <head> element.
 document.documentElement – Returns the root element (<html>).
 document.title – Gets or sets the title of the document.
Common Methods:
 getElementById(id) – Returns an element by ID.
 getElementsByClassName(class) – Returns a live HTMLCollection.
 getElementsByTagName(tag) – Returns elements with the given
 tag.querySelector(selector) – Returns the first matching
 element.querySelectorAll(selector) – Returns a static NodeList of matches.
 createElement(tagName) – Creates a new element.
 createTextNode(text) – Creates a new text node.
Element Object
Represents an individual element in the DOM.

Common Properties:
 innerHTML – Gets or sets the HTML inside the element.
 textContent – Gets or sets the text content.
 className – Gets or sets the class attribute.
 id – Gets or sets the ID.
 style – Access inline styles.
Common Methods:
 appendChild(node) – Adds a node as the last child.
 removeChild(node) – Removes a child node.
 replaceChild(newNode, oldNode) – Replaces a child node.
 insertBefore(newNode, referenceNode) – Inserts a node before
 another.setAttribute(name, value) – Sets an attribute.
 getAttribute(name) – Gets an attribute.
 classList.add/remove/toggle/contains() – Modifies class list.
Node Interface
Element, Text, Comment, and other types inherit from Node.

Useful Methods and Properties:


nodeType – Returns the type of the node (e.g., 1 = element, 3 = text).
nodeName – Tag name or #text, #comment, etc.
parentNode – Returns the parent node.
childNodes – Returns a live NodeList of child nodes.
firstChild, lastChild, nextSibling, previousSibling – Navigation.
Event Handling
DOM provides an event system to handle user interactions.

Common Methods:
addEventListener(type, listener) – Adds an event listener.
removeEventListener(type, listener) – Removes one.

Example:
document.querySelector('button').addEventListener('click', () => {
alert('Button clicked!');
});
DOM Traversal
Use JavaScript to navigate between elements:

.parentElement
.children
.firstElementChild
.lastElementChild
.nextElementSibling
.previousElementSibling
Examples
Without JS example
Create element
<div id="container"></div>
<script>
const container = document.getElementById("container");
const p = document.createElement("p");
p.textContent = "Hello, DOM!";
p.setAttribute("class", "message");
container.appendChild(p);
</script>
With JS example

In this example both value of textbox and color of textbox(style)


was changed with help of JS
Accessing the value of HTML element

In this example the value of textbox with id=num was accessed using js
through documen.getElementById(“num”).value and stored it into a js
variable with name value
Accessing the value of HTML element

What should be the output of this code??


Accessing the value of HTML element

Output should be 23 because we inputted 22 and in js we increment it by


1 and then we are displaying it but why it is showing 221?
Accessing the value of HTML element
• The previous output was wrong because JS
access every HTML element value as String.
• So when anything in JS is string it will perform
operators with respect to string type i.e
addition on string will perform append
operation instead of addition.
• What’s the solution?
Accessing the value of HTML element
• To convert string into integer or float ,you
need to perform parseInt function
Accessing the value of HTML element

Now after converting the input into integer with help of parseInt the variable will now be
treated as integer and we can accurately get any result by applying appropriate operator
Adding two field values using JS
Adding two field values using
JS(output)
DOM traversal
<body>
<div id="container">
<ul>
<li class="item">Item 1</li>
<li class="item">Item 2</li>
<li class="item">Item 3</li>
</ul>
</div>

<script>
// Get the container element
const container = document.getElementById('container');

// Traverse to the <ul> element inside the container


const ulElement = container.querySelector('ul');

// Traverse through the <li> elements using childNodes or children


const listItems = ulElement.children; // or ulElement.childNodes to include text nodes

// Loop through the list items


Array.from(listItems).forEach((li, index) => {
console.log(`List Item ${index + 1}: ${li.textContent}`);
});

// Example of using parentNode


const firstItem = listItems[0];
const parentOfFirstItem = firstItem.parentNode;
console.log('Parent of first item:', parentOfFirstItem);

// Example of using nextElementSibling to get the next <li> element


const nextItem = firstItem.nextElementSibling;
console.log('Next item:', nextItem.textContent);

// Example of using previousElementSibling to get the previous <li> element


const prevItem = nextItem.previousElementSibling;
console.log('Previous item:', prevItem.textContent);
</script>
</body>
</html>

You might also like