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

Basics of WEB II

Uploaded by

Poonam
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Basics of WEB II

Uploaded by

Poonam
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 59

UNIT-II: CSS, Form Handling and JavaScript 12 hours

CSS: Introduction, Levels of style sheets, Style specification formats, Selector forms,
Property value forms. Form Handling: Introduction, Creating Forms in HTML, GET
and POST, Accessing Form data, $_POST, _GET, $_REQUEST, Handling the file
upload, Saving the uploaded file, Restricting the file type/size, | Checking for errors,
File inclusion. JavaScript: Introduction JavaScript, HTML DOM, JavaScript Data
type, Loops in JavaScript, Functions in JavaScript, Embedding JavaScript in HTML,
Lab components

WhatisCSS?
Cascading Style Sheets, fondly referred to as CSS, is a simple design
language intended to simplify the process of making web pages
presentable.
CSS handles the look and feel part of a web page. Using CSS, you
can control the color of the text, the style of fonts, the spacing
between paragraphs, how columns are sized and laid out, what
background images or colors are used, as well as a variety of other
effects.
CSS is easy to learn and understand but it provides a powerful
control over the presentation of an HTML document. Most
commonly, CSS is combined with the markup languages HTML or
XHTML.

AdvantagesofCSS
• CSS saves time - You can write CSS once and then reuse the
same sheet in multipleHTML pages. You can define a style for
each HTML element and apply it to as many web pages as you
want.
• Pages load faster - If you are using CSS, you do not need to
write HTML tag attributes every time. Just write one CSS rule
of a tag and apply it to all the occurrences of that tag. So, less
code means faster download times.

l Page 1
• Easy maintenance - To make a global change, simply change
the style, and all the elements in all the web pages will be
updated automatically.
• Superior styles to HTML - CSS has a much wider array of
attributes than HTML, soyou can give a far better look to your
HTML page in comparison to HTML attributes.
• Multiple Device Compatibility - Style sheets allow content to
be optimized for more than one type of device. By using the
same HTML document, different versions of a website can be
presented for handheld devices such as PDAs and cellphones
or for printing.
• Global web standards – Now HTML attributes are being
deprecated and it is being recommended to use CSS. So it’s a
good idea to start using CSS in all the HTML pages to make
them compatible with future browsers.
WhoCreatesandMaintainsCSS?
CSS is created and maintained through a group of people within the
W3C called the CSS Working Group. The CSS Working Group
creates documents called specifications. When a specification has
been discussed and officially ratified by the W3C members, it
becomes a recommendation.
These ratified specifications are called recommendations because the
W3C has no control overthe actual implementation of the language.
Independent companies and organizations createthat software.
NOTE: The World Wide Web Consortium or W3C is a group that
makes recommendations about how the Internet works and how it
should evolve.

CSSVersions
Cascading Style Sheets level 1 (CSS1) came out of W3C as a
recommendation in December 1996. This version describes the CSS
language as well as a simple visual formatting model for all the
HTML tags.
CSS2 became a W3C recommendation in May 1998 and builds on
l Page 2
CSS1. This version adds support for media-specific style sheets e.g.
printers and aural devices, downloadable fonts, element positioning
and tables.

A CSS comprises of style rules that are interpreted by the browser


and then applied to thecorresponding elements in your document. A
style rule is made of three parts:
• Selector: A selector is an HTML tag at which a style will be
applied. This could be anytag like <h1> or <table> etc.
• Property: A property is a type of attribute of HTML tag.
Put simply, all the HTMLattributes are converted into CSS
properties. They could be color, border, etc.
• Value: Values are assigned to properties. For example, color
property can have thevalue either red or #F1F1F1 etc.
You can put CSS Style Rule Syntax as follows:

selector { property: value }

Example: You can define a table border as follows:

table{ border :1px solid #C00; }

Here table is a selector and border is a property and the given value
1px solid #C00 is thevalue of that property.
You can define selectors in various simple ways based on your
comfort.

TheTypeSelectors
This is the same selector we have seen above. Again, one more
example to give a color to alllevel 1 headings:

l Page 3
h1 {
color: #36CFFF;

TheUniversal Selectors
Rather than selecting elements of a specific type, the universal selector
quite simply matchesthe name of any element type:

* {
color: #000000;

This rule renders the content of every element in our document in black.

TheDescendantSelectors
Suppose you want to apply a style rule to a particular element only
when it lies inside a particular element. As given in the following
example, the style rule will apply to <em> element only when it lies
inside the <ul> tag.

ul em {
color: #000000;

The Class Selectors


You can define style rules based on the class attribute of the elements.
All the elements havingthat class will be formatted according to the
defined rule.

.black {
color: #000000;

l Page 4
This rule renders the content in black for every element with class
attribute set to black in ourdocument. You can make it a bit more
particular. For example:

h1.black {
color: #000000;

This rule renders the content in black for only <h1> elements with class attribute
set to black.
You can apply more than one class selectors to a given element.
Consider the followingexample:

<p class="center bold">


This para will be styled by the classes center and bold.

</p>

TheID Selectors
You can define style rules based on the id attribute of the elements.
All the elements havingthat id will be formatted according to the
defined rule.

#black {
color: #000000;

This rule renders the content in black for every element with id
attribute set to black in ourdocument. You can make it a bit more
particular. For example:

l Page 5
h1#black {

color: #000000;

This rule renders the content in black for only <h1> elements with id attribute set
to black.
The true power of id selectors is when they are used as the
foundation for descendantselectors. For example:

#black h2 {
color: #000000;

In this example, all level 2 headings will be displayed in black color


when those headings willlie within tags having id attribute set to black.

TheChild Selectors
You have seen the descendant selectors. There is one more type of
selector, which is verysimilar to descendants but have different
functionality. Consider the following example:

body > p {
color: #000000;

This rule will render all the paragraphs in black if they are a direct
child of the <body> element. Other paragraphs put inside other
elements like <div> or <td> would not have anyeffect of this rule.

TheAttributeSelectors
You can also apply styles to HTML elements with particular
attributes. The style rule below will match all the input elements
l Page 6
having a type attribute with a value of text:
input[type="text"]{
color: #000000;
}

The advantage to this method is that the <input type="submit" />


element is unaffected, and the color applied only to the desired text
fields.
There are following rules applied to attribute selector.
• p[lang] - Selects all paragraph elements with a lang attribute.
• p[lang="fr"] - Selects all paragraph elements whose lang
attribute has a value ofexactly "fr".
• p[lang~="fr"] - Selects all paragraph elements whose lang
attribute contains theword "fr".
• p[lang|="en"] - Selects all paragraph elements whose lang
attribute contains valuesthat are exactly "en", or begin with
"en-".

MultipleStyleRules
You may need to define multiple style rules for a single element.
You can define these rules to combine multiple properties and
corresponding values into a single block as defined in the following
example:

h1 {
color: #36C;

font-weight:
normal; letter-
spacing: .4em;
margin-bottom:
1em;
text-transform: lowercase;

l Page 7
Here all the property and value pairs are separated by a semicolon (;).
You can keep them in a single line or multiple lines. For better
readability, we keep them in separate lines.
For a while, don't bother about the properties mentioned in the above
block. These properties will be explained in the coming chapters and
you can find the complete detail about propertiesin CSS References.

GroupingSelectors
You can apply a style to many selectors if you like. Just separate the
selectors with a comma,as given in the following example:

h1, h2, h3
{ color:
#36C;
font-weight:
normal; letter-
spacing: .4em;

This define style rule will be applicable to h1, h2 and h3 element as


well. The order of the listis irrelevant. All the elements in the selector
will have the corresponding declarations appliedto them.
You can combine the various class selectors together as shown below:

#content, #footer, #supplement {


position:
absolute; left:
510px; width:
200px;

There are four ways to associate styles with your HTML document.
Most commonly used methods are inline CSS and External CSS.
l Page 8
EmbeddedCSS-The<style>Element
You can put your CSS rules into an HTML document using the
<style> element. This tag is placed inside the <head>...</head> tags.
Rules defined using this syntax will be applied to all the elements
available in the document. Here is the generic syntax:

<head>
<style type="text/css"
media="..."> Style Rules
............
</style>
</head>

Attributes
Attributes associated with <style> elements are:

Attribute Value Descripti


on
type text/css Specifies the style sheet language as a
content-type(MIME type). This is a required
attribute.
media screen Specifies the device, the document will be
tty displayedon. Default value is all. This is an
tv optional attribute.
projection
handheld
print
braille,
atural, all
Example

l Page 9
<head>
<style type="text/css"
media="all"> h1{
color: #36C;

}
</style>
</head>

Following is an example of embed CSS based on the above syntax

InlineCSS-The style Attribute


You can use style attribute of any HTML element to define style
rules. These rules will beapplied to that element only. Here is the
generic syntax:

<element style="...style rules ">

Attributes

Attribut Value Descriptio


e n
style styl The value of style attribute is a combination of style
e declarationsseparated by semicolon (;).
rule
s

Example
Following is the example of inline CSS based on the above syntax:
<h1 style ="color:#36C;"> This is inline CSS </h1>

It will produce the following result:

l Page 10
This is inline CSS

ExternalCSS-The<link>Element
The <link> element can be used to include an external stylesheet file in your
HTML document.
An external style sheet is a separate text file with .css extension. You
define all the Style rules within this text file and then you can include
this file in any HTML document using <link>element.
Here is the generic syntax of including external CSS file:

<head>
<link type="text/css" href="..." media="..." />
</head>

Attributes
Attributes associated with <style> elements are:

Attribut Value Descriptio


e n
type text/css Specifies the style sheet language as a content-type
(MIMEtype). This attribute is required.
href URL Specifies the style sheet file having Style rules. This
attributeis a required.
media scree Specifies the device the document will be displayed on.
ntty Defaultvalue is all. This is an optional attribute.
tv
projectio
n
handheld
l Page 11
print
braille
aural
all

Example
Consider a simple style sheet file with a name mystyle.css having the following
rules:

h1, h2, h3
{ color:
#36C;
font-weight:
normal; letter-
spacing: .4em;

Now you can include this file mystyle.css in any HTML document as follows:

<head>
<link type="text/css" href="mystyle.css" media="all" />
</head>

ImportedCSS-@importRule
@import is used to import an external stylesheet in a manner similar
to the <link> element.Here is the generic syntax of @import rule.

<head>
<head>
<@import "URL";
</head>

l Page 12
Here URL is the URL of the style sheet file having style rules. You
can use another syntax aswell:
<@import url("URL");
</head>

Example
Following is the example showing you how to import a style sheet file into an
HTML document:

<head>
@import "mystyle.css";
</head>

CSS Rules Overriding


We have discussed four ways to include style sheet rules in an
HTML document. Here is the rule to override any Style Sheet Rule.
• Any inline style sheet takes the highest priority. So, it will override any rule
defined in
<style>...</style> tags or the rules defined in any external style sheet file.
• Any rule defined in <style>...</style> tags will override the
rules defined in anyexternal style sheet file.
• Any rule defined in the external style sheet file takes the lowest
priority, and the rulesdefined in this file will be applied only
when the above two rules are not applicable.

HandlingOldBrowsers
There are still many old browsers who do not support CSS. So, we
should take care while writing our Embedded CSS in an HTML
document. The following snippet shows how to use comment tags to
hide CSS from older browsers:

l Page 13
<style type="text/css">
<!--
body, td {
color: blue;
}
-->
</style>

CSSComments
Many times, you may need to put additional comments in your style
sheet blocks. So, it isvery easy to comment any part in the style sheet.
You can simply put your comments inside
/*.....this is a comment in style sheet. */.
You can use /* ....*/ to comment multi-line blocks in similar way
you do in C and C++programming languages.

Example
/* This is an external style sheet file */
h1, h2, h3
{ color:
#36C;
font-weight:
normal; letter-
spacing: .4em;
margin-bottom:

Before we start the actual exercise, we would like to give a brief idea
about the CSS Measurement Units. CSS supports a number of
measurements including absolute units such as inches, centimeters,
l Page 14
points, and so on, as well as relative measures such as percentages
and em units. You need these values while specifying various
measurements in your Style rules e.g. border="1px solid red".
We have listed out all the CSS Measurement Units along with proper Examples:

Unit Descriptio Exampl


n e
Defines a measurement as a
%
percentage relative to another value, p {font-size: 16pt; line-
typically anenclosing element. height:125%;}
cm Defines a measurement in div {margin-bottom: 2cm;}
centimeters.
A relative measurement for the
height of a font in em spaces.
em p {letter-spacing: 7em;}
Because an em unit is equivalent to
the size of a given font, ifyou assign
a font to 12pt, each "em" unitwould
be 12pt; thus, 2em would be 24pt.
This value defines a measurement
p {font-size: 24pt; line-
relative to a font's x-height. The x-
ex height:3ex;}
heightis determined by the height of
the font's lowercase letter x.
in Defines a measurement in inches. p {word-spacing: .15in;}

mm Defines a measurement in p {word-spacing: 15mm;}


millimeters.
Defines a measurement in picas. A
pc p {font-size: 20pc;}
pica is equivalent to 12 points; thus,
there are 6picas per inch.

JAVASCRIPT
l Page 15
JavaScript is the scripting language of the Web.

JavaScript is used in millions of Web pages to add functionality, validate forms, detect
browsers, andmuch more.

Introduction to JavaScript

JavaScript is used in millions of Web pages to improve the design, validate forms, detect
browsers, createcookies, and much more.

JavaScript is the most popular scripting language on the Internet, and works in all major
browsers, such asInternet Explorer, Mozilla Firefox, and Opera.

What is JavaScript?

 JavaScript was designed to add interactivity to HTML pages


 JavaScript is a scripting language
 A scripting language is a lightweight programming language
 JavaScript is usually embedded directly into HTML pages
 JavaScript is an interpreted language (means that scripts execute without preliminary
compilation)
 Everyone can use JavaScript without purchasing a license

Java and JavaScript are two completely different languages in both concept and design!

Java (developed by Sun Microsystems) is a powerful and much more complex


programming language - inthe same category as C and C++.

What can a JavaScript Do ?

 JavaScript gives HTML designers a programming tool - HTML authors are


normally not programmers, but JavaScript is a scripting language with a very simple
syntax! Almost anyone canput small "snippets" of code into their HTML pages
 JavaScript can put dynamic text into an HTML page - A JavaScript
statement like this:document.write("<h1>" + name + "</h1>") can write a
variable text into an HTML page
 JavaScript can react to events - A JavaScript can be set to execute when
something happens,like when a page has finished loading or when a user clicks
on an HTML element
 JavaScript can read and write HTML elements - A JavaScript can read and
change the contentof an HTML element
l Page 16
 JavaScript can be used to validate data - A JavaScript can be used to validate
form data beforeit is submitted to a server. This saves the server from extra
processing
 JavaScript can be used to detect the visitor's browser - A JavaScript can be used
to detect the visitor's browser, and - depending on the browser - load another page
specifically designed for thatbrowser
 JavaScript can be used to create cookies - A JavaScript can be used to
store and retrieveinformation on the visitor's computer.

JavaScript Variables
Variables are "containers" for storing information.

JavaScript variables are used to hold values or

expressions.

A variable can have a short name, like x, or a more descriptive name,

like carname.Rules for JavaScript variable names:

 Variable names are case sensitive (y and Y are two different variables)
 Variable names must begin with a letter or the underscore

character Note: Because JavaScript is case-sensitive, variable

names are case-sensitive.Example

A variable's value can change during the execution of a script. You can refer to a variable by
its name todisplay or change its value.

<html>
<body>
<script
type="text/javascript">
var firstname;
firstname="Welcome";
document.write(firstname);
document.write("<br />");
firstname="XYZ";
document.write(firstname);
l Page 17
</script>

<p>The script above declares a variable,


assigns a value to it, displays the value, change
the value,and displays the value again.</p>

</body>
</html>

Output :
Welco
meXYZ

The script above declares a variable, assigns a value to it, displays the value, change the
value, anddisplays the value again.
Declaring (Creating) JavaScript Variables

Creating variables in JavaScript is most often referred to as "declaring"

variables.You can declare JavaScript variables with the var statement:

var x;
var carname;

After the declaration shown above, the variables are empty (they have no values

yet).However, you can also assign values to the variables when you declare

them:

var x=5;
var carname="Scorpio";

After the execution of the statements above, the variable x will hold the value 5, and
carname will holdthe value Scorpio.

Note: When you assign a text value to a variable, use quotes around the value.

Assigning Values to Undeclared JavaScript Variables

l Page 18
If you assign values to variables that have not yet been declared, the variables will
automatically bedeclared.

These statements:

x=5;
carname="Scorpio";

have the same effect as:

var x=5;
var carname="Scorpio";

Redeclaring JavaScript Variables

If you redeclare a JavaScript variable, it will not lose its original value.

var x=5;
var x;

After the execution of the statements above, the variable x will still have the value of 5.
The value of x isnot reset (or cleared) when you redeclare it.

DataTypes

 Numbers - are values that can be processed and calculated. You don't enclose
them in quotationmarks. The numbers can be either positive or negative.
 Strings - are a series of letters and numbers enclosed in quotation marks. JavaScript
uses the stringliterally; it doesn't process it. You'll use strings for text you want
displayed or values you want passed along.
 Boolean (true/false) - lets you evaluate whether a condition meets or does not
meet specifiedcriteria.
 Null - is an empty value. null is not the same as 0 -- 0 is a real, calculable number,
whereas null isthe absence of any value.

Data Types
l Page 19
TYPE EXAMPLE
Number Any number, such as 17, 21, or 54e7
s
Strings "Greetings!" or "Fun"
Boolean Either true or false
Null A special keyword for exactly that – the null value (that is,
nothing)

JavaScript Arithmetic

As with algebra, you can do arithmetic operations with JavaScript variables:

y=x-5;
z=y+5;

JavaScript Operators
The operator = is used to assign

values.The operator + is used to

add values.

The assignment operator = is used to assign values to JavaScript

variables.The arithmetic operator + is used to add values together.

y=5;
z=2;
x=y+z;
The value of x, after the execution of the statements above is 7.

JavaScript Arithmetic Operators

Arithmetic operators are used to perform arithmetic between variables

and/or values.Given that y=5, the table below explains the arithmetic
l Page 20
operators:

Operato Description Exampl Resul


r e t
+ Addition x=y+2 x=7
- Subtraction x=y-2 x=3
* Multiplication x=y*2 x=10
/ Division x=y/2 x=2.5
% Modulus (division remainder) x=y%2 x=1
++ Increment x=++y x=6
-- Decrement x=--y x=4

JavaScript Assignment Operators

Assignment operators are used to assign values to JavaScript

variables. Given that x=10 and y=5, the table below explains the

assignment operators:

Operato Exampl Same Resul


r e As t
= x=y x=5
+= x+=y x=x+y x=15
-= x-=y x=x-y x=5
*= x*=y x=x*y x=50
/= x/=y x=x/y x=2
%= x%=y x=x%y x=0

The + Operator Used on Strings

The + operator can also be used to add string variables or text values

together.To add two or more string variables together, use the +

operator.

l Page 21
txt1="What a very";
txt2="nice day";
txt3=txt1+txt2;

After the execution of the statements above, the variable txt3 contains "What a

verynice day".To add a space between the two strings, insert a space into one of

the strings:

txt1="What a very ";


txt2="nice day";
txt3=txt1+txt2;

or insert a space into the expression:

txt1="What a very";
txt2="nice day";
txt3=txt1+" "+txt2;

After the execution of the statements above, the variable

txt3 contains:"What a very nice day"

Adding Strings and Numbers

Look at these examples:

x=5+5;
document.write(x);

x="5"+"5";
document.write(x);

x=5+"5";
document.write(x);

x="5"+5;
document.write(x);

l Page 22
The rule is:

If you add a number and a string, the result will be a

string.JavaScript Comparison and Logical Operators

Comparison and Logical operators are used to test for true or false.

Comparison Operators

Comparison operators are used in logical statements to determine equality or difference


between variablesor values.

Given that x=5, the table below explains the comparison operators:

Operato Description Example


r
== is equal to x==8 is false
=== is exactly equal to (value and type) x===5 is true
x==="5" is
false
!= is not equal x!=8 is true
> is greater than x>8 is false
< is less than x<8 is true
>= is greater than or equal to x>=8 is false
<= is less than or equal to x<=8 is true

How Can it be Used

Comparison operators can be used in conditional statements to compare values and take
action dependingon the result:

if (age<18) document.write("Too young");

You will learn more about the use of conditional statements in the next chapter of this tutorial.

Logical Operators

l Page 23
Logical operators are used to determine the logic between variables

or values.Given that x=6 and y=3, the table below explains the

logical operators:

Operato Descripti Example


r on
&& and (x < 10 && y > 1) is true
|| or (x==5 || y==5) is false
! not !(x==y) is true

Conditional Operator

JavaScript also contains a conditional operator that assigns a value to a variable based on
some condition.

Syntax
variablename=(condition)?value1:value2

Example
greeting=(visitor=="PRES")?"Dear President ":"Dear ";

If the variable visitor has the value of "PRES", then the variable greeting will be
assigned the value"Dear President " else it will be assigned "Dear".

Conditional Statements

Very often when you write code, you want to perform different actions for different
decisions. You canuse conditional statements in your code to do this.

In JavaScript we have the following conditional statements:

 if statement - use this statement if you want to execute some code only if a
specified condition istrue
 if...else statement - use this statement if you want to execute some code if the
condition is trueand another code if the condition is false
 if...else if. else statement - use this statement if you want to select one of many blocks
of code to
l Page 24
be executed
 switch statement - use this statement if you want to select one of many blocks
of code to beexecuted

If Statement

You should use the if statement if you want to execute some code only if a specified
condition is true.

Syntax
if (condition)
{
code to be executed if condition is true
}

Note that if is written in lowercase letters. Using uppercase letters (IF) will generate a
JavaScript error!

Example 1
<script type="text/javascript">
//Write a "Good morning" greeting if
//the time is less than 10
var d=new Date();
var time=d.getHours();

if (time<10)
{
document.write("<b>Good morning</b>");
}
</script>

Example 2
<script type="text/javascript">
//Write "Lunch-time!" if the time is 11
var d=new Date();
var time=d.getHours();

if (time==11)
{
document.write("<b>Lunch-time!</b>");
}
l Page 25
</script>
Note: When comparing variables you must always use two equals signs next to each other
(==)!

Notice that there is no ..else.. in this syntax. You just tell the code to execute some
code only if thespecified condition is true.

If...else Statement

If you want to execute some code if a condition is true and another code if the condition
is not true, usethe if else statement.

Syntax
if (condition)
{
code to be executed if condition is true
}
else
{
code to be executed if condition is not true
}

Example
<script type="text/javascript">
//If the time is less than 10,
//you will get a "Good morning" greeting.
//Otherwise you will get a "Good day" greeting.
var d = new Date();

var time = d.getHours();

if (time < 10)


{
document.write("Good morning!");
}
else
{
document.write("Good day!");
}
</script>

l Page 26
If...else if...else Statement

You should use the if....else if...else statement if you want to select one of many sets of lines
to execute.

Syntax
if (condition1)
{
code to be executed if condition1 is true
}
else if (condition2)
{
code to be executed if condition2 is true
}
else
{
code to be executed if condition1 and
condition2 are not true
}

Example
<script type="text/javascript">
var d = new Date()
var time = d.getHours()
if (time<10)
{
document.write("<b>Good morning</b>");
}
else if (time>10 && time<16)
{
document.write("<b>Good day</b>");
}
else

{
document.write("<b>Hello World!</b>");
}
</script>

The JavaScript Switch Statement


l Page 27
You should use the switch statement if you want to select one of many blocks of code to be
executed.

Syntax
switch(n)
{
case 1:
execute code block 1
break;
case 2:
execute code block 2
break;
default:
code to be executed if n is
different from case 1 and 2
}

This is how it works: First we have a single expression n (most often a variable), that is
evaluated once.The value of the expression is then compared with the values for each case
in the structure. If there is amatch, the block of code associated with that case is executed.
Use break to prevent the code from running into the next case automatically.

Example
<script type="text/javascript">
//You will receive a different greeting based
//on what day it is. Note that Sunday=0,
//Monday=1, Tuesday=2, etc.
var d=new Date();
theDay=d.getDay();
switch (theDay)
{
case 5:
document.write("Finally Friday");
break;
case 6:
document.write("Super Saturday");
break;
case 0:
document.write("Sleepy Sunday");

l Page 28
break;
default:
document.write("I'm looking forward to this weekend!");
}
</script>

JavaScript Controlling(Looping) Statements

Loops in JavaScript are used to execute the same block of code a specified number of
times or whilea specified condition is true.

JavaScript Loops

Very often when you write code, you want the same block of code to run over and over
again in a row.Instead of adding several almost equal lines in a script we can use loops
to perform a task like this.

In JavaScript there are two different kind of loops:

 for - loops through a block of code a specified number of times


 while - loops through a block of code while a specified condition is true

The for Loop

The for loop is used when you know in advance how many times the script should run.

Syntax

for (var=startvalue;var<=endvalue;var=var+increment)
{
code to be executed
}

Example

Explanation: The example below defines a loop that starts with i=0. The loop will continue
to run as longas i is less than, or equal to 10. i will increase by 1 each time the loop runs.

Note: The increment parameter could also be negative, and the <= could be any comparing
l Page 29
statement.

<html>
<body>
<script type="text/javascript">
var i=0;
for (i=0;i<=10;i++)
{

document.write("The number is " + i);


document.write("<br />");
}
</script>
</body>
</html>

Result

The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9
The number is 10

JavaScript While Loop

Loops in JavaScript are used to execute the same block of code a specified number of
times or whilea specified condition is true.

The while loop

The while loop is used when you want the loop to execute and continue executing while the
l Page 30
specifiedcondition is true.

while (var<=endvalue)
{
code to be executed
}

Note: The <= could be any comparing statement.

Example

Explanation: The example below defines a loop that starts with i=0. The loop will continue
to run as longas i is less than, or equal to 10. i will increase by 1 each time the loop runs.

<html>

<body>
<script type="text/javascript">
var i=0;
while (i<=10)
{
document.write("The number is " + i);
document.write("<br />");
i=i+1;
}
</script>
</body>
</html>

Result

l Page 31
The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9
The number is 10

The do...while Loop

The do...while loop is a variant of the while loop. This loop will always execute a block
of code ONCE,and then it will repeat the loop as long as the specified condition is true.
This loop will always be executed at least once, even if the condition is false, because the
code is executed before the condition istested.

do
{
code to be executed
}
while (var<=endvalue);

Example

<html>
<body>
<script type="text/javascript">

l Page 32
var i=0;
do
{
document.write("The number is " + i);
document.write("<br />");
i=i+1;
}
while (i<0);
</script>
</body>
</html>

Result

The number is 0

JavaScript Break and Continue


There are two special statements that can be used inside loops: break and continue.

JavaScript break and continue Statements

There are two special statements that can be used inside loops: break and continue.

Break

The break command will break the loop and continue executing the code that follows
after the loop (ifany).

Example

l Page 33
<html>
<body>
<script type="text/javascript">
var i=0;
for (i=0;i<=10;i++)
{
if (i==3)
{
break;
}
document.write("The number is " + i);
document.write("<br />");
}
</script>
</body>

l Page 34
JAVASCRIPT Notes

</html>

Result

The number is 0
The number is 1
The number is 2

Continue

The continue command will break the current loop and continue with the next value.

Example

<html>
<body>
<script type="text/javascript">
var i=0
for (i=0;i<=10;i++)
{
if (i==3)
{
continue;
}
document.write("The number is " + i);
document.write("<br />");
}
</script>
</body>
</html>

Result

l Page 35
JAVASCRIPT Notes

The number is 0
The number is 1
The number is 2
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9
The number is 10

JavaScript Functions

A function (also known as a method) is a self-contained piece of code that performs a


particular "function". You can recognise a function by its format - it's a piece of
descriptive text, followed by openand close brackets.A function is a reusable code-block
that will be executed by an event, or when the function is called.

To keep the browser from executing a script when the page loads, you can put your script

into a function.A function contains code that will be executed by an event or by a call to

that function.

You may call a function from anywhere within the page (or even from other pages if the
function isembedded in an external .js file).

Functions can be defined both in the <head> and in the <body> section of a document.
However, to assure that the function is read/loaded by the browser before it is called, it
could be wise to put it in the
<head> section.

l Page 36
JAVASCRIPT Notes
Example
<html>
<head>
<script type="text/javascript">
function displaymessage()
{
alert("Hello World!");
}
</script>
</head>
<body>
<form>
<input type="button" value="Click me!"
onclick="displaymessage()" >
</form>
</body>
</html>

If the line: alert("Hello world!!") in the example above had not been put within a function,
it would havebeen executed as soon as the line was loaded. Now, the script is not executed
before the user hits the button. We have added an onClick event to the button that will
execute the function displaymessage() when the button is clicked.

You will learn more about JavaScript events in the JS Events chapter.

How to Define a Function

The syntax for creating a function is:

function functionname(var1,var2,...,varX)
{
some code
}

var1, var2, etc are variables or values passed into the function. The { and the } defines the
start and end ofthe function.

Note: A function with no parameters must include the parentheses () after the function name:

l Page 37
JAVASCRIPT Notes

function functionname()
{
some code
}

Note: Do not forget about the importance of capitals in JavaScript! The word function
must be written inlowercase letters, otherwise a JavaScript error occurs! Also note that
you must call a function with the exact same capitals as in the function name.

The return Statement

The return statement is used to specify the value that is returned from the

function.So, functions that are going to return a value must use the

return statement.

Example

The function below should return the product of two numbers (a and b):

function prod(a,b)
{
x=a*b;
return x;
}

When you call the function above, you must pass along two parameters:

product=prod(2,3);

l Page 38
JAVASCRIPT Notes

The returned value from the prod() function is 6, and it will be stored in the variable called
product.

The Lifetime of JavaScript Variables

When you declare a variable within a function, the variable can only be accessed within
that function. When you exit the function, the variable is destroyed. These variables are
called local variables. You canhave local variables with the same name in different
functions, because each is recognized only by the function in which it is declared.

If you declare a variable outside a function, all the functions on your page can access it.
The lifetime ofthese variables starts when they are declared, and ends when the page is
closed.

There are 3 types of pop-up boxes:


 Alert
 Confirm
 Prompt
The alert method opens a dialog window and displays its parameter in that window. It also
displays an OK button.
The string parameter of alert is not XHTML code; it is plain text.
Therefore, the string parameter of alert may include \n but never should include <br />.

alert(“The sum is:” + sum + “\n”);

The confirm method opens a dialog window in which the method displays its string
parameter, along with two buttons: OK and Cancel.
confirm returns a Boolean value that indicates the user’s button input: true for OK and false
for Cancel. This method is often used to offer the user the choice of continuing some process.
var question = confirm(“Do you want to continue this download?”);

Page 39
JAVASCRIPT Notes
After the user presses one of the buttons in the confirm dialog window, the script can test the
variable, question, and react accordingly.

The prompt method creates a dialog window that contains a text box used to collect a string
of input from the user, which prompt returns as its value.

FORM Handling in JAVA SCRIPT :


Beyond using JavaScript to alter the lifecycle of form data, we can use it for a variety of
other services like validating input and enabling more sophisticated features in our form
pages, like sliders and shuttles.

Let’s begin by looking at an HTML form and some vanilla JavaScript to go with it, as shown
in Listing 1. You can also see this example running in a live fiddle.
Listing 1. A simple HTML form with JavaScript

<form name="myForm" action="" method="GET">


Enter something in the box: <br>
<input type="text" name="inputbox" value="">
<input type="button" name="button" value="Click"
onClick="testResults(this.form)"></form>

Page 40
JAVASCRIPT Notes
function testResults (form) {
var inputValue = form.inputbox.value;
alert ("You typed: " + inputValue);
}

Listing 1 is very simple but it has all the basic elements of an HTML form with
JavaScript. In this case, the JavaScript takes the input value and displays it in an alert
popup. Here’s an overview of the parts of the page:
<form> declares a new form:
name="myForm" names the form. Elsewhere in the JavaScript you can reference this form
by the name myForm. The name you give your form is up to you, but it should comply with
JavaScript's standard rules for naming variables and functions (no spaces, no weird
characters except the underscore, etc.).
action="" defines where you want the browser to send the form info. This field will be a
URL when defined. In this case, it is blank because we aren’t actually sending the form
anywhere.
method="GET" defines how the method data is passed to the action destination. The
possible values are GET and POST, meaning URL-encoded or body-encoded, respectively.
<input> starts an input element:
type="text" defines the type of input.
name = “inputbox” gives a name to the input, which we’ll use later to access it.
<input type="button"> defines a button object. If the type were “submit” the button would
automatically submit the form:
onClick="testResults(this.form)" is an event handler. It tells the browser to invoke the
given JavaScript function when the button is clicked, then pass in an object representing the
form.
It is also possible to create an input with type=”submit”, then capture the onSubmit event,
prevent the default submit behavior, and then proceed as usual.
The testResults() function is defined in our JavaScript. It obtains the value in the input field
by taking the form that was passed as an argument and then looking at inputbox.value. This
is the standard browser object model (BOM) for the form object: the form has a field by the
name of each input, and the value holds the value for that input.

What is an Event?

Event Handlers

Event Handlers are JavaScript methods, i.e. functions of objects, that allow us
as JavaScriptprogrammers to control what happens when events occur.

Page 41
JAVASCRIPT Notes

Directly or indirectly, an Event is always the result of something a user does. For example,
we've alreadyseen Event Handlers like onClick and onMouseOver that respond to mouse
actions. Another type of Event, an internal change-of-state to the page (completion of
loading or leaving the page). An onLoad Event can be considered an indirect result of a
user action.

Although we often refer to Events and Event Handlers interchangeably, it's important to
keep in mind thedistinction between them. An Event is merely something that happens -
something that it is initiated by an Event Handler (onClick, onMouseOver, etc...).

The elements on a page which can trigger events are known as "targets" or "target
elements," and we can easily understand how a button which triggers a Click event is a
target element for this event. Typically, events are defined through the use of Event
Handlers, which are bits of script that tell the browser what todo when a particular event
occurs at a particular target. These Event Handlers are commonly written as attributes of
the target element's HTML tag.

The Event Handler for a Click event at a form field button element is quite simple to
understand:

<INPUT TYPE="button" NAME="click1" VALUE="Click me for fun!"


onClick="event_handler_code">

The event_handler_code portion of this example is any valid JavaScript and it will be
executed when thespecified event is triggered at this target element. This particular topic
will be continued in IncorporatingJavaScripts into your HTML pages.

There are "three different ways" that Event Handlers can be used to trigger Events or
Functions.

Method 1 (Link Events):


Places an Event Handler as an attribute within an <A HREF= > tag,
like this:

<A HREF="foo.html" onMouseOver="doSomething()"> ...


</A>

You can use an Event Handler located within an <A HREF= > tag to make either an image
or a text linkrespond to a mouseover Event. Just enclose the image or text string between the
Page 42
JAVASCRIPT Notes
<A HREF= > and the
</A> tags.

Whenever a user clicks on a link, or moves her cursor over one, JavaScript is sent a Link
Event. One Link Event is called onClick, and it gets sent whenever someone clicks on a
link. Another link event iscalled onMouseOver. This one gets sent when someone moves
the cursor over the link.

You can use these events to affect what the user sees on a page. Here's an example of how
to use linkevents. Try it out, View Source, and we'll go over it.

<A HREF="javascript:void('')"
onClick="open('index.htm', 'links', 'height=200,width=200');">How to Use Link
Events
</A>

The first interesting thing is that there are no <SCRIPT> tags. That's because anything
that appears in thequotes of an onClick or an onMouseOver is automatically interpreted
as JavaScript. In fact, because semicolons mark the end of statements allowing you to
write entire JavaScripts in one line, you can fit anentire JavaScript program between the
quotes of an onClick. It'd be ugly, but you could do it.

Here are the three lines of interest:

1. <A HREF="#" onClick="alert('Ooo, do it again!');">Click on me!</A>


2. <A HREF="javascript:void('')" onClick="alert('Ooo, do it
again!');">Click on me!
</A>
3. <A HREF="javascript:alert('Ooo, do it again!')" >Click on me!</A>

In the first example we have a normal <A> tag, but it has the magic onClick=""
element, which says,"When someone clicks on this link, run the little bit of JavaScript
between my quotes." Notice, there'seven a terminating semicolon at the end of the alert.
Question: is this required? NO.

Let's go over each line:

1. HREF="#" tells the browser to look for the anchor #, but there is no anchor "#",
so the browserreloads the page and goes to top of the page since it couldn't find
the anchor.
2. <A HREF="javascript:void('')" tells the browser not to go anywhere - it "deadens"

Page 43
JAVASCRIPT Notes
the link whenyou click on it. HREF="javascript: is the way to call a function
when a link (hyperlink or an HREFed image) is clicked.
3. HREF="javascript:alert('Ooo, do it again!')" here we kill two birds with one stone.
The default behavior of a hyperlink is to click on it. By clicking on the link we call
the window Method alert()and also at the same time "deaden" the link.

The next line is

<A HREF="javascript:void('')"
onMouseOver="alert('Hee hee!');">Mouse over me!
</A>

This is just like the first line, but it uses an onMouseOver instead of an

onClick.Method 2 (Actions within FORMs):

The second technique we've seen for triggering a Function in response to a mouse action is to
place an
onClick Event Handler inside a button type form element, like this:

<FORM>
<INPUT TYPE="button" onClick="doSomething()">
</FORM>

While any JavaScript statement, methods, or functions can appear inside the quotation
marks of an EventHandler, typically, the JavaScript script that makes up the Event
Handler is actually a call to a function defined in the header of the document or a single
JavaScript command. Essentially, though, anything thatappears inside a command block
(inside curly braces {}) can appear between the quotation marks.

For instance, if you have a form with a text field and want to call the function checkField()
whenever thevalue of the text field changes, you can define your text field as follows:

<INPUT TYPE="text" onChange="checkField(this)">

Nonetheless, the entire code for the function could appear in quotation marks rather than a
function call:

<INPUT TYPE="text" onChange="if (this.value <= 5) {


alert("Please enter a number greater than 5");
}">
Page 44
JAVASCRIPT Notes

To separate multiple commands in an Event Handler, use semicolons

<INPUT TYPE="text" onChange="alert(‘Thanks for the entry.’);


confirm(‘Do you want to continue?’);">

The advantage of using functions as Event Handlers, however, is that you can use the same
Event Handlercode for multiple items in your document and, functions make your code
easier to read and understand.

Method 3 (BODY onLoad & onUnLoad):

The third technique is to us an Event Handler to ensure that all required objects are defined
involve the onLoad and onUnLoad. These Event Handlers are defined in the <BODY> or
<FRAMESET> tag of anHTML file and are invoked when the document or frameset are
fully loaded or unloaded. If you set a flag

within the onLoad Event Handler, other Event Handlers can test this flags to see if they
can safely run,with the knowledge that the document is fully loaded and all objects are
defined. For example:

<SCRIPT>
var loaded =
false;function
doit() {
// alert("Everything is \"loaded\" and loaded = " + loaded);
alert('Everything is "loaded" and loaded = ' + loaded);
}

</SCRIPT>

<BODY onLoad="loaded = true;">


-- OR --
<BODY onLoad="window.loaded = true;">

<FORM>
<INPUT TYPE="button" VALUE="Press Me"
onClick="if (loaded == true) doit();">
-- OR --
Page 45
JAVASCRIPT Notes
<INPUT TYPE="button" VALUE="Press Me"
onClick="if (window.loaded == true) doit();">
-- OR --
<INPUT TYPE="button" VALUE="Press Me"
onClick="if (loaded) doit();">
</FORM>

</BODY>

The onLoad Event Handler is executed when the document or frameset is fully loaded,
which means that all images have been downloaded and displayed, all subframes have
loaded, any Java Applets and Plugins(Navigator) have started running, and so on. The
onUnLoad Event Handler is executed just before the page is unloaded, which occurs
when the browser is about to move on to a new page. Be aware that whenyou are working
with multiple frames, there is no guarantee of the order in which the onLoad Event
Handler is invoked for the various frames, except that the Event Handlers for the parent
frame is invoked after the Event Handlers of all its children frames -- This will be
discussed in detail in Week 8.

Setting the bgColor Property

The first example allows the user to change the color by clicking buttons, while the
second exampleallows you to change colors by using drop down boxes.

Event Handlers

EVENT DESCRIPTI
ON
onAbort the user cancels loading of an image
input focus is removed from a form element (when the user clicks outside
onBlur
the field) orfocus is removed from a window
onClick the user clicks on a link or form element
onChange the value of a form field is changed by the user
onError an error happens during loading of a document or image
onFocus input focus is given to a form element or a window
onLoad once a page is loaded, NOT while loading
onMouseOut the user moves the pointer off of a link or clickable area of an image map
Page 46
JAVASCRIPT Notes

onMouseOver the user moves the pointer over a hypertext link


onReset the user clears a form using the Reset button
onSelect the user selects a form element’s field
onSubmit a form is submitted (ie, when the users clicks on a submit button)
onUnload the user leaves a page

Note: Input focus refers to the act of clicking on or in a form element or field. This can be
done byclicking in a text field or by tabbing between text fields.

Which Event Handlers Can Be


Used

OBJECT EVENT HANDLERS


AVAILABLE
Button element onClick, onMouseOver
Checkbox onClick
Clickable ImageMap onClick, onMouseOver,
area onMouseOut
Document onLoad, onUnload, onError
Form onSubmit, onReset
Framesets onBlur, onFocus
Hypertext link onClick, onMouseOver,
onMouseOut
Image onLoad, onError, onAbort

Radio button onClick


Reset button onClick
Selection list onBlur, onChange, onFocus
Submit button onClick
TextArea element onBlur, onChange, onFocus,
onSelect
Text element onBlur, onChange, onFocus,
onSelect
Page 47
JAVASCRIPT Notes

Window onLoad, onUnload, onBlur,


onFocus

Javascript Object Hierarchy

Hierarchy Objects
Object Properties Methods Event Handlers
Window defaultStat alert onLoad
usframes blur onUnloa
opener close donBlur
parent confir onFocus
scroll m
self focus
status open
top prompt
windo clearTimeo
w ut
setTimeout
History length back none
forwar
dgo
Navigato appCodeNa javaEnable none
r meappName d
appVersion
mimeTypes
plugins
userAgent

Page 48
JAVASCRIPT Notes

documen alinkCol clear none (the onLoad and onUnload event


t or close handlersbelong to the Window object.
anchors open
applets write
area writel
bgColor n
cookie
fgColor
forms
images
lastModifi
ed
linkColor
links
location
referrer
title

vlinkColor
image border none none
complet
eheight
hspace
lowsrc
name
src
vspac
e
width
form action submi onSubm
elements treset it
encoding onReset
FileUploa
dmethod
name
target

Page 49
JAVASCRIPT Notes

text defaultVal focu onBlur


uename sblur onCharg
type selec e
valu t onFocus
e onSelect
Built-in Objects
Array length join none
revers
esort
xx
Date none getDate none
getDay
getHours
getMinuts
getMonth
getSecons
getTime
getTimeZoneoff
setgetYear
parse
prototype
setDate
setHours
setMinute
s
setMonth
setSecon
ds
setTime

Page 50
JAVASCRIPT Notes

setYear
toGMTString
toLocaleString
UTC
String length anchor Window
prototyp big blink
e bold
charAt
fixed
fontColor
fontSize
indexOf
italics
lastIndexOf
link
small split
strike sub
substring
sup
toLowerCase
toUpperCase

JavaScript Array Object

The Array object is used to store multiple values in a single variable.

Create an Array

The following code creates an Array object called myCars:

var myCars=new Array();

There are two ways of adding values to an array (you can add as many values as you need
to define asmany variables you require).

1:

Page 51
JAVASCRIPT Notes

var myCars=new Array();


myCars[0]="Saab";
myCars[1]="Volvo";
myCars[2]="BMW";

You could also pass an integer argument to control the array's size:

var myCars=new Array(3);


myCars[0]="Saab";
myCars[1]="Volvo";
myCars[2]="BMW";

2:

var myCars=new Array("Saab","Volvo","BMW");

Note: If you specify numbers or true/false values inside the array then the type of variables
will benumeric or Boolean instead of string.

Access an Array

You can refer to a particular element in an array by referring to the name of the array and
the indexnumber. The index number starts at 0.

The following code line:

document.write(myCars[0]);

will result in the following output:

Saab

Modify Values in an Array


Page 52
JAVASCRIPT Notes

To modify a value in an existing array, just add a new value to the array with a specified
index number:

myCars[0]="Opel";

Now, the following code line:

document.write(myCars[0]);

will result in the following output:

Opel

JavaScript Date Object


Create a Date Object

The Date object is used to work with dates and

times. The following code create a Date object

called myDate:

var myDate=new Date()

Note: The Date object will automatically hold the current date and time as its initial value!

Set Dates

We can easily manipulate the date by using the methods available for the

Date object.In the example below we set a Date object to a specific date

(14th January 2010):

Page 53
JAVASCRIPT Notes
var myDate=new Date();
myDate.setFullYear(2010,0,14);

And in the following example we set a Date object to be 5 days into the future:

var myDate=new Date();


myDate.setDate(myDate.getDate()+5);

Note: If adding five days to a date shifts the month or year, the changes are handled
automatically by theDate object itself!

Compare Two Dates

The Date object is also used to compare two dates.

The following example compares today's date with the 14th January 2010:

var myDate=new Date();


myDate.setFullYear(2010,0,14);
var today = new Date();
if (myDate>today)
{
alert("Today is before 14th January 2010");
}
else
{
alert("Today is after 14th January 2010");
}

JavaScript Math Object

Page 54
JAVASCRIPT Notes

Math Object

The Math object allows you to perform mathematical tasks.

The Math object includes several mathematical constants and methods.

Syntax for using properties/methods of Math:

var pi_value=Math.PI;
var sqrt_value=Math.sqrt(16);

Note: Math is not a constructor. All properties and methods of Math can be called by
using Math as anobject without creating it.

Mathematical Constants

JavaScript provides eight mathematical constants that can be accessed from the Math
object. These are: E,PI, square root of 2, square root of 1/2, natural log of 2, natural log of
10, base-2 log of E, and base-10 logof E.

You may reference these constants from your JavaScript like this:

Math.E
Math.PI
Math.SQRT2
Math.SQRT1_2
Math.LN2
Math.LN10
Math.LOG2E
Math.LOG10E

Mathematical Methods

In addition to the mathematical constants that can be accessed from the Math object there are
also severalmethods available.

The following example uses the round() method of the Math object to round a number to
the nearestinteger:
Page 55
JAVASCRIPT Notes

document.write(Math.round(4.7));

The code above will result in the following output:

The following example uses the random() method of the Math object to return a random
number between0 and 1:

document.write(Math.random());

The code above can result in the following output:

0.4218824567728053

The following example uses the floor() and random() methods of the Math object to
return a randomnumber between 0 and 10:

document.write(Math.floor(Math.random()*11));

The code above can result in the following output:

JavaScript String Object

String object

The String object is used to manipulate a stored piece of text.

Examples of use:

The following example uses the length property of the String object to find the length of a
Page 56
JAVASCRIPT Notes
string:

var txt="Hello world!";


document.write(txt.length);

The code above will result in the following output:

12

The following example uses the toUpperCase() method of the String object to convert a
string touppercase letters:

var txt="Hello world!";


document.write(txt.toUpperCase());

The code above will result in the following output:

HELLO WORLD!

DOM In Java Script

Why DOM is 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, a corresponding document is created(DOM). DOM is
basically the representation of the same HTML document but in a different format with the
use of objects. Javascript interprets DOM easily i.e javascript can not understand the
tags(<h1>H</h1>) in HTML document but can understand object h1 in DOM. Now,
Javascript can access each of the objects (h1, p, etc) by using different functions.
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 called an Object Model?
Page 57
JAVASCRIPT Notes
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.
Properties of DOM: Let’s see the properties of the document object that can be accessed and
modified by the document object.

Representation of the DOM


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.
Methods of Document Object:
write(“string”): Writes the given string on the document.
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.
Page 58
JAVASCRIPT Notes
getElementsByClassName(): returns all the elements having the given class name.

EXAMPLE
<!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>
Output:

Page 59

You might also like