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

JavaScript Notes2

The HTML Document Object Model (DOM) is a tree-like structure that represents a web page, allowing JavaScript to access and manipulate HTML elements dynamically. It enables the creation of interactive web pages by responding to user actions and updating content without reloading the page. Key methods for interacting with the DOM include getElementById, getElementsByClassName, and getElementsByTagName, which facilitate the retrieval and modification of elements based on their identifiers.

Uploaded by

Nitisha
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)
2 views22 pages

JavaScript Notes2

The HTML Document Object Model (DOM) is a tree-like structure that represents a web page, allowing JavaScript to access and manipulate HTML elements dynamically. It enables the creation of interactive web pages by responding to user actions and updating content without reloading the page. Key methods for interacting with the DOM include getElementById, getElementsByClassName, and getElementsByTagName, which facilitate the retrieval and modification of elements based on their identifiers.

Uploaded by

Nitisha
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

DOM

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:

HTML DOM is a standard object model and programming interface


for HTML documents. HTML DOM is a way to represent the webpage
in a structured hierarchical way so that it will become easier for
programmers and users to glide through the document.
With HTML DOM, we can easily access and manipulate tags, IDs,
classes, attributes, or elements of HTML using commands or methods
provided by the document object.
Using DOM JavaScript we get access to HTML as well as CSS of the
web page and can also modify the behaviour of the HTML elements.

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.


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

JavaScript HTML DOM Document


The HTML DOM document object is the owner of all other objects in your
web page.

The HTML DOM Document Object

The document object represents 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

[Link](id) Find an element by element id

[Link](name) Find elements by tag name

[Link](name) Find elements by class name

Methods of Document Object


DOM provides various methods that allows users to interact with and
manipulate the document. Some commonly used DOM methods are:
write(“string”): Writes the given string on the document.
HTML DOM write() Method
The•• write() method in HTML is used to write some content or JavaScript code in
a Document. This method is mostly used for testing purposes. It is used to delete
all the content from the HTML document and inserts the new content. It is also
used to give additional text to an output that is opened by the [Link]()
method. This method is quite similar to writeln() method.
Syntax:
[Link]( exp1, exp2, exp3, ... )
Parameters: This method contains many parameters which are optional. All the
expression arguments (exp1, exp2, … ) can be listed and displayed in the order of
occurrence.
Example 1:
<!DOCTYPE html>
<html>

<head>
<title>DOM write() Method</title>
<style>
body {
text-align:center;
}
h1 {
color:green;
}
</style>
</head>
<body>
<h1>welcome to ambedkar institute of technology</h1>
<h2>DOM write() Method</h2>
<script>
[Link]("dept of mca; ");
[Link]
("A computer science portal ")
</script>
</body>
</html>

Example 2:
<!DOCTYPE html>
<html>

<head>
<title>DOM write() Method</title>
<style>
body {
text-align:center;
}
h1 {
color:green;
}
</style>
</head>

<body>
<h1>Welcome to [Link]</h1>
<h2>DOM write() Method</h2>
<button type="button" onclick="mca()">
Submit
</button>
<script>
function mca() {
[Link]
('<center>Master of Computer Applications</center>');
}
</script>
</body>
</html>

• getElementById(): returns the element having the given id value.

HTML DOM getElementById() Method



The•• getElementById() method returns the elements that have given an ID
which is passed to the function. This function is a widely used HTML
DOM method in web designing to change the value of any particular element
or get a particular element. If the passed ID to the function does not exist then
it returns null.
Note: Each ID needs to be unique. If there are multiple elements with the
same ID, only the first one will be returned.
Syntax:
[Link]( element_ID )
Parameter:
This function accepts single parameter element_ID which is used to hold the
ID of the element.
Return Value:
It returns the object of the given ID. If no element exists with the given ID
then it returns null.
Example 1

<!DOCTYPE html>
<html>

<head>
<title>
DOM getElementById() Method
</title>
<script>
// Function to change the color of element
function mca() {
var demo = [Link]("mca");
[Link] = "green";
}
</script>
</head>

<body style="text-align:center">
<h1 id="mca">master of computer applications</h1>
<h2>DOM getElementById() Method</h2>

<!-- Click on the button to change color -->


<input type="button" onclick="mca()"
value="Click here to change color" />
</body>
</html>

• getElementsByName(): returns all the elements having the given


name value.

HTML DOM getElementsByName() Method



The•• getElementsByName() method returns collection of all elements of
particular document by name. This collection is called node list and each
element of the node list can be visited with the help of the index.
Syntax:
[Link](name)
Parameter:This function accepts name of document.
Return Type:This function returns collection of elements. By using the build
in method length we can find the total number of elements presents inside
that particular element. Below example illustrates it clearly.
Example 1:
<!DOCTYPE html>
<html>
<head>
<title>DOM getElementsByName()</title>
<style>
body {
text-align: center;
}

h1 {
color: green;
}
</style>
<script>
// creating geeks function to display
// number of elements at particular name
function mca() {

// taking list of elements under name ga


var x = [Link]("mc");

// printing number of elements inside alert tag


alert("Total element with name mc are: " + [Link]);
}
</script>
</head>
<body>
<h1>master of Computer Applications</h1>
<h2>DOM getElementsByName() Method</h2>

<!-- creating tag with name mc -->


<h4 name="mc">ait</h4>
<h4 name="mc">mca</h4>
<h4 name="mc">1 sem</h4>

<input type="button" onclick="mca()"


value="Click here" />
</body>
</html>

Example 2:
<!DOCTYPE html>
<html>

<head>
<title>DOM getElementsByName()</title>
<style>
body {
text-align: center;
}

h1 {
color: green;
}
</style>
<script>
// creating geeks function to display
// elements at particular name
function mca() {

// This line will print entered result


alert([Link]("mc")[0].value);

}
</script>
</head>

<body>
<h1>Ambedkar Institute of Technology</h1>
<h2>DOM getElementsByName() Method</h2>

<!-- This will create an input tag-->


<input type="text" name="mc" />
<br>
<br>
<!-- function will be called when we
click on this button-->
<input type="button" onclick="mca()"
value="Click here" />
<p></p>
</body>
</html>

• getElementsByClassName(): returns all the elements having the


given class name.

HTML DOM getElementsByClassName() Method



The•• getElementsByClassName() method in Javascript returns an object
containing all the elements with the specified class names in the document
as objects. Each element in the returned object can be accessed by its index.
The index value will start with 0. This method can be called upon by any
individual element to search for its descendant elements with the specified
class names.
Syntax:
[Link](classnames);
Parameters: This is a required method that takes only one parameter, which
is a string containing space-separated class names of the elements that are
to be searched for. For searching with multiple class names, it must be
separated with space.

Example 1: This example describes the getElementsByClassName() method


for getting access to an HTML element by its class name.
<!DOCTYPE html>
<html>
<head>
<title>
DOM getElementByClassName() Method
</title>
<style>
h1 {
color: green;
}

body {
text-align: center;
}

.example {
padding: 10px;
margin: auto;
margin-top: 10px;
border: 1px solid black;
width: 300px;
}
</style>
</head>

<body>
<h1>
[Link] Institute of TEchnology
</h1>
<h2>
DOM getElementByClassName() Method
</h2>
<div>
<h4 class="example">
div1
</h4>
<h4 class="yellowBorder example">
div2
</h4>
<h4 class="greenBorder example">
div3
</h4>
<h4 class="example">
div4
</h4>
</div>
<script>
[Link]('greenBorder example')[0]
.[Link] = "10px solid green";
[Link]('yellowBorder example')[0]
.[Link] = "10px solid yellow";
</script>
</body>

</html>
Example 2:
This example describes the use of
the [Link]() method that accesses all the 3
button classes with the specific color & alters the color of the button on
clicked & the last button resets all the above 3 buttons to their initial state.
<!DOCTYPE html>
<html>
<head>
<title>
DOM getElementByClassName() Method
</title>
<style>
h1 {
color: green;
}

body {
text-align: center;
}

button {
background-color: black;
color: white;
width: 300px;
padding: 10px;
margin: 10px;
cursor: pointer;
}
</style>
</head>
<body>
<h1> [Link] Institute of TEchnology
</h1>
<h2>
DOM getElementByClassName() Method
</h2>
<div>
<button onclick="red()"
class="black red">
Click to change to red button
</button>
<br>
<button onclick="blue()"
class="black blue">
Click to change to blue button
</button>
<br>
<button onclick="yellow()"
class="black yellow">
Click to change to yellow button
</button>
<br>
<button onclick="black()">
Click to change to all buttons to initial state
</button>
</div>
<script>
function red() {
[Link]('red')[0]
.[Link] = 'red';
}

function blue() {
[Link]('blue')[0]
.[Link] = 'blue';
}

function yellow() {
[Link]('yellow')[0]
.[Link] = 'yellow';
}

function black() {
var elements =
[Link]('black');
for(var i = 0; i < [Link]; i++) {
elements[i].[Link] = 'black';
}
}
</script>
</body>
</html>

HTML DOM getElementsByTagName() Method



The•• getElementsByTagName() method in the HTML DOM allows the selection
of elements by their tag name. It returns a collection of elements with the
specified tag name within the specified document or element.
To extract any info just iterate through all the elements using the length
property.
Syntax:
let elements = [Link](name);
Parameters:
• elements is a collection of all the found elements in the order they
appear with the given tag name.
• name is a string representing the name of the elements. The special
string “*” represents all elements.
Example 1: In this example, we will change the background color of the
element using [Link]() function.

<!DOCTYPE html>
<html>

<head>
<title>DOM getElementsByTagName() Method</title>
</head>

<body style="text-align: center">


<p> [Link] Institute of TEchnology
</p>
<button onclick="mc()">Try it</button>
<script>
function mc() {
let doc = [Link]("p");
doc[0].[Link] = "green";
doc[0].[Link] = "white";
}
</script>
</body>
</html>
Explanation:
• In the above example we defines an HTML document with a title,
heading, paragraph, and a button.
• When the button is clicked, the mc() function is called, which
modifies the style of the first paragraph.
• It uses [Link]() to select all <p>
elements and applies style changes to the first one.
• The paragraph’s background color is set to green, and its text
color is set to white.
Example 2: In this example, we will change the properties of multiple
elements using [Link]() function.
<!DOCTYPE html>
<html>

<head>
<title>
DOM getElementsByTagName() Method
</title>
</head>

<body style="text-align: center">


<p>This is the first paragraph.</p>
<p>This is the second paragraph.</p>
<p>This is the third paragraph.</p>
<button onclick="geek()">Try it</button>
<script>
function geek() {
let doc =
[Link](
"p"
);
let i;
for (i = 0; i < [Link]; i++) {
doc[i].[Link] =
"green";
doc[i].[Link] = "white";
}
}
</script>
</body>
</html>
DOM Forms

Example1:
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm() {
let x = [Link]["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}
</script>
</head>
<body>

<h2>JavaScript Validation</h2>

<form name="myForm" action="/action_page.php" onsubmit="return


validateForm()" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
</body>
</html>

Data Validation
Data validation is the process of ensuring that user input is clean, correct,
and useful.

Typical validation tasks are:


• has the user filled in all required fields?
• has the user entered a valid date?
• has the user entered text in a numeric field?

Most often, the purpose of data validation is to ensure correct user input.

Validation can be defined by many different methods, and deployed in many


different ways.

Server side validation is performed by a web server, after input has been
sent to the server.

Client side validation is performed by a web browser, before input is sent


to a web server.

HTML Constraint Validation


HTML5 introduced a new HTML validation concept called constraint
validation.

HTML constraint validation is based on:

• Constraint validation HTML Input Attributes


• Constraint validation CSS Pseudo Selectors
• Constraint validation DOM Properties and Methods

Constraint Validation HTML Input


Attributes
Attribute Description

disabled Specifies that the input element should be disabled

max Specifies the maximum value of an input element


min Specifies the minimum value of an input element

pattern Specifies the value pattern of an input element

required Specifies that the input field requires an element

type Specifies the type of an input element

For a full list, go to HTML Input Attributes.

Constraint Validation CSS Pseudo Selectors


Selector Description

:disabled Selects input elements with the "disabled" attribute specified

:invalid Selects input elements with invalid values

:optional Selects input elements with no "required" attribute specified

:required Selects input elements with the "required" attribute specified

:valid Selects input elements with valid values

Event handling in JavaScript


JavaScript Events are actions or occurrences that happen in the
browser. They can be triggered by various user interactions or by the
browser itself.
Common events include mouse clicks, keyboard presses, page loads, and
form submissions. Event handlers are JavaScript functions that respond to
these events, allowing developers to create interactive web applications.
Syntax:
<HTML-element Event-Type = "Action to be performed">
HTML Events

An HTML event can be something the browser does, or something a user


does.

Here are some examples of HTML events:

• An HTML web page has finished loading


• An HTML input field was changed
• An HTML button was clicked

Often, when events happen, you may want to do something.

JavaScript lets you execute code when events are detected.

HTML allows event handler attributes, with JavaScript code, to be added


to HTML elements.

With single quotes:

<element event='some JavaScript'>

With double quotes:

<element event="some JavaScript">


JavaScript Event Handlers

Event handlers can be used to handle and verify user input, user actions,
and browser actions:

• Things that should be done every time a page loads


• Things that should be done when the page is closed
• Action that should be performed when a user clicks a button
• Content that should be verified when a user inputs data
• And more ...

Many different methods can be used to let JavaScript work with events:

• HTML event attributes can execute JavaScript code directly


• HTML event attributes can call JavaScript functions
• You can assign your own event handler functions to HTML elements
• You can prevent events from being sent or being handled

Common JavaScript Events


• onclick: Triggered when an element is clicked.
• onmouseover: Fired when the mouse pointer moves over an
element.
• onmouseout: Occurs when the mouse pointer leaves an element.
• onkeydown: Fired when a key is pressed down.
• onkeyup: Fired when a key is released.
• onchange: Triggered when the value of an input element changes.
• onload: Occurs when a page has finished loading.
• onsubmit: Fired when a form is submitted.
• onfocus: Occurs when an element gets focus.
• onblur: Fired when an element loses focus.

Example 1: onclick() event


<!DOCTYPE html>
<html>
<body>
<h1>JavaScript HTML Events</h1>
<h2>The onclick Attribute</h2>

<button
onclick="[Link]('demo').innerHTML=Date()">The time
is?</button>

<p id="demo"></p>

</body>
</html>
Example 2:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript HTML Events</h1>
<h2>The onclick Attribute</h2>

<button onclick="[Link]=Date()">The time is?</button>

</body>
</html>

Example 3:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript HTML Events</h1>
<h2>The onclick Attribute</h2>

<p>Click the button to display the date.</p>


<button onclick="displayDate()">The time is?</button>

<script>
function displayDate() {
[Link]("demo").innerHTML = Date();
}
</script>

<p id="demo"></p>

</body>
</html>

Onload event:
<html>
<head>Javascript Events</head>
</br>
<body onload="[Link]('Page successfully loaded');">
<script>
<!--
[Link]("The page is loaded successfully");
//-->
</script>
</body>
</html>

Onfocus event
<html>
<head> Javascript Events</head>
<body>
<h2> Enter something here</h2>
<input type="text" id="input1" onfocus="focusevent()"/>
<script>
<!--
function focusevent()
{
[Link]("input1").[Link]="
aqua";
}
//-->
</script>
</body>
</html>

Keydown Event
<html>
<head> Javascript Events</head>
<body>
<h2> Enter something here</h2>
<input type="text" id="input1" onkeydown="keydownevent()"/>
<script>
<!--
function keydownevent()
{
[Link]("input1");
alert("Pressed a key");
}
//-->
</script>
</body>
</html>

MouseOver Event
<html>
<head>
<h1> Javascript Events </h1>
</head>
<body>
<script language="Javascript" type="text/Javascript">
<!--
function mouseoverevent()
{
alert("This is JavaTpoint");
}
//-->
</script>
<p onmouseover="mouseoverevent()"> Keep cursor over me</p>
</body>
</html>
Onchange( ) Event
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript HTML Events</h1>
<h2>The onchange Attribute</h2>

Enter your name: <input type="text" id="fname"


onchange="upperCase()">
<p>When you leave the input field, a function transforms the input to
upper case.</p>

<script>
function upperCase() {
const x = [Link]("fname");
[Link] = [Link]();
}
</script>
</body>
</html>

Onblur() Event
Description

The onblur event occurs when an HTML element loses focus.

The onblur event is often used on input fields.

The onblur event is often used with form validation (when the user leaves a
form field).

<!DOCTYPE html>
<html>
<body>
<h1>HTML DOM Events</h1>
<h2>The blur Event</h2>

<p>This example assigns an "onblur" event to an input element.</p>

<p>Write in the input field and click outside the field to lose focus
(blur).</p>
<input type="text" onblur="myFunction()">
<script>
function myFunction() {
alert("Input field lost focus.");
}
</script>
</body>
</html>

You might also like