0% found this document useful (0 votes)
9 views

Javascript Module 4 Notes

The document explains the Document Object Model (DOM) and how JavaScript interacts with HTML elements, allowing for dynamic changes to the web page. It details various collections such as anchors, links, and images, along with their properties and methods for accessing and modifying these elements. Additionally, it covers the creation of Date objects and basic string handling in JavaScript.

Uploaded by

suryasahoo396
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)
9 views

Javascript Module 4 Notes

The document explains the Document Object Model (DOM) and how JavaScript interacts with HTML elements, allowing for dynamic changes to the web page. It details various collections such as anchors, links, and images, along with their properties and methods for accessing and modifying these elements. Additionally, it covers the creation of Date objects and basic string handling in JavaScript.

Uploaded by

suryasahoo396
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/ 29

Document and its associated objects

Document is just the web page.


Objects are elements.
For ex:<head></head> is an object.
<body></body> is an object.
<p></p> is an object.

The way document content is accessed and modified is called


the Document Object Model, or DOM.
Use the DOM when interact with web page.

With the object model, JavaScript gets all the power it needs
to create dynamic HTML:

• 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 andattributes
• JavaScript can react to all existing HTML events in the page
• JavaScript can create new HTML events in the page

The following properties and methods can be used on HTML documents:

• anchor
• Link
• Area
• Image
• Applet
• Layer

• anchor
The anchors collection returns a collection of all <a>
elements in the document that have a name attribute.
Ex:
Output:

After clicking on button

Syntax
document.anchors

Properties
Property Description

Length Returns the number of <a> elements in the collection.

Note: This property is read-only

Methods
Method Description

[index] Returns the <a> element from the collection with the specified index
(starts at 0).
Note: Returns null if the index number is out of range

item(index) Returns the <a> element from the collection with the specified index
(starts at 0).

Note: Returns null if the index number is out of range

namedItem(id) Returns the <a> element from the collection with the specified id.

Note: Returns null if the id does not exist

Example
Get the HTML content of the first <a> element in the document:

var x = document.anchors[0].innerHTML;

The result of x will be:

HTML Tutorial

<html>
<body>

<a name="html">HTML Tutorial</a><br>


<a name="css">CSS Tutorial</a><br>
<a name="xml">XML Tutorial</a><br>

<p>Click the button to display the HTML content of the first anchor in the
document.</p>

<input type=”button” value=”show” onclick="myFunction()">Try it


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

<script>
function myFunction() {
var x = document.anchors[0].innerHTML;
document.getElementById("demo").innerHTML = x;
}
</script>

</body>
</html>
• Link

The links collection returns a collection of all links in the document.


The links in the collection represents <a> elements and/or
<area> elements with a href attribute.

If the element is missing the href attribute, nothing is returned.

Ex:

Output:

After clicking on button

Syntax
document.links
Properties
Property Description

Length Returns the number of <a> and/or <area> elements in the collection.

Note: This property is read-only

Methods
Method Description

[index] Returns the <a> and/or <area> element from the collection with the
specified index (starts at 0).

Note: Returns null if the index number is out of range

item(index) Returns the <a> and/or <area> element from the collection with the
specified index (starts at 0).

Note: Returns null if the index number is out of range

namedItem(id) Returns the <a> and/or <area> element from the collection with the
specified id.

Note: Returns null if the id does not exist

More Examples
<html>
<body>

<imgsrc ="planets.gif" width="145" height="126" alt="Planets" usemap ="#planetmap">

<map name="planetmap">
<area shape="rect" coords="0,0,82,126" href="sun.htm" alt="Sun">
<area shape="circle" coords="90,58,3" href="mercur.htm" alt="Mercury">
<area shape="circle" coords="124,58,8" href="venus.htm" alt="Venus">
</map>

<p>
<a href="/html/default.asp">HTML</a><br>
<a href="/css/default.asp">CSS</a>
</p>

<p>Click the button to display the URL of the first link (index 0) in the document.</p>

<input type=”button” onclick="myFunction()">Try it

<p id="demo"></p>
<script>
function myFunction() {
var x = document.links[0].href;
document.getElementById("demo").innerHTML = x;
}
</script>

</body>
</html>

Get the URL of the first link (index 0) in the document:

var x = document.links.item(0).href;

The result of x will be:

sun.htm

<html>
<body>

<imgsrc ="planets.gif" width="145" height="126" alt="Planets" usemap


="#planetmap">

<map name="planetmap">
<area shape="rect" coords="0,0,82,126" href="sun.htm" alt="Sun">
<area shape="circle" coords="90,58,3" href="mercur.htm"
alt="Mercury">
<area shape="circle" coords="124,58,8" href="venus.htm" alt="Venus">
</map>

<p>
<a href="/html/default.asp">HTML</a><br>
<a href="/css/default.asp">CSS</a>
</p>

<p>Click the button to display the URL of the first link (index 0) in the
document.</p>

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
var x = document.links.item(0).href;
document.getElementById("demo").innerHTML = x;
}
</script>

</body>
</html>
Example
namedItem(id)

Get the URL of the element with id="myLink" in the document:

var x = document.links.namedItem("myLink").href;

The result of x will be:

default.asp

<html>
<body>

<imgsrc ="planets.gif" width="145" height="126" alt="Planets" usemap


="#planetmap">

<map name="planetmap">
<area shape="rect" coords="0,0,82,126" href="sun.htm" alt="Sun">
<area shape="circle" coords="90,58,3" href="mercur.htm"
alt="Mercury">
<area shape="circle" coords="124,58,8" href="venus.htm" alt="Venus">
</map>

<p>
<a id="myLink" href="/html/default.asp">HTML</a><br>
<a href="/css/default.asp">CSS</a>
</p>

<p>Click the button to display the URL of the element with


id="myLink".</p>

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
var x = document.links.namedItem("myLink").href;
document.getElementById("demo").innerHTML = x;
}
</script>

</body>
</html>
Example
Add a red border to the first link in the document:

document.links[0].style.border = "5px solid red";


<html>
<body>

<p>
<a href="/html/default.asp">HTML</a><br>
<a href="/css/default.asp">CSS</a>
</p>

<p>Click the button to add a red border to the first link in the
document.</p>

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
document.links[0].style.border = "5px solid red";
}
</script>

</body>
</html>
Example
Loop through all links in the document, and output the URL (href) of each link:

var x = document.links;
var txt = "";
var i;
for (i = 0; i<x.length; i++) {
txt = txt + x[i].href + "<br>";
}
The result of txt will be:https

sun.htm
mercur.htm
venus.htm
default.asp
default.asp

<html>
<body>

<imgsrc ="planets.gif" width="145" height="126" alt="Planets" usemap


="#planetmap">

<map name="planetmap">
<area shape="rect" coords="0,0,82,126" href="sun.htm" alt="Sun">
<area shape="circle" coords="90,58,3" href="mercur.htm"
alt="Mercury">
<area shape="circle" coords="124,58,8" href="venus.htm" alt="Venus">
</map>

<p>
<a href="/html/default.asp">HTML</a><br>
<a href="/css/default.asp">CSS</a>
</p>

<p>Click the button to display the URL of each link in the document.</p>

<button type="button" onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
var x = document.links;
var txt = "";
var i;
for (i = 0; i<x.length; i++) {
txt = txt + x[i].href + "<br>";
}
document.getElementById("demo").innerHTML = txt;
}
</script>

</body>
</html>
• Image
The images collection returns a collection of all
<img> elements in the document.
Ex:

Ouput:

After clicking on button

Syntax
document.images

Properties
Property Description
Length Returns the number of <img> elements in the collection.

Note: This property is read-only

Methods
Method Description

[index] Returns the <img> element from the collection with the specified
index (starts at 0).

Note: Returns null if the index number is out of range

item(index) Returns the <img> element from the collection with the specified
index (starts at 0).

Note: Returns null if the index number is out of range

namedItem(id) Returns the <img> element from the collection with the specified id.

Note: Returns null if the id does not exist

Example
[index]

Get the URL of the first <img> element (index 0) in the document:

var x = document.images[0].src;

The result of x will be:


klematis.jpg

<html>
<body>

<img src="klematis.jpg" alt="flower" width="150" height="113">


<img src="klematis2.jpg" alt="flower" width="152" height="128">
<img src="smiley.gif" alt="Smiley face" width="42" height="42">

<p>Click the button to display the URL of the first image (index 0) in the
document.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>
<script>
function myFunction() {
var x = document.images[0].src;
document.getElementById("demo").innerHTML = x;
}
</script>

</body>
</html>
Example
item(index)

Get the URL of the first <img> element (index 0) in the document:

var x = document.images.item(0).src;

The result of x will be:

klematis.jpg

<html>
<body>

<imgsrc="klematis.jpg" alt="flower" width="150" height="113">


<imgsrc="klematis2.jpg" alt="flower" width="152" height="128">
<imgsrc="smiley.gif" alt="Smiley face" width="42" height="42">

<p>Click the button to display the URL of the first image (index 0) in the
document.</p>

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
var x = document.images.item(0).src;
document.getElementById("demo").innerHTML = x;
}
</script>

</body>
</html>
Example
namedItem(id)

Get the URL of the <img> element with id="myImg" in the document:

var x = document.images.namedItem("myImg").src;

The result of x will be:

smiley.gif

<html>
<body>

<img src="klematis.jpg" alt="flower" width="150" height="113">


<img src="klematis2.jpg" alt="flower" width="152" height="128">
<img id="myImg" src="smiley.gif" alt="Smiley face" width="42"
height="42">

<p>Click the button to display the URL of the img element with
id="myImg".</p>

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
var x = document.images.namedItem("myImg").src;
document.getElementById("demo").innerHTML = x;
}
</script>

</body>
</html>
Example
Add a black dotted border to the first <img> element in the document:

document.images[0].style.border = "10px dotted black";


<html>
<body>

<imgsrc="klematis.jpg" alt="flower" width="150" height="113">


<imgsrc="klematis2.jpg" alt="flower" width="152" height="128">
<img id="myImg" src="smiley.gif" alt="Smiley face" width="42"
height="42">
<p>Click the button to add a black dotted border of the first image in the
document.</p>

<button onclick="myFunction()">Try it</button>

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

<script>
function myFunction() {
var x = document.images[0];
x.style.border = "10px dotted black";
}
</script>

</body>
</html>
Example
Loop through all <img> elements in the document, and output the URL (src) of each image:

var x = document.images;
var txt = "";
var i;
for (i = 0; i<x.length; i++) {
txt = txt + x[i].src + "<br>";
}

The result of txt will be:

klematis.jpg
klematis2.jpg
smiley.gif
<html>
<body>

<img src="klematis.jpg" alt="flower" width="150" height="113">


<img src="klematis2.jpg" alt="flower" width="152" height="128">
<img src="smiley.gif" alt="Smiley face" width="42" height="42">

<p>Click the button to display the URL of each img element in the
document.</p>

<button type="button" onclick="myFunction()">Try it</button>

<p id="demo"></p>
<script>
function myFunction() {
var x = document.images;
var txt = "";
var i;
for (i = 0; i<x.length; i++) {
txt = txt + x[i].src + "<br>";
}
document.getElementById("demo").innerHTML = txt;
}
</script>

</body>
</html>

• area
The Area object represents an

HTML <area> element. Ex:

Output:
After clicking on button

6.applet
Applets are Internet programs, designed to communicate
across the Net and execute within a web browser.

applet tag is not supported in html5.

Layer
Layers are objects on the map that consist of one or more
separate items, but are manipulated as a single unit. Layers
generally reflect collections of objects that you add on top of
the map to designate a common association.

Creating Date Objects


Date objects are created with the new Date() constructor.

There are 4 ways to create a new date object:

new Date()
new Date(year, month, day, hours, minutes, seconds, milliseconds)
new Date(date string)

new Date()
new Date() creates a new date object with the current date and time:

Example
const d = new Date();

new Date(dateString)
new Date(dateString) creates a new date object from a date string:

Example
const d = new Date("October 13, 2014 11:13:00");

These methods can be used for getting information from a date object:

Method Description

getFullYear() Get the year as a four digit number (yyyy)

getMonth() Get the month as a number (0-11)

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

getHours() Get the hour (0-23)

getMinutes() Get the minute (0-59)

getSeconds() Get the second (0-59)

getMilliseconds() Get the millisecond (0-999)

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

JavaScript Strings
A JavaScript string stores a series of characters like "John Doe".

A string can be any text inside double or single quotes:

var carName1 = "Volvo XC60";


var carName2 = 'Volvo XC60';

String indexes are zero-based: The first character is in position 0, the second
in 1, and so on.
String Properties
Property Description

Length Returns the length of a string

var str = "Hello World!";


str.length // Returns 12

String Methods
All string methods return a new value. They do not change the original
variable.
Method Description

charAt() Returns the character at the specified index (position)

var str = "HELLO WORLD";


str.charAt(0) // Returns "H"

concat() Joins two or more strings, and returns a new joined strings

var str1 = "Hello ";


var str2 = "world!";
var res = str1.concat(str2);

endsWith() Checks whether a string ends with specified string/characters

var str = "Hello world";


str.endsWith("world") // Returns true
str.endsWith("World") // Returns false

fromCharCode() Converts Unicode values to characters

String.fromCharCode(65) // Returns "A"

includes() Checks whether a string contains the specified string/characters

var str = "Hello world, welcome to the universe.";


str.includes("world") // Returns true

indexOf() Returns the position of the first found occurrence of a specified value in a
string

let str = "Hello world, welcome to the universe.";


str.indexOf("welcome") // Returns 13
str.indexOf("Welcome") // Returns -1

lastIndexOf() Returns the position of the last found occurrence of a specified value in a
string

var str = "Hello planet earth, you are a great planet.";


str.lastIndexOf("planet") // Returns 36
str.lastIndexOf("Planet") // Returns -1

match() The string.match() is an inbuilt function in JavaScript used to search a


string for a match against any regular expression. If the match is found, then
this will return the match as an array.
syntax

string.match(regExp)

<script>

var str = "Welcome to peeks for peeks!";

document.write(str.match(/eek/g));

</script>
Output:
eek, eek
In the above example, substring “eek” will match with the given string, and
when a match is found, it will return an array of string objects. Here “g” flag
indicates that the regular expression should be tested against all possible
matches in a string.
document.write(string.match(/eek/i);

Here “i” parameter helps to find the case-insensitive match in


the given string.

repeat() Returns a new string with a specified number of copies of an existing string

<script>

var str = "Hello world!";

document.write(str.repeat(2));

</script>

replace() Searches a string for a specified value, or a regular expression, and returns
a new string where the specified values are replaced

<script>
var str = "Visit Microsoft!";

document.write(str.replace("Microsoft", "Infosys"));

</script>

search() Searches a string for a specified value, or regular expression, and returns
the position of the match

var str = "Visit W3Schools!";


str.search("W3Schools") // Returns 6

slice() Extracts a part of a string and returns a new string

var str = "Hello world!";


str.slice(0, 5) // Returns "Hello"

split() Splits a string into an array of substrings

var str = "How,are,you doing today?";


const myArr = str.split(",");

document.write(myArr[3]);//doing

startsWith() Checks whether a string begins with specified characters

var str = "Hello world, welcome to the universe.";


str.startsWith("Hello") // Returns true

substr() Extracts the characters from a string, beginning at a specified start position,
and through the specified number of character

var str = "Hello world!";


str.substr(1, 4) // Returns "ello"

substring() Extracts the characters from a string, between two specified indices

var str = "Hello world!";


str.substring(1, 4) // Returns "ell"

toLowerCase() Converts a string to lowercase letters

var str = "Hello World!";


str.toLowerCase();

toUpperCase() Converts a string to uppercase letters

var str = "Hello World!";


str.toUpperCase() // Returns "HELLO WORLD!"

trim() Removes whitespace from both ends of a string

var str = " Hello World! ";


str.trim() // Returns "Hello World!"

JavaScript Number Methods


Let's see the list of JavaScript number methods with their description.

Methods Description

isInteger() It determines whether the given value is an integer.

Example 1
Let's see a simple example of isInteger() method.

<script>
var x=0;
var y=1;
var z=-1;
document.write(Number.isInteger(x));
document.write(Number.isInteger(y));
document.write(Number.isInteger(z));
</script>
Output:

true true true

Example 2
isInteger() method with some test cases.

1. <script>
2. function check(x,y)
3. {
4. return x/y;
5. }
6. document.write(Number.isInteger(check(12,2)));
7. document.write(Number.isInteger(check(12,5)));
8. </script>

Output:

true false

parseFloat() It converts the given string into a floating point number.


script>
var a="50";
var b="50.25"
var c="String";
var d="50String";
var e="50.25String"
document.write(Number.parseFloat(a)+"<br>");
document.write(Number.parseFloat(b)+"<br>");
document.write(Number.parseFloat(c)+"<br>");
document.write(Number.parseFloat(d)+"<br>");
document.write(Number.parseFloat(e));
</script>

Output:

50
50.25
NaN
50
50.25
parseInt() It converts the given string into an integer number.
1. <script>
2. var a="50";
3. var b="50.25"
4. var c="String";
5. var d="50String";
6. var e="50.25String"
7. document.writeln(Number.parseInt(a)+"<br>");
8. document.writeln(Number.parseInt(b)+"<br>");
9. document.writeln(Number.parseInt(c)+"<br>");
10. document.writeln(Number.parseInt(d)+"<br>");
11. document.writeln(Number.parseInt(e));
12. </script>

Output:

50
50
NaN
50
50

toString() It returns the given number in the form of string.


1. <script>
2. var a=50;
3. var b=-50;
4. var c=50.25;
5. document.writeln(a.toString()+"<br>");
6. document.writeln(b.toString()+"<br>");
7. document.writeln(c.toString());
8. </script>

Output:

50
-50
50.25
JavaScript Boolean
JavaScript Boolean is an object that represents value in two states: true or false. You
can create the JavaScript Boolean object by Boolean() constructor as given below.

The default value of JavaScript Boolean object is false.

1. Boolean b=new Boolean(value);

let x = false;

But booleans can also be defined as objects with the keyword new:

let y = new Boolean(false);

Example
let x = false;
let y = new Boolean(false);

// typeof x returns boolean


// typeof y returns object

JavaScript Math

Method Description

abs(x) Returns the absolute value of x

Math.abs(-4.7); // returns 4.7

ceil(x) Returns x, rounded upwards to the nearest integer

Math.ceil(4.9); // returns 5
Math.ceil(4.7); // returns 5
Math.ceil(4.4); // returns 5
Math.ceil(4.2); // returns 5
Math.ceil(-4.2); // returns -4

floor(x) Returns x, rounded downwards to the nearest integer

Math.floor(4.9); // returns 4
Math.floor(4.7); // returns 4
Math.floor(4.4); // returns 4
Math.floor(4.2); // returns 4
Math.floor(-4.2); // returns -5

max(x, y, z, ..., n) Returns the number with the highest value

Math.max(0, 150, 30, 20, -8, -200); // returns 150

min(x, y, z, ..., n) Returns the number with the lowest value

Math.min(0, 150, 30, 20, -8, -200); // returns -200

pow(x, y) Returns the value of x to the power of y

Math.pow(8, 2); // returns 64

round(x) Rounds x to the nearest integer

Math.round(4.9); // returns 5
Math.round(4.7); // returns 5
Math.round(4.4); // returns 4
Math.round(4.2); // returns 4
Math.round(-4.2); // returns -4

sign(x) Returns the sign of a number (checks whether it is positive, negative

Math.sign(-4); // returns -1
Math.sign(0); // returns 0
Math.sign(4); // returns 1

sqrt(x) Returns the square root of x

Math.sqrt(64); // returns 8

trunc(x) Returns the integer part of a number (x)

Math.trunc(4.9); // returns 4
Math.trunc(4.7); // returns 4

What is an Array?
In JavaScript, array is a single variable that is used to store different elements. It is
often used when we want to store list of elements and access them by a single
variable.
Declaration of an Array
There are basically two ways to declare an array.
Example:

var House = [ ]; // method 1


var House = new Array(); // method 2

Initialization of an Array
Example (for Method 1):

// Initializing while declaring


Var house = ["1BHK", "2BHK", "3BHK", "4BHK"];

Example (for Method 2):


// Initializing while declaring

// Creates an array having elements 10, 20, 30, 40, 50

Var house = newArray(10, 20, 30, 40, 50);

//Creates an array of 4 undefined elements

Var house1 = newArray(4);

// Now assign values

house1[0] = "1BHK"

house1[1] = "2BHK"

house1[2] = "3BHK"

house1[3] = "4BHK

//Creates an array with element 1BHK

varhome = newArray("!BHK");

An array in JavaScript can hold different elements


We can store Numbers, Strings and Boolean in a single array.
Example:
// Storing number, boolean, strings in an Array
Var house = ["1BHK", 25000, "2BHK", 50000, "Rent", true];

Accessing Array Elements


Array in JavaScript are indexed from 0 so we can access array
elements as follows:
var house = ["1BHK", 25000, "2BHK", 50000, "Rent", true];
alert(house[0]+" cost= "+house[1]);
var cost_1BHK = house[1];
var is_for_rent = house[5];
alert("Cost of 1BHK = "+ cost_1BHK);
alert("Is house for rent = ")+ is_for_rent);

Adding / removing elements

 push() – add one or more elements to the end of an array.

let fruits = ["Banana", "Orange", "Apple", "Mango"];


fruits.push("Kiwi");


 unshift() – add one or more elements to the beginning of an array.
 let fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.unshift("Lemon");

 pop() – remove an element from the end of an array.
 Let fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.pop();
 shift() – remove the first element from an array.
 let fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.shift();
 splice() – manipulate elements in an array such as deleting, inserting, and
replacing elements.

Array.splice (start, deleteCount, item 1, item 2….)


Parameters:
Start : Location at which to perform operation
deleteCount: Number of element to be deleted,
if no element is to be deleted pass 0.
Item1, item2 …..- this is an optional parameter .
These are the elements to be inserted from location start

// Removing an adding element at a particular location


// in an array
// Declaring and initializing arrays
var number_arr = [ 20, 30, 40, 50, 60];
var string_arr = [ "amit", "sumit", "anil", "prateek"];
// splice()
// deletes 3 elements starting from 1
// number array contains [20, 60]
number_arr.splice(1, 3);
// doesn't delete but inserts 3, 4, 5
// at starting location 1
number_arr.splice(1, 0, 3, 4, 5);

// deletes two elements starting from index 1


// and add three elements.
// It contains ["amit", "xyz", "geek 1", "geek 2", "prateek"];
string_arr.splice(1, 2, "xyz", "geek 1", "geek 2");

// Printing both the array after performing splice operation


document.write("After splice op "+ number_arr);
document.write("After splice op "+ string_arr);

You might also like