0% found this document useful (0 votes)
2 views55 pages

Module-IV DOM - Java Scripth

The document provides an overview of the JavaScript Document Object Model (DOM) and Browser Object Model (BOM), explaining their structures, functionalities, and methods for manipulating HTML documents. It highlights the importance of the DOM in creating dynamic web pages, enabling interactivity, and managing content updates, while the BOM focuses on browser-specific features. Key methods of the document object, such as getElementById, getElementsByName, and getElementsByTagName, are also discussed, illustrating how to access and modify HTML elements.

Uploaded by

Shubham Kumar
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)
2 views55 pages

Module-IV DOM - Java Scripth

The document provides an overview of the JavaScript Document Object Model (DOM) and Browser Object Model (BOM), explaining their structures, functionalities, and methods for manipulating HTML documents. It highlights the importance of the DOM in creating dynamic web pages, enabling interactivity, and managing content updates, while the BOM focuses on browser-specific features. Key methods of the document object, such as getElementById, getElementsByName, and getElementsByTagName, are also discussed, illustrating how to access and modify HTML elements.

Uploaded by

Shubham Kumar
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/ 55

JavaScript DOM Model

• The document object represents the whole html document. The HTML DOM (Document Object
Model), When a web page is loaded, the browser creates a Document Object Model of the page. It
is the root element that represents the html document. It has properties and methods. By the help
of document object, we can add dynamic content to our web page.It is the object of window. So
window.document
• Is same as : document
• The HTML DOM model is constructed
as a tree of Objects:
The HTML DOM Tree of Objects

• With the object model, JavaScript gets all the power it needs to create dynamic HTML:
 JavaScript can change all the HTML elements in the page
 JavaScript can change all the HTML attributes in the page
 JavaScript can change all the CSS styles in the page
 JavaScript can remove existing HTML elements and attributes
 JavaScript can add new HTML elements and attributes
 JavaScript can react to all existing HTML events in the page
 JavaScript can create new HTML events in the page
 Why is DOM Required?
• HTML is used to structure the web pages and Javascript is used to add behavior to our web pages.
When an HTML file is loaded into the browser, the JavaScript can not understand the HTML
document directly. So it interprets and interacts with the Document Object Model (DOM), which is
created by the browser based on the HTML document.
• DOM is basically the representation of the same HTML document but in a tree-like structure
composed of objects. JavaScript can not understand the tags(<h1>H</h1>) in HTML document but
can understand object h1 in DOM.
• JavaScript interprets DOM easily, using it as a bridge to access and manipulate the elements. DOM
Javascript allow access to each of the objects (h1, p, etc) by using different functions.
• The Document Object Model (DOM) is essential in web development for several reasons:
 Dynamic Web Pages: It allows you to create dynamic web pages. It enables the JavaScript to access
and manipulate page content, structure, and style dynamically which gives interactive and
responsive web experiences, such as updating content without reloading the entire page or
responding to user actions instantly.
 Interactivity: With the DOM, you can respond to user actions (like clicks, inputs, or scrolls) and
modify the web page accordingly.
 Content Updates: When you want to update the content without refreshing the entire page, the
DOM enables targeted changes making the web applications more efficient and user-friendly.
 Cross-Browser Compatibility: Different browsers may render HTML and CSS in different ways. The
DOM provides a standardized way to interact with page elements.
 Single-Page Applications (SPAs): Applications built with frameworks such as React or Angular,
heavily rely on the DOM for efficient rendering and updating of content within a single HTML page
without reloading the full page
 Structure of DOM
• DOM can be thought of as a Tree or Forest (more than one tree). The term structure model is
sometimes used to describe the tree-like representation of a document.
• Each branch of the tree ends in a node, and each node contains objects Event listeners can
be added to nodes and triggered on an occurrence of a given event.
• One important property of DOM structure models is structural isomorphism: if any two DOM
implementations are used to create a representation of the same document, they will create
the same structure model, with precisely the same objects and relationships.
 Why DOM is called an Object Model?
• Documents are modeled using objects, and the model includes not only the structure of a
document but also the behavior of a document and the objects of which it is composed like
tag elements with attributes in HTML.
• According to W3C - "The W3C Document Object Model (DOM) is a platform and language-
neutral interface that allows programs and scripts to dynamically access and update the
content, structure, and style of a document."
 Properties of document object
• Let's see the properties of document object that can be accessed and modified by the
document
• Window Object: Window Object is object of the browser which is always at top of the
hierarchy. It is like an API that is used to set and access all the properties and methods of the
browser. It is automatically created by the browser.
• Document object: When an HTML document is loaded into a window, it becomes a
document object. The ‘document’ object has various properties that refer to other objects
which allow access to and modification of the content of the web page. If there is a need to
access any element in an HTML page, we always start with accessing the ‘document’ object.
Document object is property of window object.
• Form Object: It is represented by form tags.
• Link Object: It is represented by link tags.
• Anchor Object: It is represented by a href tags.
• Form Control Elements: Form can have many control elements such as text fields, buttons,
radio buttons, checkboxes, etc.
Relationship between BOM, DOM and JavaScript
 The Browser Object Model (BOM)
• The BOM represents the browser-specific objects and interfaces that enable JavaScript to
interact with the browser window and its elements. It provides access to various properties,
methods, and events, allowing developers to control browser behavior, handle windows,
manage cookies, manipulate URLs, and more.
 Key Components of the BOM:
• Window Object:
The global object in the BOM, representing the browser window and providing access to
browser-related features.
• Navigator Object:
Provides information about the browser’s name, version, platform, and capabilities.
• Location Object:
Represents the URL of the current web page and allows manipulation of the URL.
• Document Object:
Represents the entire HTML document and provides methods to interact with its content.
 Practical Scenarios for Using the BOM:
• Managing Windows:
// Open a new browser window
const newWindow = window.open("https://www.example.com", "_blank");
// Close the current window
window.close();
• Manipulating URLs:
// Redirect the user to a different URL
window.location.href = "https://www.example.com";
// Get the current URL and display it
const currentUrl = window.location.href;
console.log(currentUrl);
• Handling Cookies:
// Create a cookie
document.cookie = "username=John Doe";
// Read a cookie
const username = document.cookie.split(";")[0].split("=")[1];
console.log(username);
// Delete a cookie
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
• The Document Object Model (DOM)
• The DOM is a platform-independent programming interface that represents the structure of
an HTML or XML document as a tree-like structure. It allows JavaScript to manipulate and
interact with the document’s elements, such as modifying content, adding or removing
elements, handling events, and more.
• Key Components of the DOM:
• Document Object:
Represents the root of the document tree and provides methods to access and manipulate
elements.
• Element Objects:
Represent HTML elements and provide methods to manipulate their properties, styles, and
content.
• Node Objects:
Represent different types of nodes within the document, including elements, text,
comments, and more.
 Practical Scenarios for Using the DOM:
• Modifying Content:
• // Change the text of a paragraph element
const paragraph = document.getElementById("myParagraph");
paragraph.textContent = "Updated text";
// Update an element's attribute
const link = document.querySelector("a");
link.setAttribute("href", "https://www.example.com");
• Manipulating Elements:
• // Create a new element and append it to the document
const newElement = document.createElement("div");
newElement.textContent = "New Element";
document.body.appendChild(newElement);
// Remove an element from the document
const elementToRemove = document.getElementById("myElement");
elementToRemove.parentNode.removeChild(elementToRemove);
• Handling Events:
• // Add an event listener to a button
const button = document.getElementById("myButton");
button.addEventListener("click", function() {
console.log("Button clicked");
});
// Handle form submission event
const form = document.getElementById("myForm");
form.addEventListener("submit", function(event) {
event.preventDefault();
console.log("Form submitted");
});
 Comparing and Contrasting the BOM and DOM
 Relationship between the BOM and DOM:
 Both the BOM and DOM are part of the JavaScript environment within a web browser.
 The BOM provides access to browser-specific features and controls the browser window.
 The DOM represents the structure of an HTML or XML document and enables manipulation
of its elements.
 Key Differences between the BOM and DOM:
 Scope:The BOM operates at the window level, while the DOM operates within the document
and its elements.
 Functionality:The BOM focuses on browser-related features like managing windows, cookies,
and URLs.
 The DOM is concerned with manipulating and interacting with the document’s structure and
content.
 Practical Examples Comparing the BOM and DOM:
• Accessing Window Properties with the BOM:
// Get the width and height of the browser window
const windowWidth = window.innerWidth || document.documentElement.clientWidth;
const windowHeight = window.innerHeight || document.documentElement.clientHeight;
console.log(`Window dimensions: ${windowWidth} x ${windowHeight}`);
// Scroll to a specific position
window.scrollTo(0, 0);
• Manipulating DOM Elements with the DOM:
// Change the background color of an element
const element = document.getElementById("myElement");
element.style.backgroundColor = "blue";
// Create a new element and append it to the document
const newElement = document.createElement("div");
newElement.textContent = "New Element";
document.body.appendChild(newElement);
• The BOM provides access to browser-specific features, allowing control over the browser
window, cookies, and URLs. On the other hand, the DOM facilitates manipulation and
interaction with the document’s elements, enabling dynamic content updates and event
handling. By leveraging the capabilities of both the BOM and DOM, developers can create
dynamic and interactive web applications. Whether it’s managing windows, manipulating
URLs, handling cookies, modifying content, or interacting with events, the BOM and DOM
provide the necessary tools to enhance web interactions with JavaScript.
 Methods of document object
• We can access and change the contents of document by its methods. The important methods
of document object are as follows:

Method Description

write("string") writes the given string on the doucment.

writeln("string") writes the given string on the doucment


with newline character at the end.

getElementById() returns the element having the given id


value.

getElementsByName() returns all the elements having the given


name value.

getElementsByTagName() returns all the elements having the given tag


name.

getElementsByClassName() returns all the elements having the given


class name.
• Example: In this example, We use HTML element id to find the DOM HTML element.
<!DOCTYPE html>
<html>
<body>
<h2>GeeksforGeeks</h2>
<!-- Finding the HTML Elements by their Id in DOM -->
<p id="intro">
A Computer Science portal for geeks.
</p>
<p>
This example illustrates the <b>getElementById</b> method.
</p>
<p id="demo"></p>
<script>
const element = document.getElementById("intro");
document.getElementById("demo").innerHTML =
"GeeksforGeeks introduction is: " + element.innerHTML;
</script>
</body>

• </html>
 Accessing field value by document object
• In this example, we are going to get the value of input text by user. Here, we are using
document.form1.name.value
• to get the value of name field. Here, document is the root element that represents the html
document.
• form1 is the name of the form.
• name is the attribute name of the input text.
• value is the property, that returns the value of the input text.
• Let's see the simple example of document object that prints name with welcome message.
<script type="text/javascript">
function printvalue(){
var name=document.form1.name.value;
alert("Welcome: "+name);
}
</script>

<form name="form1">
Enter Name:<input type="text" name="name"/>
<input type="button" onclick="printvalue()" value="print name"/>
</form>
 Javascript - document.getElementById() method
• The document.getElementById() method returns the element of specified id.
• In the previous page, we have used document.form1.name.value to get the value of the
input value.
• Instead of this, we can use document.getElementById() method to get value of the input text.
But we need to define id for the input field.
• Let's see the simple example of document.getElementById() method that prints cube of the
given number.
<script type="text/javascript">
function getcube(){
var number=document.getElementById("number").value;
alert(number*number*number);
}
</script>
<form>
Enter No:<input type="text" id="number" name="number"/><br/>
<input type="button" value="cube" onclick="getcube()"/>
</form>
 Javascript - document.getElementsByName() method
• The document.getElementsByName() method returns all the element of specified name.
• The syntax of the getElementsByName() method is given below:
• document.getElementsByName("name")
• Here, name is required.
• Example of document.getElementsByName() method
• In this example, we going to count total number of genders. Here, we are using
getElementsByName() method to get all the genders.
• <script type="text/javascript">
• function totalelements()
• {
• var allgenders=document.getElementsByName("gender");
• alert("Total Genders:"+allgenders.length);
• }
• </script>
• <form>
• Male:<input type="radio" name="gender" value="male">
• Female:<input type="radio" name="gender" value="female">

• <input type="button" onclick="totalelements()" value="Total Genders">
• </form>
 Javascript - document.getElementsByTagName() method
• The document.getElementsByTagName() method returns all the element of specified tag name.
• The syntax of the getElementsByTagName() method is given below:
document.getElementsByTagName("name")
• Here, name is required.
• Example of document.getElementsByTagName() method: we going to count total number of
paragraphs used in the document. To do this, we have called the
document.getElementsByTagName("p") method that returns the total paragraphs.
<script type="text/javascript">
function countpara(){
var totalpara=document.getElementsByTagName("p");
alert("total p tags are: "+totalpara.length); }
</script>
<p>This is a pragraph</p>
<p>Here we are going to count total number of paragraphs by getElementByTagName() method.</
p>
<p>Let's see the simple example</p>
<button onclick="countpara()">count paragraph</button>
• Output of the above example
This is a pragraph
Here we are going to count total number of paragraphs by getElementByTagName() method.
Let's see the simple example
count paragraph
• Another example of document.getElementsByTagName() method: we going to count total number of h2
and h3 tags used in the document.
<script type="text/javascript">
function counth2(){
var totalh2=document.getElementsByTagName("h2");
alert("total h2 tags are: "+totalh2.length);
}
function counth3(){
var totalh3=document.getElementsByTagName("h3");
alert("total h3 tags are: "+totalh3.length);
}
</script>
<h2>This is h2 tag</h2>
<h2>This is h2 tag</h2>
<h3>This is h3 tag</h3>
<h3>This is h3 tag</h3>
<h3>This is h3 tag</h3>
<button onclick="counth2()">count h2</button>
<button onclick="counth3()">count h3</button>
• Output of the above example
This is h2 tag
This is h2 tag
This is h3 tag
This is h3 tag
This is h3 tag
count h2 count h3
Javascript - innerHTML

• The innerHTML property can be used to write the dynamic html on the html document.
• It is used mostly in the web pages to generate the dynamic html such as registration form,
comment form, links, writing the validation message, password strength etc.
• Example of innerHTML property: we are going to create the html form when user clicks on
the button.
• In this example, we are dynamically writing the html form inside the div name having the id
mylocation. We are identifing this position by calling the document.getElementById()
method.
<script type="text/javascript" >
function showcommentform() {
var data="Name:<input type='text' name='name'><br>Comment:<br><textarea rows='5' cols='80'
></textarea>
<br><input type='submit' value='Post Comment'>";
document.getElementById('mylocation').innerHTML=data;
}
</script>
<form name="myForm">
<input type="button" value="comment" onclick="showcommentform()">
<div id="mylocation"></div>
</form>
• Javascript innerText Example: we are going to display the password strength when releases
the key after press.
<script type="text/javascript" >
function validate() {
var msg;
if(document.myForm.userPass.value.length>5){
msg="good";
}
else{
msg="poor";
}
document.getElementById('mylocation').innerText=msg;
}

</script>
<form name="myForm">
<input type="password" value="" name="userPass" onkeyup="validate()">
Strength:<span id="mylocation">no strength</span>
</form>
• Show/Hide Comment Form Example using innerHTML
<!DOCTYPE html>
<html> <head> <title>First JS</title>
<script>
var flag=true;
function commentform(){
var cform="<form action='Comment'>Enter Name:<br><input type='text' name='name'/><br/>
Enter Email:<br><input type='email' name='email'/><br>Enter Comment:<br/>
<textarea rows='5' cols='70'></textarea><br><input type='submit' value='Post Comment'/></
form>";
if(flag){
document.getElementById("mylocation").innerHTML=cform;
flag=false;
}
else{
document.getElementById("mylocation").innerHTML="";
flag=true;
} }
</script> </head>
<body>
<button onclick="commentform()">Comment</button>
<div id="mylocation"></div>
</body> </html>
 The HTML DOM Document Object
• The document object represents your web page. The HTML DOM document object is the
owner of all other objects in your web page. If you want to access any element in an HTML
page, you always start with accessing the document object.Below are some examples of how
you can use the document object to access and manipulate HTML.
 Finding HTML Elements

Method Description
document.getElementById(id) Find an element by element id
document.getElementsByTagName(name) Find elements by tag name
document.getElementsByClassName(name) Find elements by class name

• Changing HTML Elements

Property Description

element.innerHTML = new html content Change the inner HTML of an element

element.attribute = new value Change the attribute value of an HTML element

element.style.property = new style Change the style of an HTML element

Method Description

element.setAttribute(attribute, value) Change the attribute value of an HTML element


 Adding and Deleting Elements
Method Description
document.createElement(element) Create an HTML element
document.removeChild(element) Remove an HTML element
document.appendChild(element) Add an HTML element
document.replaceChild(new, old) Replace an HTML element
document.write(text) Write into the HTML output stream

 Adding Events Handlers

Method Description
document.getElementById(id).onclick = function() Adding event handler code to an onclick event
{code}

 Finding HTML Objects


• The first HTML DOM Level 1 (1998), defined 11 HTML objects, object collections, and
properties. These are still valid in HTML5.
Property Description
document.anchors Returns all <a> elements that have a name attribute
document.applets Deprecated
document.baseURI Returns the absolute base URI of the document
document.body Returns the <body> element
document.cookie Returns the document's cookie
document.doctype Returns the document's doctype
document.documentElement Returns the <html> element
document.documentMode Returns the mode used by the browser
document.documentURI Returns the URI of the document
document.domain Returns the domain name of the document server
document.domConfig Obsolete.
document.embeds Returns all <embed> elements
document.forms Returns all <form> elements
document.head Returns the <head> element
document.images Returns all <img> elements
document.implementation Returns the DOM implementation
document.inputEncoding Returns the document's encoding (character set)
document.lastModified Returns the date and time the document was updated

document.links Returns all <area> and <a> elements that have a href attribute

document.readyState Returns the (loading) status of the document


document.referrer Returns the URI of the referrer (the linking document)

document.scripts Returns all <script> elements


document.strictErrorChecking Returns if error checking is enforced
document.title Returns the <title> element
document.URL Returns the complete URL of the document
JavaScript HTML DOM Elements
• This page teaches you how to find and access HTML elements in an HTML page.
 Finding HTML Elements
• Often, with JavaScript, you want to manipulate HTML elements. To do so, you have to find the
elements first. There are several ways to do this:
 Finding HTML elements by id
 Finding HTML elements by tag name
 Finding HTML elements by class name
 Finding HTML elements by CSS selectors
 Finding HTML elements by HTML object collections
 Finding HTML Element by Id
• The easiest way to find an HTML element in the DOM, is by using the element id.
• This example finds the element with id="intro":
const element = document.getElementById("intro");
• If the element is found, the method will return the element as an object (in element).
• If the element is not found, element will contain null.
 Finding HTML Elements by Tag Name
• This example finds all <p> elements:
const element = document.getElementsByTagName("p");
 Finding HTML Elements by Class Name
• If you want to find all HTML elements with the same class name, use getElementsByClassName().
This example returns a list of all elements with class="intro".
const x = document.getElementsByClassName("intro");
 Finding HTML Elements by CSS Selectors
• If you want to find all HTML elements that match a specified CSS selector (id, class names, types,
attributes, values of attributes, etc), use the querySelectorAll() method.
This example returns a list of all <p> elements with class="intro".
const x = document.querySelectorAll("p.intro");
 Finding HTML Elements by HTML Object Collections
• This example finds the form element with id="frm1", in the forms collection, and displays all
element values:
const x = document.forms["frm1"];
let text = "";
for (let i = 0; i < x.length; i++) {
text += x.elements[i].value + "<br>";
}
document.getElementById("demo").innerHTML = text;
• The following HTML objects (and object collections) are also accessible:
• document.anchors
• document.body
• document.documentElement
• document.embeds
• document.forms
• document.head
• document.images
• document.links
• document.scripts
• document.title
JavaScript HTML DOM Elements (Nodes)

• Adding and Removing Nodes (HTML Elements)


 Creating New HTML Elements (Nodes): To add a new element to the HTML DOM, you must create the element
(element node) first, and then append it to an existing element. Example
<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
const para = document.createElement("p");
const node = document.createTextNode("This is new a paragraph");
para.appendChild(node);

const element = document.getElementById("div1");


element.appendChild(para);
</script>
• Example Explained : This code creates a new <p> element:
const para = document.createElement("p");
• To add text to the <p> element, you must create a text node first. This code creates a text node:
const node = document.createTextNode("This is a new paragraph.");
• Then you must append the text node to the <p> element:
para.appendChild(node);
• Finally you must append the new element to an existing element.
• This code finds an existing element:
const element = document.getElementById("div1");
• This code appends the new element to the existing element:
element.appendChild(para);
 Creating new HTML Elements - insertBefore(): The appendChild() method in the previous example,
appended the new element as the last child of the parent. If you don't want that you can use
the insertBefore() method: Example
• <div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
const para = document.createElement("p");
const node = document.createTextNode("This is new.");
para.appendChild(node);

const element = document.getElementById("div1");


const child = document.getElementById("p1");
element.insertBefore(para, child);
</script>
 Removing Existing HTML Elements: To remove an HTML element, use the remove() method:
• Example
• <div>
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>

<script>
const elmnt = document.getElementById("p1");
elmnt.remove();
</script>
 Removing a Child Node: For browsers that does not support the remove() method, you have
to find the parent node to remove an element: Example
• <div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
const parent = document.getElementById("div1");
const child = document.getElementById("p1");
parent.removeChild(child);
</script>
• Example Explained ; This HTML document contains a <div> element with two child nodes
(two <p> elements):
• <div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
• Find the element with id="div1":
const parent = document.getElementById("div1");
Find the <p> element with id="p1":
const child = document.getElementById("p1");
 Remove the child from the parent: parent.removeChild(child);
• Here is a common workaround: Find the child you want to remove, and use
its parentNode property to find the parent:
const child = document.getElementById("p1");
child.parentNode.removeChild(child);
 Replacing HTML Elements ; To replace an element to the HTML DOM, use
the replaceChild() method: Example
• <div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
const para = document.createElement("p");
const node = document.createTextNode("This is new.");
para.appendChild(node);
const parent = document.getElementById("div1");
const child = document.getElementById("p1");
parent.replaceChild(para, child);
</script>
JavaScript HTML DOM Collections

 The HTMLCollection Object: The getElementsByTagName() method returns


an HTMLCollection object.
• An HTMLCollection object is an array-like list (collection) of HTML elements.
• The following code selects all <p> elements in a document: Example
const myCollection = document.getElementsByTagName("p");
• The elements in the collection can be accessed by an index number.
• To access the second <p> element you can write:
myCollection[1]
Note: The index starts at 0.
 HTML HTMLCollection Length
• The length property defines the number of elements in an HTMLCollection: Example
myCollection.length
• The length property is useful when you want to loop through the elements in a collection:
• Example: Change the text color of all <p> elements:
const myCollection = document.getElementsByTagName("p");
for (let i = 0; i < myCollection.length; i++) {
myCollection[i].style.color = "red";
}
• An HTMLCollection may look like an array, but it is not.
• You can loop through the list and refer to the elements with a number (just like an array).
• However, you cannot use array methods like valueOf(), pop(), push(), or join() on an
HTMLCollection.
JavaScript HTML DOM Node Lists

 The HTML DOM NodeList Object:


• A NodeList object is a list (collection) of nodes extracted from a document. A NodeList object
is almost the same as an HTMLCollection object.
• Some (older) browsers return a NodeList object instead of an HTMLCollection for methods
like getElementsByClassName().
• All browsers return a NodeList object for the property childNodes.
• Most browsers return a NodeList object for the method querySelectorAll().
• The following code selects all <p> nodes in a document: Example
const myNodeList = document.querySelectorAll("p");
• The elements in the NodeList can be accessed by an index number.
• To access the second <p> node you can write:
myNodeList[1]
 HTML DOM Node List Length: The length property defines the number of nodes in a node
list:Example
myNodelist.length
• The length property is useful when you want to loop through the nodes in a node list:
• Example: Change the color of all <p> elements in a node list:
const myNodelist = document.querySelectorAll("p");
for (let i = 0; i < myNodelist.length; i++) {
myNodelist[i].style.color = "red";
}
 The Difference Between an HTMLCollection and a NodeList
• A NodeList and an HTMLcollection is very much the same thing.
• Both are array-like collections (lists) of nodes (elements) extracted from a document. The
nodes can be accessed by index numbers. The index starts at 0.
• Both have a length property that returns the number of elements in the list (collection).
• An HTMLCollection is a collection of document elements. While A NodeList is a collection
of document nodes (element nodes, attribute nodes, and text nodes).
• HTMLCollection items can be accessed by their name, id, or index number. But NodeList
items can only be accessed by their index number.
• An HTMLCollection is always a live collection. Example: If you add a <li> element to a list in
the DOM, the list in the HTMLCollection will also change. while A NodeList is most often
a static collection. Example: If you add a <li> element to a list in the DOM, the list in NodeList
will not change.
• The getElementsByClassName() and getElementsByTagName() methods return a live
HTMLCollection. While the querySelectorAll() method returns a static NodeList.
• The childNodes property returns a live NodeList.
 Date and Objects : Date methods let you get and set date values (years, months, days, hours,
minutes, seconds, milliseconds)
• Date Get Methods : Get methods are used for getting a part of a date. Here are the most
common (alphabetically):

Method Description
getDate() Get the day as a number (1-31)

getDay() Get the weekday as a number (0-6)

getFullYear() Get the four digit year (yyyy)

getHours() Get the hour (0-23)


getMilliseconds() Get the milliseconds (0-999)
getMinutes() Get the minutes (0-59)
getMonth() Get the month (0-11)
getSeconds() Get the seconds (0-59)
getTime() Get the time (milliseconds since January 1,
1970)
• The getTime() Method : getTime() returns the number of milliseconds since January 1,
1970:
Example:
<!DOCTYPE html> <html>
<body>
<p>The internal clock in JavaScript starts at midnight January 1, 1970.</p>
<p>The getTime() function returns the number of milliseconds since then:</p>
<p id="demo"></p>
<script>
var d = new Date();
document.getElementById("demo").innerHTML = d.getTime();
</script> </body> </html>
• The getFullYear() Method: getFullYear() returns the year of a date as a four digit number:
Example :
<script>
var d = new Date();
document.getElementById("demo").innerHTML = d.getFullYear();
</script>
• The getDay() Method : getDay() returns the weekday as a number (0-6): Example
<script>
var d = new Date();
document.getElementById("demo").innerHTML = d.getDay();
</scrip>
• Date Set Methods L Set methods are used for setting a part of a date. Here are the most
common (alphabetically):
Method Description
setDate() Set the day as a number (1-31)
setFullYear() Set the year (optionally month and day)

setHours() Set the hour (0-23)


setMilliseconds() Set the milliseconds (0-999)
setMinutes() Set the minutes (0-59)
setMonth() Set the month (0-11)
setSeconds() Set the seconds (0-59)
setTime() Set the time (milliseconds since January 1,
1970)

•The setFullYear() Method : setFullYear() sets a date object to a specific date. In this example, to
January 14, 2020: Example
<script>
var d = new Date();
d.setFullYear(2020, 0, 14);
document.getElementById("demo").innerHTML = d;
</script>
• Compare Dates : Dates can easily be compared. The following example compares today's
date with January 14, 2100: Example
var today, someday, text;
today = new Date();
someday = new Date();
someday.setFullYear(2100, 0, 14);
if (someday > today)
{
text = "Today is before January 14, 2100.";
}
else
{
text = "Today is after January 14, 2100.";
}
document.getElementById("demo").innerHTML = tex;
JavaScript - Events Handling

• JavaScript's interaction with HTML is handled through events that occur when the user or the
browser manipulates a page.
• When the page loads, it is called an event. When the user clicks a button, that click too is an
event. Other examples include events like pressing any key, closing a window, resizing a window,
etc.
• onclick Event Type: This is the most frequently used event type which occurs when a user clicks
the left button of his mouse. You can put your validation, warning etc., against this event type.
Example
<html> <head>
<script type="text/javascript">
<!—
function sayHello() {
alert("Hello World") }
//-->
</script>
</head>
<body>
<p>Click the following button and see result</p>
<form>
<input type="button" onclick="sayHello()" value="Say Hello" />
</form> </body> </html>
 JavaScript HTML DOM Events
• HTML DOM allows JavaScript to react to HTML events: Reacting to Events A JavaScript can be executed when an
event occurs, like when a user clicks on an HTML element. To execute code when a user clicks on an element, add
JavaScript code to an HTML event attribute: onclick=JavaScript
• Examples of HTML events:
 When a user clicks the mouse
 When a web page has loaded
 When an image has been loaded
 When the mouse moves over an element
 When an input field is changed
 When an HTML form is submitted
 When a user strokes a key
• In this example, the content of the <h1> element is changed when a user clicks on it:
<!DOCTYPE html>
<html> <body>

<h1 onclick="this.innerHTML = 'Ooops!'">Click on this text!</h1>


</body></html>
• In this example, a function is called from the event handler:
<!DOCTYPE html>
<html> <body>

<h1 onclick="changeText(this)">Click on this text!</h1>


<script>
function changeText(id) {
id.innerHTML = "Ooops!";
}
</script></body> </html>
• onsubmit Event type : onsubmit is an event that occurs when you try to submit a form. You
can put your form validation against this event type.
• onmouseover and onmouseout : These two event types will help you create nice effects with
images or even with text as well. The onmouseover event triggers when you bring your
mouse over any element and the onmouseout triggers when you move your mouse out from
that element. Try the following example.
<html> <head>
<script type="text/javascript">
<!—
function over() {
document.write ("Mouse Over"); }
function out() {
document.write ("Mouse Out"); }
//-->
</script> </head>
<body>
<p>Bring your mouse inside the division to see the result:</p>
<div onmouseover="over()" onmouseout="out()">
<h2> This is inside the division </h2>
</div>
</body> </html>
HTML Event Attributes

 HTML Event Attributes: To assign events to HTML elements you can use event attributes. Example
• Assign an onclick event to a button element:
<button onclick="displayDate()">Try it</button>
• In the example above, a function named displayDate will be executed when the button is clicked.
• Assign Events Using the HTML DOM: The HTML DOM allows you to assign events to HTML elements using JavaScript:
• Example: Assign an onclick event to a button element:
<script>
document.getElementById("myBtn").onclick = displayDate;
</script>
• In the example above, a function named displayDate is assigned to an HTML element with the id="myBtn".
• The function will be executed when the button is clicked.
• The onload and onunload Events
• The onload and onunload events are triggered when the user enters or leaves the page.
• The onload event can be used to check the visitor's browser type and browser version, and load the proper version of the web page
based on the information.
• The onload and onunload events can be used to deal with cookies. Example
• <body onload="checkCookies()">
• The oninput Event
• The oninput event is often to some action while the user input data.
• Below is an example of how to use the oninput to change the content of an input field. Example
• <input type="text" id="fname" oninput="upperCase()">
• The onchange Event
• The onchange event is often used in combination with validation of input fields.
• Below is an example of how to use the onchange. The upperCase() function will be called when a user changes the content of an
input field. Example
• <input type="text" id="fname" onchange="upperCase()">
• The onmouseover and onmouseout Events
• The onmouseover and onmouseout events can be used to trigger a function when the user mouses over, or out of, an HTML
element:
• Mouse Over Me
• The onmousedown, onmouseup and onclick Events
• The onmousedown, onmouseup, and onclick events are all parts of a mouse-click. First when
a mouse-button is clicked, the onmousedown event is triggered, then, when the mouse-
button is released, the onmouseup event is triggered, finally, when the mouse-click is
completed, the onclick event is triggered.
• Click Me
• Try it Yourself »
• More Examples
• onmousedown and onmouseup
Change an image when a user holds down the mouse button.
• onload
Display an alert box when the page has finished loading.
• onfocus
Change the background-color of an input field when it gets focus.
• Mouse Events
Change the color of an element when the cursor moves over it.
• HTML DOM Event Object Reference
• For a list of all HTML DOM events, look at our complete HTML DOM Event Object Reference.
• JavaScript HTML DOM EventListener
• ❮ PreviousNext ❯
• The addEventListener() method
• Example
• Add an event listener that fires when a user clicks a button:
• document.getElementById("myBtn").addEventListener("click", displayDate);
• Try it Yourself »
• The addEventListener() method attaches an event handler to the specified element.
• The addEventListener() method attaches an event handler to an element without overwriting existing
event handlers.
• You can add many event handlers to one element.
• You can add many event handlers of the same type to one element, i.e two "click" events.
• You can add event listeners to any DOM object not only HTML elements. i.e the window object.
• The addEventListener() method makes it easier to control how the event reacts to bubbling.
• When using the addEventListener() method, the JavaScript is separated from the HTML markup, for better
readability and allows you to add event listeners even when you do not control the HTML markup.
• You can easily remove an event listener by using the removeEventListener() method.

• Syntax
• element.addEventListener(event, function, useCapture);
• The first parameter is the type of the event (like "click" or "mousedown" or any other HTML DOM Event.)
• The second parameter is the function we want to call when the event occurs.
• The third parameter is a boolean value specifying whether to use event bubbling or event capturing. This
parameter is optional.
• Note that you don't use the "on" prefix for the event; use "click" instead of "onclick".
• Add an Event Handler to an Element
• Example
• Alert "Hello World!" when the user clicks on an element:
• element.addEventListener("click", function(){ alert("Hello World!"); });
• Try it Yourself »
• You can also refer to an external "named" function:
• Example
• Alert "Hello World!" when the user clicks on an element:
• element.addEventListener("click", myFunction);

function myFunction() {
alert ("Hello World!");
}
• Try it Yourself »
• ADVERTISEMENT
• Add Many Event Handlers to the Same Element
• The addEventListener() method allows you to add many events to the same element, without overwriting existing events:
• Example
• element.addEventListener("click", myFunction);
element.addEventListener("click", mySecondFunction);

• Try it Yourself »
• You can add events of different types to the same element:
• Example
• element.addEventListener("mouseover", myFunction);
element.addEventListener("click", mySecondFunction);
element.addEventListener("mouseout", myThirdFunction);
• Try it Yourself »
• Add an Event Handler to the window Object
• The addEventListener() method allows you to add event listeners on any HTML DOM object such as HTML elements, the HTML document, the window object,
or other objects that support events, like the xmlHttpRequest object.
• Example
• Add an event listener that fires when a user resizes the window:
• window.addEventListener("resize", function(){
document.getElementById("demo").innerHTML = sometext;
});
• Try it Yourself »
• Passing Parameters
• When passing parameter values, use an "anonymous function" that calls the specified function with the parameters:
• Example
• element.addEventListener("click", function(){ myFunction(p1, p2); });
• Try it Yourself »
• Event Bubbling or Event Capturing?
• There are two ways of event propagation in the HTML DOM, bubbling and capturing.
• Event propagation is a way of defining the element order when an event occurs. If you have a <p> element inside a <div>
element, and the user clicks on the <p> element, which element's "click" event should be handled first?
• In bubbling the inner most element's event is handled first and then the outer: the <p> element's click event is handled first,
then the <div> element's click event.
• In capturing the outer most element's event is handled first and then the inner: the <div> element's click event will be
handled first, then the <p> element's click event.
• With the addEventListener() method you can specify the propagation type by using the "useCapture" parameter:
• addEventListener(event, function, useCapture);
• The default value is false, which will use the bubbling propagation, when the value is set to true, the event uses the
capturing propagation.
• Example
• document.getElementById("myP").addEventListener("click", myFunction, true);
document.getElementById("myDiv").addEventListener("click", myFunction, true);
• Try it Yourself »
• The removeEventListener() method
• The removeEventListener() method removes event handlers that have been attached with the addEventListener() method:
• Example
• element.removeEventListener("mousemove", myFunction);
• Try it Yourself »
• HTML DOM Event Object Reference
• For a list of all HTML DOM events, look at our complete HTML DOM Event Object Reference.
• Test Yourself With Exercises
• Exercise:
• Use the eventListener to assign an onclick event to the <button> element.
• <button id="demo"></button> <script> document.getElementById("demo").("", myFunction);
</script>
HTML - JavaScript

• A script is a small piece of program that can add interactivity to our website. For example, a script
could generate a pop-up alert box message, or provide a dropdown menu. This script could be
written using JavaScript or VBScript.
• We can write various small functions, called event handlers using any of the scripting language
and then we can trigger those functions using HTML attributes. Now-a-days, only JavaScript and
associated frameworks are being used by most of the web developers,
• We can keep JavaScript code in a separate file and then include it wherever it's needed, or you can
define functionality inside HTML document itself.
 External JavaScript: If you are going to define a functionality which will be used in various
HTML documents then it's better to keep that functionality in a separate JavaScript file and then
include that file in your HTML documents.
• A JavaScript file will have extension as .js and it will be included in HTML files using <script>
tag. Example: we define a small function using JavaScript in script.js which has following code−
function Hello() {
alert("Hello, World");}
• Now let's make use of the above external JavaScript file in our following HTML document−
<html> <head> <title>Javascript External Script</title>
<script src = "/html/script.js" type = "text/javascript"/></script> </head>
<body> <input type = "button" onclick = "Hello();" name = "ok" value = "Click Me" />
</body> </html>
• This will produce the following result, where you can try to click on the given button
 Internal Script: We can write our script code directly into our HTML document. Usually we keep
script code in header of the document using <script> tag, otherwise there is no restriction and you can
put your source code anywhere in the document but inside <script> tag. Example:
<html> <head>
<title>JavaScript Internal Script</title>
<script type = "text/JavaScript">
function Hello() {
alert("Hello, World"); }
</script> </head>
<body> <input type = "button" onclick = "Hello();" name = "ok" value = "Click Me" />
</body></html>
• This will produce the following result, where you can try to click on the given button
 Event Handlers: Event handlers are nothing but simply defined functions which can be called against
any mouse or keyboard event. We can define our business logic inside our event handler which can
vary from a single to 1000s of line code.
• Following example to write an event handler. Let's write one simple function EventHandler() in the
header of the document. We call this function when user brings mouse over a paragraph.
<html> <head> <title>Event Handlers Example</title>
<script type = "text/JavaScript">
function EventHandler() {
alert("I'm event handler!!"); }
</script> </head>
<body>
<p onmouseover = "EventHandler();">Bring your mouse here to see an alert</p> </body> </html>
• Now This will produce the following result. Bring your mouse over this line and see the result.
JavaScript Libraries

• A JavaScript library is a collection of classes, methods, and pre-written functions that a developer can
use in their web development projects. It makes code reusable and simplifies the development
process. It is also used because it provides cross-browser compatibility and saves time & effort.
 React: React is one of the most popular, efficient, and powerful open-source JavaScript library for
building dynamic and interactive user interfaces. React JS is not a framework, it is just a library
developed by Facebook.
• Why learn React JS?
• ReactJS is famous for its component-based architecture and virtual DOM which makes it highly
efficient in rendering user interface and ensuring optimal performance.
• Due to its reusable components, It is very helpful in efficient development and maintenance of large-
scale applications.
• ReactJS has a vast ecosystem and community which makes the development very easy and ensures
performance optimization.
• ReactJS Advantages
 Composable: We can divide these codes and put them in custom components. Then we can utilize
those components and integrate them into one place.
 Declarative: In ReactJS, the DOM is declarative. We can make interactive UIs by changing the state
of the component and ReactJS takes care of updating the DOM according to it.
 SEO Friendly: ReactJS affects the SEO by giving you a SPA (Single Page Application) which
requires Javascript to show the content on the page which can be rendered and indexed.
 Community: ReactJS has a huge community because of it’s demand each company wants to work
with ReactJS. Companies like Meta, Netflix, etc built on ReactJS.
 Easy to learn: HTML-like syntax of JSX make you comfortable with the codes of React, it only
requires to need a basic knowledge of HTML, CSS, and JS fundamentals to start working with it.
JavaScript Frameworks
• Javascript frameworks are essential tools for creating a web application. They provide built-in
components that help in creating robust and interactive web components or applications.
• They simplified the structure of project and provides blueprints of the project.
• Also, it simplifies HTML document traversal. They provide powerful and efficient methods for
handling events like click, double click mouseover, etc.
• They also provide two-way data binding.
 AngularJS: AngularJS was developed in 2008-2009 by Misko Hevery and Adam Abrons and is
now maintained by Google. AngularJS is a Javascript open-source front-end framework.
• Introduction to AngularJS:
• AngularJS is a Javascript open-source front-end structural framework that is mainly used to
develop single-page web applications(SPAs).
• It is a continuously growing and expanding framework which provides better ways for
developing web applications.
• It changes the static HTML to dynamic HTML. Its features like dynamic binding and
dependency injection eliminate the need for code that we have to write otherwise.
• AngularJS is rapidly growing and because of this reason, we have different versions of
AngularJS with the latest stable being 1.7.9.
• It is also important to note that Angular is different from AngularJS. It is an open-source
project which can be freely used and changed by anyone. It extends HTML attributes with
Directives, and data is bound with HTML
• Why use AngularJS?
 Easy to work with: All you need to know to work with AngularJS is the basics of HTML,
CSS, and Javascript, not necessary to be an expert in these technologies.
 Time-saving: AngularJs allows us to work with components and hence we can use them again
which saves time and unnecessary code.
 Ready to use a template: AngularJs is mainly plain HTML, and it mainly makes use of the
plain HTML template and passes it to the DOM and then the AngularJS compiler. It traverses
the templates and then they are ready to use.
 Directives: AngularJS’s directives allow you to extend HTML with custom elements and
attributes. This enables you to create reusable components and define custom behaviors for
your application. Directives make it easier to manipulate the DOM, handle events, and
encapsulate complex UI logic within a single component.
• AngularJS Expressions: Expressions in AngularJS are used to bind application data to
HTML. The expressions are resolved by AngularJS and the result is returned back to where
the expression is written.
• The expressions in AngularJS are written in double braces: {{ expression }}.
• They behave similar to ng-bind directives: ng-bind=”expression”.
• Syntax:
{
{ expression }
}
• Example 1: This example displays the name that we feed in the ng-init directive.
<!DOCTYPE html> <html> <head>
<script src= "https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> </script>
<title>AngularJS Expression</title> </head>
• <body style="text-align:center">
<h1 style="color:green">GeeksforGeeks</h1>
<h3>AngularJS Expressions</h3>
<div ng-app="“ ng-init="name='GeeksforGeeks'">
<p> {{ name }} is a portal for geeks.</p>
</div> </body> </html>
• Eg.2: This example displays the content of the object that we feed in the ng-init directive.
<!DOCTYPE html> <html> <head>
<script src= "https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> </script>
<title>AngularJS Expression</title> </head>
<body>
<h1 style="color:green"> GeeksforGeeks </h1>
<h3>AngularJS Expressions</h3>
<div ng-app="“ ng-init="sort={one:'quick sort', two:'merge sort', three:'bubble sort'}">
<p> Sorting Algorithms:</p>
<ul> <li>{{ sort.one }}</li> <li>{{ sort.two }}</li> i>{{ sort.three }}</li>
</ul>
</div>
</body> </html>
 NodeJS: NodeJS is an open-source and cross-platform runtime environment built on Chrome’s V8
JavaScript engine for executing JavaScript code outside of a browser.
• It provides an event-driven, non-blocking (asynchronous) I/O and cross-platform runtime environment
for building highly scalable server-side applications using JavaScript.
• Why to learn Node?: Node is famous due to the use of JavaScript across the entire stack, asynchronous
programming model for handling multiple requests simultaneously, fast execution due to the V8 engine,
large and active community support, scalability for real-time applications, cross-platform compatibility,
and its role in enabling full-stack development. All these features make Node very fast and popular.
• Node Advantages
 Easy Scalability: Node JS is built upon Chrome V8’s engine powered by Google. It allows Node to
provide a server-side runtime environment that compiles and executes JavaScript at lightning speeds.
 Real time web apps: Today the web has become much more about interaction. Users want to interact
with each other in real-time. Chat, gaming, constant social media updates, collaboration tools,
eCommerce websites, real-time tracking apps, marketplace- each of these features requires real-time
communication between users, clients, and servers across the web.
 Fast Suite: As we have discussed that Node is highly scalable and lightweight that’s why it’s a heavy
favorite for microservice architectures. In a nutshell, microservice architectures mean breaking down the
application into isolated and independent services.
 Easy to learn and code: No matter what language you are using for the backend application you’re
gonna need JavaScript for front-end anyway so instead of spending your time learning a server-side
language such as Php, Java or Ruby on Rails, you can spend all your efforts in learning JS and mastering
in it.
 Data Streaming: Node comes to the rescue since it’s good at handling such an I/O process which allows
users to transcode media files simultaneously while they are being uploaded. It takes less time compared
to other data processing methods for processing data.
 Corporate Support: It’s an independent community aimed at facilitating the development of Node core
tools. The foundation of Node was formed to speed up the development of Node, and it was intended to
allow broad adoption of it.
 Express.js: Express JS is a small framework that works on top of Node web server functionality to
simplify its APIs and add helpful new features. It makes it easier to organize your application’s
functionality with middleware and routing. It adds helpful utilities to Node HTTP objects and
facilitates the rendering of dynamic HTTP objects.
• Why learn Express ?;
 Express makes the development of Node application very easy and it is very simple to use.
 It provides a simple and efficient way to build web applications and APIs using JavaScript.
 It helps Node to handling routes, requests, and responses, making it easier for you to create robust
and scalable applications.
 As it is very flexible, lightweight and easy to learn and contains a ton of middleware option making it
an excellent choice to learn and use Express in your application.
• Express Advantages:
 Simplicity and Minimalism: Express JS has very simple design, that makes it easy to learn and use.
With its simple structure you can quickly set up a server, define routes, and handle HTTP requests
which makes it an excellent choice for building web applications efficiently.
 Flexibility and Customization: Express JS is a flexible framework that allows you to structure the
application based on your preferences. It does have a strict application architecture so you can
organize your code according to your preference.
 Middleware Ecosystem: Express JS has a large numbers of middleware that can be easily integrated
into applications. Middleware functions increases the functionality of Express by allowing you to
handle various tasks such as authentication, logging, and error handling.
 Scalability: Express JS is designed to be lightweight and scalable, which makes it suitable for
building both small projects and large-scale applications. It is asynchronous and has event-driven
architecture which allows you to handle a large number of requests.
 Active Community Support: Express JS has a large active community who contribute to its growth
and improvement. Because of them the framework is regularly updated and well-documented.

You might also like