You are on page 1of 16

Java Script Objects

A javaScript object is an entity having state and behavior (properties and method).
For example: car, pen, bike, chair, glass, keyboard, monitor etc. JavaScript is an object-based
language. Everything is an object in JavaScript. JavaScript is template based not class based.
Here, we don't create class to get the object. But, we direct create objects.
An object is a non-primitive, structured data type in JavaScript. Objects are same as
variables in JavaScript, the only difference is that an object holds multiple values in terms of
properties and methods.

4.1 Creating Objects

In JavaScript, an object can be created in three ways:


1. By object literal
2. By creating instance of Object directly (using new keyword)
3. By using an object constructor (using new keyword)

1. By object literal

The object literal is a short form of creating an object. Define an object in the {
} brackets with key:value pairs separated by a comma. The key would be the name of the
property and the value will be a literal value or a function.
Syntax
object={property1:value1,property2:value2.....propertyN:valueN}

Example

Code: Output:
<script> 101 Utsav Savani 1
stu={rno:101,name:"Utsav Savani",div:1} ;
document.write(stu.rno+" "+stu.name+" "+stu.div);
</script>

2. By creating instance of Object

Another way of creating objects is using the Object() constructor function using the new keyword.
Properties and methods can be declared using the dot notation(.) property-name or using the square
brackets ["property-name"], as shown in example below.

Syntax

var objectname=new Object();


Example

Code: Output:
<script> 101 Introduction to Computer I
var sub=new Object();
sub.code=101;
sub.name="Introduction to Computer";
sub.sem="I";
document.write(sub.code+" "+sub.name+" "+sub.sem);
</script>

3. By using an Object Constructor

you need to create function with arguments. Each argument value can be assigned in the
current object by using this keyword. It refers to the current object.

Example

Code: Output:
<script> 7 Dr. Viral B. Polishwala BCA
function emp(id,name,dept){
this.id=id;
this.name=name;
this.dept=dept;
}
e=new emp(7,"Dr. Viral B. Polishwala","BCA");
document.write(e.id+" "+e.name+" "+e.dept);
</script>

4.2 Date Object

The JavaScript date object can be used to get year, month and day. JavaScript provides Date
object to work with date & time, including days, months, years, hours, minutes, seconds, and
milliseconds. You can display a timer on the webpage by the help of JavaScript date object.

4.2.1 Date Constructor

Use the Date() function to get the string representation of the current date and time in
JavaScript. Use the new keyword in JavaScript to get the Date object. You can use different
Date constructors to create date object. It provides methods to get and set day, month, year,
hour, minute and seconds.
Create a date object by specifying different parameters in the Date() constructor function.
Syntax

new Date()
new Date(value)
new Date(dateString)
new Date(year, monthIndex)
new Date(year, monthIndex, day)
new Date(year, monthIndex, day, hours)
new Date(year, monthIndex, day, hours, minutes)
new Date(year, monthIndex, day, hours, minutes, seconds)
new Date(year, monthIndex, day, hours, minutes, seconds, milliseconds)

Explanation
• No Parameters: A date object will be set to the current date & time if no parameter is
specified in the constructor.
• value: An integer value representing the number of milliseconds since January 1, 1970,
00:00:00 UTC.
• dateString: A string value that will be parsed using Date.parse() method.
• year: An integer value to represent a year of a date. Numbers from 0 to 99 map to the
years 1900 to 1999. All others are actual years.
• monthIndex: An integer value to represent a month of a date. It starts with 0 for January
till 11 for December
• day: An integer value to represent day of the month.
• hours: An integer value to represent the hour of a day between 0 to 23.
• minutes: An integer value to represent the minute of a time segment.
• seconds: An integer value to represent the second of a time segment.
• milliseconds: An integer value to represent the millisecond of a time segment. Specify
numeric milliseconds in the constructor to get the date and time elapsed from 1/1/1970.

Examples

Code(Date by Specifying Milliseconds) Output


<h1>Date by Specifying Milliseconds</h1>
<p id="p1"></p> Date by Specifying Milliseconds
<p id="p2"></p>
Thu Jan 01 1970 05:30:00 GMT+0530 (India
<p id="p3"></p> Standard Time)
<script>
var date1 = new Date(0); Thu Jan 01 1970 05:30:01 GMT+0530 (India
Standard Time)
var date2 = new Date(1000);
var date3 = new Date(5000); Thu Jan 01 1970 05:30:05 GMT+0530 (India
Standard Time)
document.getElementById("p1").innerHTML = date1;
document.getElementById("p2").innerHTML = date2;
document.getElementById("p3").innerHTML = date3;
</script>
Code(Date by Specifying Date String) Output
<h1>Date by Specifying Date String</h1>
<p id="p1"></p> Date by Specifying Date String
<p id="p2"></p>
Tue Aug 31 2021 00:00:00 GMT+0530 (India
<p id="p3"></p> Standard Time)
<p id="p4"></p>
<p id="p5"></p> Thu Aug 05 2021 00:00:00 GMT+0530 (India
Standard Time)
<p id="p6"></p>
<p id="p7"></p> Invalid Date
<p id="p8"></p>
<p id="p9"></p> Sun Jan 03 2021 00:00:00 GMT+0530 (India
Standard Time)
<script>
var date1 = new Date("31 august 2021"); Fri Oct 01 2021 00:00:00 GMT+0530 (India
var date2 = new Date("5 August, 2021"); Standard Time)
var date3 = new Date("5th September, 2021");
Mon Mar 01 2021 00:00:00 GMT+0530 (India
var date4 = new Date("2021 3 January"); Standard Time)
var date5 = new Date("31 2021 September");
var date6 = new Date("February 29 2021"); Sat Feb 29 2020 00:00:00 GMT+0530 (India
Standard Time)
var date7 = new Date("February 2020 29");
var date8 = new Date("31 12 2021"); Invalid Date
var date9 = new Date("30 march 2021
20:21:44"); Tue Mar 30 2021 20:21:44 GMT+0530 (India
Standard Time)
document.getElementById("p1").innerHTML = date1;
document.getElementById("p2").innerHTML = date2;
document.getElementById("p3").innerHTML = date3;
document.getElementById("p4").innerHTML = date4;
document.getElementById("p5").innerHTML = date5;
document.getElementById("p6").innerHTML = date6;
document.getElementById("p7").innerHTML = date7;
document.getElementById("p8").innerHTML = date8;
document.getElementById("p9").innerHTML = date9;
</script>
Code(Date using different separator) Output
<h1>Date using different separtor</h1>
Date using different separator
<p id="p1"></p>
<p id="p2"></p> Wed Sep 01 2021 00:00:00 GMT+0530 (India

<p id="p3"></p> Standard Time)


<p id="p4"></p> Wed Sep 01 2021 00:00:00 GMT+0530 (India
<p id="p5"></p> Standard Time)

<p id="p6"></p> Wed Sep 01 2021 00:00:00 GMT+0530 (India


<p id="p7"></p> Standard Time)
<p id="p8"></p> Wed Sep 01 2021 00:00:00 GMT+0530 (India

<p id="p9"></p> Standard Time)


<script> Wed Sep 01 2021 00:00:00 GMT+0530 (India
var date1 = new Date("Sepetember 2021-1"); Standard Time)
var date2 = new Date("Sepetember-2021-1"); Wed Sep 01 2021 00:00:00 GMT+0530 (India
var date3 = new Date("Sepetember- Standard Time)
2021-1"); Wed Sep 01 2021 00:00:00 GMT+0530 (India

var date4 = new Date("Sepetember,2021-1"); Standard Time)


var date5 = new Date("Sepetember,2021,1"); Sat Jan 09 2021 00:00:00 GMT+0530 (India
var date6 = new Date("Sepetember*2021,1"); Standard Time)

var date7 = new Date("Sepetember$2021$1"); Sat Jan 09 2021 00:00:00 GMT+0530 (India
var date8 = new Date("1-9-2021"); Standard Time)
var date9 = new Date("1/9/2021");
document.getElementById("p1").innerHTML = date1;
document.getElementById("p2").innerHTML = date2;
document.getElementById("p3").innerHTML = date3;
document.getElementById("p4").innerHTML = date4;
document.getElementById("p5").innerHTML = date5;
document.getElementById("p6").innerHTML = date6;
document.getElementById("p7").innerHTML = date7;
document.getElementById("p8").innerHTML = date8;
document.getElementById("p9").innerHTML = date9;
</script>
Code(Date with various parameters) Output
<h1>Date with various parameters</h1>
<p id="p1"></p> Date with various parameters
<p id="p2"></p>
Tue Mar 09 2021 00:00:00 GMT+0530 (India
<p id="p3"></p> Standard Time)
<p id="p4"></p>
<p id="p5"></p> Tue Mar 09 2021 10:00:00 GMT+0530 (India
Standard Time)
<script>
var date1 = new Date(2021, 2, 9); Tue Mar 09 2021 10:30:00 GMT+0530 (India
var date2 = new Date(2021, 2, 9, 10); Standard Time)
var date3 = new Date(2021, 2, 9, 10, 30);
var date4 = new Date(2021, 2, 9, 10, 30, 50); Tue Mar 09 2021 10:30:50 GMT+0530 (India
Standard Time)
var date5 = new Date(2021, 2, 9, 10, 30, 50, 800);
document.getElementById("p1").textContent = date1; Tue Mar 09 2021 10:30:50 GMT+0530 (India
document.getElementById("p2").textContent = date2; Standard Time)
document.getElementById("p3").textContent = date3;
document.getElementById("p4").textContent = date4;
document.getElementById("p5").textContent = date5;
</script>

4.2.2 Date Methods

• getDate()

It returns the integer value between 1 and 31 that represents the day for the specified
date on the basis of local time.
Syntax
Date.getDate()

Example

Code(As on September 1, 2021) Output

<script type = "text/javascript"> getDate() : 1


var dt = new Date();
document.write("getDate() : " + dt.getDate() );
</script>

• getDay()

Javascript date getDay() method returns the day of the week for the specified date
according to local time. The value returned by getDay() is an integer corresponding to the
day of the week: 0 for Sunday, 1 for Monday, 2 for Tuesday, and so on.
Syntax
Date,getDay()

Example

Code(As on September 1, 2021) Output

<script type = "text/javascript"> getDay() : 3


var dt = new Date();
document.write("getDay() : " + dt.getDay() );
</script>
• getMonth()

Javascript date getMonth() method returns the month in the specified date according to
local time. The value returned by getMonth() is an integer between 0 and 11. 0 corresponds
to January, 1 to February, and so on.

Syntax
Date.getMonth()

Example

Code(As on September 1, 2021) Output

<script type = "text/javascript"> getMonth() : 8


var dt = new Date();
document.write("getMonth() : " + dt.getMonth() );
</script>

• getHours ()

Javascript Date getHours() method returns the hour in the specified date according
to local time. The value returned by getHours() is an integer between 0 and 23.
Syntax
Date.getHours()

Example

Code(As on September 1, 2021) 2.10pm Output

<script type = "text/javascript"> getHours() : 14


var dt = new Date();
document.write("getHours() : " + dt.getHours() );
</script>

• setDate()

Javascript date setDate() method sets the day of the month for a specified date according to
local time.
Syntax
Date.setDate(dayValue)
Parameter: dayValue ranges from 1 to 31, representing day of month
Example

Code(As on September 1, 2021) Output

<script type = "text/javascript"> setDate() : Sat Sep 25 2021 15:32:47 GMT+0530


var dt = new Date(); (India Standard Time)
dt.setDate(25);
document.write("setDate() : " + dt);
</script>

• setMonth()
Javascript date setMonth() method sets the month for a specified date according
to local time.
Syntax
Date.setMonnth(monthValue,[dayValue,….,miliSecondValue])
Parameter: monthValue ranges from 0 to 11
Optional parameters: dayValue ranges from 1 to 31, representing day of month;
milliseconds value ranges from 0 to 999 while using also need to give values for minutes and
seconds.
Note: If you do not specify the dayValue parameter, the value returned from the getDate
method is used. If a parameter you specify is outside of the expected range, setMonth
attempts to update the date information in the Date object accordingly. For example, if you
use 18 for monthValue, the year will be incremented by 1 (year + 1), and 6 will be used for
month.

Example

Code(As on September 1, 2021) 3.48pm Output

<script type = "text/javascript"> Mon Mar 01 2021 15:47:43 GMT+0530 (India


var dt1 = new Date(); Standard Time)
var dt2 = new Date(); Fri Jul 01 2022 15:47:43 GMT+0530 (India
var dt3 = new Date(); Standard Time)
dt1.setMonth(2); Tue Jun 15 2021 15:47:43 GMT+0530 (India
dt2.setMonth(18); Standard Time)
dt3.setMonth(5,15,45,60,100);
document.write( dt1 +"<br>");
document.write( dt2 +"<br>");
document.write( dt3 +"<br>");
</script>
• toString()

Javascript date toString() method return string specifying the given date object.
Syntax
Date.toString()

Example

Code(As on September 1, 2021) 3.48pm Output

<script type = "text/javascript"> Today's date as String : Thu Sep 02 2021


var dateobject = new Date(); 10:20:03 GMT+0530 (India Standard
stringobj = dateobject.toString(); Time)
document.write( "Today's date as String : " + stringobj
);
</script>

4.3 Document Object Model (DOM)

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 of
like tag elements with attributes in HTML.

4.3.1 DOM Concepts

The document object represents the whole html document. When html document is loaded
in the browser, it becomes a document object. 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 an application programming interface (API) for
manipulating HTML and XML documents.
The DOM represents a document as a tree of nodes. It provides API that allows you to add,
remove, and modify parts of the document effectively. It is called a Logical structure because
DOM doesn’t specify any relationship between objects.
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 DOM, we can
easily access and manipulate tags, IDs, classes, Attributes, or Elements using commands or
methods provided by the Document object.
window.document is same as document

"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."
4.3.2 DOM Properties

The way a document content is accessed and modified is called the Document Object Model,
or DOM. The Objects are organized in a hierarchy. This hierarchical structure applies to the
organization of objects in a Web document.

The DOM represents an HTML or XML document as a hierarchy of nodes. Consider the
following HTML document:

<html>
<head>
<title>JavaScript DOM Example</title>
</head>
<body>
<p> Hello DOM! </p>
</body>
</html>

Hierarchy of Above Code


HEAD TITLE:TEXT
Window
HTML
Document
BODY P:TEXT

The above diagram demonstrates the parent/child relationships between the nodes.
The topmost node i.e. the Window AND/OR Document node is the root node of the DOM tree,
which has one child, the <html> element. Whereas, the <head> and <body> elements are the
child nodes of the <html> parent node.
The <head> and <body> elements are also siblings since they are at the same level. Further,
the text content inside an element is a child node of the parent element
Common Dom Property Structure

window
Frame parent self top

history document location

ancho
link form r
checkbo passwor
radio textbox textarea reset submit select button
x d

option
1. Window Object: Window Object is always at top of the hierarchy.
2. Document object: When an HTML document is loaded into a window, it becomes a
document object.
3. Form Object: It is represented by form tags.
4. Link Objects: It is represented by link tags.
5. Anchor Objects: It is represented by a href tags.
6. Form Control Elements: Form can have many control elements such as text fields,
buttons, radio buttons, and checkboxes, etc.

4.3.3 DOM Methods

At the most basic level, a website consists of an HTML and CSS document. The
browser creates a representation of the document known as Document Object Model (DOM).
This document enables Javascript to access and manipulate the elements and styles of a
website. The model is built in a tree structure of objects and defines:
• HTML elements as objects
• Properties and events of the HTML elements
• Methods to access the HTML elements
HTML DOM methods are the actions which can be performed on the HTML elements
DOM Document
The DOM Document is the owner of all other objects in your webpage. That means if you
want to access any object on your webpage you always have to start with the document. It
also contains many important properties and methods that enable us to access and modify
our website.
HTML Elements as Objects
There are many different ways to do so using the Javascript DOM. 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.

document.write()
This method allows the user to write any string on webpage console with the help of write
method on the currently opened HTML document. We can concatenate the string along with
the variables by the “+” operator

Code Output
<script>
var name;
name = prompt("Enter you name Please...");
document.write ("Hello "+ name);
</script> Hello Viral Polishwala

document.writeln()
This method allows the user to write any string on webpage console ending with the newline
character(<br>/\n) with the help of writeln method on the currently opened HTML
document.

Code Output
<script>
var no,i,j;
no = prompt("Enter Any number...");
for (i=1;i<=no;i++)
{
for(j=1;j<=i;j++)
{
document.writeln (j);
}
document.writeln("<br>");
}
</script>

document.getElementById()
An “id” is the core attribute of every HTMl element, which is used for identify the HTML
element uniquely under the opened document. We can provide the unique id to any element
of HTML by rule, but we also can give the same id to multiple elements in the HTML
document. To manage such element with the id value we can use the method
document.getElementById(id of HTML element). It will return the element as an object if
the mentioned id found in the opened document but if the id is not available in document
will return NULL. In case of repetition of same id in same document the execution will
performed on the first occurrence.

Code Output
<script>
function printMe()
{

_______________________________
var show=prompt("Enter Your Name...!");
document.getElementById('showHere').innerHTML="Hello
" + show;
}
</script>
<button onclick="printMe();">Click To Print your
Name</button>
<p id="showHere" style="border:1px solid; width:200px;
height:100px;">
After clicking the above button the text will be updated
</p>

Summary: The getElementById() is a JavaScript function that lets you grab an HTML
element, by its id, and perform an action on it. The name of the id is passed as a parameter,
and the corresponding element is the return value.

document.getElementByName(elementName)
This method searches for all the elements within the document with the parameterized name
value. In the below given example the method searches for the all element with name value
as fsub; then the length method is used to count the no of occurrences of the element with
the same name “fsub” and displays in the paragraph <p> tag.

Code Output
<script>
function printMe()
{
var
totalsub=document.getElementsByName('fsub').length;
_______________________________
document.getElementById('show').innerHTML="Total
Subjects: "+totalsub;
}
</script>
<button onclick="printMe();">Total
Subjects</button><br>
Favorite Subject:<br>
<input type="radio" name="fsub" value="Statistics" >
Statistics <br>
<input type="radio" name="fsub" value="Software
Engineering" > Software Engineering<br>
<input type="radio" name="fsub" value="OOPs & DS" >
OOPs & DS<br>
<input type="radio" name="fsub" value="Database with
Python" > Database with Python<br>
<input type="radio" name="fsub" value="Web Design -
1" > Web Design - 1<br>
<p style="border:1px solid; width=150px;height:50px;"
id="show"></p>

document.getElementByTagName(tagName)
The getElementsByTagName() is a method of the document object or a specific DOM
element. The getElementsByTagName() method accepts a tag name and returns a existing
HTML Collection of elements with the matching tag name in the order which they appear in
the document. The return collection of the getElementsByTagName() is live, meaning that it
is automatically updated when elements with the matching tag name are added and/or
removed from the document.

Code Output
<script>
function countTags(tagname)
{
var totalTags=document.getElementsByTagName(tagname);
document.getElementById('show').innerHTML=tagname + " tag used for " +
totalTags.length + " times";
}
</script>
<button onclick="countTags('p');">No of Paragraph Tags</button>
<p>This is the First Paragraph</p>
<p>This is the Second Paragraph</p>
<p>This is the Third Paragraph</p>
<p style="border:1px solid; width:150px; height:50px;" id="show"></p>

The above script will count the no of paragraphs and on clicking on the button the no of
paragraphs are shown in the last paragraph box as shown in the output window besides.
document.getElementByClassName(className)
The getElementsByClassName() is a function of an interface called Document which gives us
the array-like objects of all child members having all of the inputted class names in the form
of an HTML. This HTMLCollection object signifies the collection of nodes. These nodes can
be obtained by index numbering whose index starts from 0. The entire document will be
searched, including the main root node when the document object is called. This function
getElementsByClassName() can also be called on any element and it will give only output of
those elements which will be the products of the described root element with the specified
class names.
This function fetches and gives us an HTMLCollection object which shows an aggregation of
elements with the described class name. The returned elements will be sorted as they are
seen in the source code.

Code Output
<html>
<head>
<style>
.test {
border: 1px solid;
margin: 15px;
padding:10px;
width:300px;
}
</style>
<script>
function getClass(clname) {
var x = document.getElementsByClassName(clname);
var i;
for (i = 0; i<x.length; i++) {
x[i].style.border = "2px solid red";
}
}
</script></head>
<body>
<div class="test">
First DIV with test class
</div>
<span class="test">
Span tag with test class
</span>
<p class="test">
Paragraph tag with test Class
</p>
<button onclick="getClass('test')">Try it</button>
In the above example 3 different tags were have the class value as test, when the button
called Try it clicked the function getClass called which operates on the
getElementsByClassName for searching all tags with class name test are changed with
border style to 2px, solid and red colored.

You might also like