100% found this document useful (1 vote)
134 views

WT 1st Unit

The document provides information about a Web Technologies course, including its objectives and outcomes. The course objectives are to understand basic web concepts, XML processing, client-side scripting with JavaScript, and server-side programming with Java servlets, JSP, and PHP. The course outcomes are that students will be able to create dynamic websites, write client-side scripts, parse and execute XML, and write and deploy server-side programs using Java and PHP technologies.

Uploaded by

priya
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
100% found this document useful (1 vote)
134 views

WT 1st Unit

The document provides information about a Web Technologies course, including its objectives and outcomes. The course objectives are to understand basic web concepts, XML processing, client-side scripting with JavaScript, and server-side programming with Java servlets, JSP, and PHP. The course outcomes are that students will be able to create dynamic websites, write client-side scripts, parse and execute XML, and write and deploy server-side programs using Java and PHP technologies.

Uploaded by

priya
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/ 69

WEB TECHNOLOGIES

Course Objectives & Outcomes

Course Objectives

1. Understand the basic web concepts and internet protocols.


2. Understand XML and processing of XML data.
3. Understand client side scripting with Javascript and DHTML
4. Understand Server-side programming with Java Servlets and JSP.
5. Understand Server side scripting with PHP.

Course Outcomes

After Completion of this course Students will be able to


CO1. Create dynamic and interactiveweb sites.
CO2. Write and execute client side scripts using Javascripts and DHTML.
CO3. Write parse ,execute XML schemas.
CO4. Write implement ,deploy and execute server side programs and components using java servlets
and JSPs.
CO5. Write implement ,deploy and execute server side programs and components using PHP.
UNIT-1
HTML History:

 HTML was created by Sir Tim Berners-Lee in late 1991 but was not released officially,
published in 1995 as HTML 2.0. HTML 4.01 was published in late 1999 and was a major
version of HTML.
 HTML is a very evolving markup language and has evolved with various versions updating.
 Long before its revised standards and specifications are carried in, each version has allowed its
user to create web pages in a much easier and prettier way and make sites very efficient.

 HTML 1.0 was released in 1993 with the intention of sharing information that can be
readable and accessible via web browsers. But not many of the developers were involved in
creating websites. So the language was also not growing.
 Then comes the HTML 2.0, published in 1995, which contains all the features of HTML 1.0
along with that few additional features, which remained as the standard markup language for
designing and creating websites until January 1997 and refined various core features of
HTML.
 Then comes the HTML 3.0, where Dave Raggett who introduced a fresh paper or draft on
HTML. It included improved new features of HTML, giving more powerful characteristics
for webmasters in designing web pages. But these powerful features of new HTML slowed
down the browser in applying further improvements.
 Then comes HTML 4.01, which is widely used and was a successful version of HTML
before HTML 5.0, which is currently released and used worldwide. HTML 5 can be said for
an extended version of HTML 4.01, which was published in the year 2012.

Introduction:

 HTML (Hypertext Markup Language) is the only markup language for creating web pages.
 It provides some titles, headings, paragraphs, lists, tables, embedded images, etc., to describe the
structure of text-based and multimedia information in HTML documents.
 HTML (Hypertext Markup Language) is a language for publishing text-based and multimedia
information on the World Wide Web.
 HTML uses 'tags' to create web documents.
 HTML is relatively easy to learn because every tag is predefined, so only we need to know the
work of tags and their attributes.
 Web browsers (Chrome, Internet Explorer, Firefox, Safari, and other web browsers) are software'
to read HTML and display web page design as output.
 You can write HTML in any simple editor such as Notepad. And other software such as Adobe
Dreamweaver, Sublime, NetBeans, Notepad ++, etc., are mainly used for writing and editing
HTML.
 ".html" or ".htm" are the two extensions used to write and save HTML files; we can write
HTML code in any text editor and save it as "filename.html" or "filename.htm".
Basic Structure of HTML:

HTML elements:
 HTML elements are the names of the starting tags of your HTML code.
 When you find an element containing additional content, you will see that it ends up using a
closing tag with a forward slash with the element's name.
 HTML Elements is a combination of HTML tags and content.
Example:

<p> <p>Paragraph elements are used for giving paragraph spacing to statements.</p>

<h1> <h1>Heading elements are used to provide a heading to articles of your web page.</h1>
<br/> <br/>Line break is used to provide carriage return or going to the next line.

<h1>–<h6>: The HTML Section Heading elements:

The HTML <h1>–<h6> elements represent six levels of section headings. <h1> is the highest section
level and <h6> is the lowest.

Commonly used tags

As we saw earlier, the <h1>...<h6> tags are used to define headings. Other tags that are often used to
define elements in the body of a document include:
 <p></p> to define paragraphs of text
 <em></em> to give text emphasis (displayed in italics by default)
 <strong></strong> to give text strong emphasis (displayed in bold by default)
 <br> to insert a line break
 <hr> to insert a horizontal rule (line)

HTML Formatting:

 Formatting is one of the crucial sections of every development.


 To make an article or content look attractive, readable, and user-intractable, formatting plays a
significant role.
 Formatting can be defined as the appearance of your documentation or presentation of your
HTML code in a meaningful and more beautiful way.
 Formatting is mainly done to make the layout attractive.
Formatting elements in HTML were mainly created for displaying texts of a special type:

Tag Meanings

<u> For making text underlined.

<b> For making the text Bold.

<strong> Used in those texts, which are important and need to highlight.

<i> For making the text italics.

<em> For emphasizing the texts.

<mark> To make the texts marked or highlighted.

<small> For making texts small in size, then the regular texts surrounded.

<big> For making texts bigger or larger, then the rest of the texts are surrounded.

<del> To show texts that have been deleted or removed or replaced.

<ins> To show texts that have been inserted or added

<sub> To give a subscript effect to any text.

<sup> To give a superscript effect to any text.

<strike> For displaying any text as strikethrough.

<tt> For displaying any font as a mono-spaced font. This tag is abbreviated as a
typewriter type font tag.

Example:
OUTPUT:

HTML Attributes:

 You can define an attribute as the characteristics of any HTML tag that needs to be placed within
the opening tag.

HTML attributes consist of two parts:

1. a name and
2. a value

 Names of attribute and its values are not case-sensitive.


 But according to the World Wide Web Consortium (W3C), it is recommended to use lowercase
name and value.
 For an attribute, the name defines the property to be implemented.
 For example, BODY Tag, <body> carries many attributes such as bgcolor, background that you
can implement for indicating the back color of your webpage, or give a specific image or
background texture to your page, respectively.
 The value defines the value which you want to assign to the property and is set within quotations.
Example:
<!DOCTYPE html>
<html>
<body bgcolor="#E6E6FA">
</body>
</html>
Core Attributes:
There are four essential attributes which you can implement on almost all HTML elements:
1. id
2. title
3. class
4. style

id Attribute:

 This attribute can be implemented for providing unique identification to any element. There are
two primary reasons that you might want to use an id attribute on an element.
 The id attribute provides a unique identifier, which eventually makes it possible to identify the
HTML element.
 When you contain two elements with the same name within the same script, the id attribute
helps to distinguish the two same elements via the unique ID.
Example:
<p id = "para1"> Paragraph 1 in your HTML document. </p>

<p id = "para2"> Paragraph 2 in your HTML document. </p>

Title Attribute:

 This attribute gives a recommended title for your element.


 Its behavior depends on the element upon which it's implemented, even though this is often
implemented to display a tooltip if the cursor hovers (comes over) the element.
Example:

<h3 title="Welcome to Web Technologies Lab">Please visit</h3>

Class Attribute:

 This attribute is implemented by combining an element through a stylesheet (CSS) and


identifying its class element.
Example:
<p class = "classname1 ">This is a sample paragraph text.</p>

Style Attribute:

 This attribute gives you a chance for specifying the rules for Cascading Style Sheet (CSS) in
your element.
Example:

<p style = "font-family:arial;">An example of style attribute.</p>

Writing comments in HTML:

 For writing comments in HTML, they begin with the <! -- (starting comment tag) and ends with
the close comment tag, i.e. -->.
 Comments in HTML can be visible if and only if anyone tries to view the source code of the
page, but anything is written within <!-- …. --> does not get rendered when you will render your
HTML based web page through your browser.
Example:
<!DOCTYPE html>
<html>
<head>
<title>Example for comment.</title>
</head>
<!-- Body of webpage starts from here -->
<body>
<h2>This is HTML comment example</h2>
<p>This is my first <strong>paragraph text</strong>.</p>
</body>
</html>

HTML IMG Tag:

 For inserting pictures into our web page, we can use the <img> tag. The <img> tag is an empty
tag which mean it has no ending tag (i.e. no </img>) associated with it.

The syntax of using <img> tag is:

<img src = "path or URL" alt = "alternate_text or image replacement text">

src Attribute:

 This attribute helps specify the image's source, which means this, instruct your web browser
from which location it must fetch the particular picture (in other words, specify the path).
 SRC attribute takes path or URL as its value in quotes.

Example:

<img src="http://example.com/wallpaper.jpg" alt="Wallpaper"

alt Attribute:
 This attribute of Image Tag or <img> tag allows you to define an alternative text in case your
browser becomes unsuccessful in loading the image.
 There may be situations when your browser might not be able to display that particular image
either because of a slow connection or server error, or any other reason.
Example:

<img src= "gun.jpg" alt ="image still loading">

border attribute:
 The default value of the border is assigned as "0px" to every image. For displaying the borders
all around the image, you have to implement the border attribute of the IMG tag.
Example:

<img src="guitar.jpg" height="30px" width="30px" border="6">

 In case you need a specific size of the image for fitting it into your web page, you can use the
height and width attribute of the IMG tag.

LISTS
 Information on your web page can be listed using the List feature of HTML. There will be a set
of reasons you may have for including a list in your web pages.
 HTML provides three different techniques to specify information in the form of lists. It is to be
noted that every list needs to have at least one multiple data elements within it. The various
forms of HTML list tags are:

Tag Description

<ol> HTML ol tag is abbreviated as an Ordered List, which is used for numbering the lists on a web
page.

<ul> HTML UL tag is abbreviated as an Unordered List, which is used for listing your items via bullets
and circles.

<dl> HTML dl tag is abbreviated as a Definition List, which is used for arranging your data items like
the way items remain arranged in any dictionary.

The type Attribute:

 This type of attribute will eventually help you specify your customized type from the
types pre-specified by HTML.

For Ordered List, the type can have 5 values:

 <ol type = "1"> - Numbers, which is the default type of Ordered List
 <ol type = "i"> - Numerals (roman) with lower caps
 <ol type = "I"> - Numerals (roman) with upper caps
 <ol type = "a"> - Numbering will be done in the form of Lower-case Letters
 <ol type = "A"> - Numbering will be done in the form of upper-case Letters

Similarly, for Unordered lists also, there are three symbols which will acts as bullets for your lists.

These three values can be used for type attribute of <ul>

 <ul type = "square"> - Bulleting using a filled square


 <ul type = "disc"> - Bulleting using a filled circle
 <ul type = "circle"> - Bulleting using a empty circle

The start attribute:


The start attribute of <ol> is used for providing the starting point or value of your list.

Example:
<ol type = "I" start = "3">

Example of ol tag:

OUTPUT:

Example of ul tag:
OUTPUT:

Definition List:

 In this type of data listing, the data are arranged or listed like that of a dictionary or
encyclopedia. It is used on the last page of your site to provide the glossary or arrange a set of
definitions.
 It takes the help of two more tags called as: <dt> - a definition terminology and <dd> -
definition description.

OUTPUT:

HTML <a> Tag:

The <a> tag defines a hyperlink, which is used to link from one page to another.

The most important attribute of the <a> element is the href attribute, which indicates the link's
destination.
By default, links will appear as follows in all browsers:

 An unvisited link is underlined and blue


 A visited link is underlined and purple
 An active link is underlined and red

Example:

<!DOCTYPE html>
<html>
<body>
<p>
<h1>HTML tutorial</h1>
You can find tutorial on HTML<a href=" HTML tutorial .html”> HTML tutorial
</a>
</p>
</body>
</html>
Image as hyperlink:

Table in HTML:
A table is an arrangement of data in rows and columns, or possibly in a more complex structure.
Tables are widely used in communication, research, and data analysis.
 Tables are useful for various tasks such as presenting text information and numerical data.
 Tables can be used to compare two or more items in tabular form layout.
 Tables are used to create databases.

Defining Tables in HTML


An HTML table is defined with the “table” tag. Each table row is defined with the “tr” tag. A table
header is defined with the “th” tag. By default, table headings are bold and centered. A table data/cell
is defined with the “td” tag.
Example:
<!DOCTYPE html>
<html>
<body>
<table style="width:100%">
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>
<tr>
<td>Priya</td>
<td>Sharma</td>
<td>24</td>
</tr>
<tr>
<td>Arun</td>
<td>Singh</td>
<td>32</td>
</tr>
<tr>
<td>Sam</td>
<td>Watson</td>
<td>41</td>
</tr>
</table>
</body>
</html>
Output:

Adding a border to a HTML Table:

 A border is set using the CSS border property.


 If you do not specify a border for the table, it will be displayed without borders.
EXAMPLE:

Program:
<!DOCTYPE html>

<html>

<head>
<style>
table, th, td {
border: 1px solid black;
}
</style>
</head>

<body>
<table style="width:100%">
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>
<tr>
<td>Priya</td>
<td>Sharma</td>
<td>24</td>
</tr>
<tr>
<td>Arun</td>
<td>Singh</td>
<td>32</td>
</tr>
<tr>
<td>Sam</td>
<td>Watson</td>
<td>41</td>
</tr>
</table>
</body>

</html>

Output:

 Creating Nested Tables in HTML: Nesting tables simply means making a Table
inside another Table.
 Nesting tables can lead to complex tables layouts, which are visually interesting and
have the potential of introducing errors.
Example:
<!DOCTYPE html>
<html>

<body>
<table border=5 bordercolor=black>
<tr>
<td>
Fisrt Column of Outer Table
</td>

<td>
<table border=5 bordercolor=grey>
<tr>
<td>
First row of Inner Table
</td>
</tr>
<tr>
<td>
Second row of Inner Table
</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>
Output:

Frames in HTML:

HTML <frame> tag (Not supported in HTML5)

 HTML <frame> tag define the particular area within an HTML file where another HTML web
page can be displayed.
 A <frame> tag is used with <frameset>, and it divides a webpage into multiple sections or
frames, and each frame can contain different web pages.

Syntax:
< frame src = "URL" >

Create Vertical frames:


<!DOCTYPE html>
<html>
<head>
<title>Frame tag</title>
</head>
<frameset cols="25%,50%,25%">
<frame src="frame1.html" >
<frame src="frame2.html">
<frame src="frame3.html">
</frameset>
</html>
Output:
Frame1.html
<html>
<head>
<style>
div{
background-color: #7fffd4;
height: 500px;
}
</style>
</head>
<body>
<div>
<h2>This is first frame</h2>
</div>
</body>
</html>
Frame2.html
<!DOCTYPE html>
<html>
<head>
<style>
div{
background-color: #2f4f4f;
height: 500px;

}
</style>
</head>
<body>
<div>
<h2>This is Second frame</h2>
</div>
</body>
</html>
Frame3.html
<!DOCTYPE html>
<html>
<head>
<style>
div{
background-color: #c1ffc1;
height: 500px;
}
</style>
</head> <body>
<div>
<h2>This is Third frame</h2>
</div>
</body>
</html>

Create Horizontal frames:


<!DOCTYPE html>
<html>
<head>
<title>Frame tag</title>
</head>
<frameset rows="30%, 40%, 30%">
<frame name="top" src="frame1.html" >
<frame name="main" src="frame2.html">
<frame name="bottom" src="frame3.html">
</frameset>
</html>
Out Put:
Attributes:
Attribute Value Description

frameborder 0 It specifies whether to display a border around the frame or not, and its
1 default value is 1

longdsec URL It specifies a page which contains the long description of the content of the
frame.

marginheight pixels It specifies the top and bottom margins of the frame.

marginwidth pixels It defines the height of the margin between frames.

name Text It is used to assign the name to the frame.

noresize noresize It is used to prevent resizing of the frame by the user.

scrolling yes It specifies the existence of the scrollbar for overflowing content.
no
auto

src URL It specifies the URL of the document which we want to display in a frame.
HTML – Forms:
 HTML Forms are required, when you want to collect some data from the site visitor.
 For example, during user registration you would like to collect information such as name, email
address, credit card, etc.
 There are various form elements available like text fields, textarea fields, drop-down menus, radio
buttons, checkboxes, etc.
 The HTML <form> tag is used to create an HTML form and it has following syntax −
<form action = "Script URL" method = "GET|POST">
form elements like input, textarea etc.
</form>

HTML Form Controls


There are different types of form controls that you can use to collect data using HTML form −

 Text Input Controls


 Checkboxes Controls
 Radio Box Controls
 Select Box Controls
 File Select boxes
 Hidden Controls
 Clickable Buttons
 Submit and Reset Button

Text Input Controls


There are three types of text input used on forms −
 Single-line text input controls − This control is used for items that require only one line of user
input, such as search boxes or names. They are created using HTML <input> tag.
 Password input controls − This is also a single-line text input but it masks the character as
soon as a user enters it. They are also created using HTMl <input> tag.
 Multi-line text input controls − This is used when the user is required to give details that may
be longer than a single sentence. Multi-line input controls are created using
HTML <textarea> tag.

Single-line text input controls


 This control is used for items that require only one line of user input, such as search boxes or
names. They are created using HTML <input> tag.

Example
Here is a basic example of a single-line text input used to take first name and last name
<!DOCTYPE html>
<html>

<head>
<title>Text Input Control</title>
</head>

<body>
<form >
First name: <input type = "text" name = "first_name" />
<br>
Last name: <input type = "text" name = "last_name" />
</form>
</body>

</html>

This will produce the following result −

Attributes
Following is the list of attributes for <input> tag for creating text field.

Sr.No Attribute & Description

1
type
Indicates the type of input control and for text input control it will be set to text.

2
name
Used to give a name to the control which is sent to the server to be recognized
and get the value.

3
value
This can be used to provide an initial value inside the control.

4
size
Allows to specify the width of the text-input control in terms of characters.

5
maxlength
Allows to specify the maximum number of characters a user can enter into the
text box.

Password input controls


 This is also a single-line text input but it masks the character as soon as a user enters it. They
are also created using HTML <input>tag but type attribute is set to password.

Example
Here is a basic example of a single-line password input used to take user password
<!DOCTYPE html>
<html>

<head>
<title>Password Input Control</title>
</head>

<body>
<form >
User ID : <input type = "text" name = "user_id" />
<br>
Password: <input type = "password" name = "password" />
</form>
</body>

</html>

OUTPUT:
Multiple-Line Text Input Controls
This is used when the user is required to give details that may be longer than a single sentence. Multi-
line input controls are created using HTML <textarea> tag.

Example
Here is a basic example of a multi-line text input used to take item description
<!DOCTYPE html>
<html>

<head>
<title>Multiple-Line Input Control</title>
</head>

<body>
<form>
Description : <br />
<textarea rows = "5" cols = "50" name = "description">
Enter description here...
</textarea>
</form>
</body>

</html>

Out Put:

Attributes
Following is the list of attributes for <textarea> tag.

Sr.No Attribute & Description

1
name
Used to give a name to the control which is sent to the server to be recognized
and get the value.
2
rows
Indicates the number of rows of text area box.

3
cols
Indicates the number of columns of text area box

Checkbox Control
Checkboxes are used when more than one option is required to be selected. They are also created using
HTML <input> tag but type attribute is set to checkbox..

Example
Here is an example HTML code for a form with two checkboxes

Attributes
Following is the list of attributes for <checkbox> tag.

Sr.No Attribute & Description

1
type
Indicates the type of input control and for checkbox input control it will be set
to checkbox..

2
name
Used to give a name to the control which is sent to the server to be recognized
and get the value.

3
value
The value that will be used if the checkbox is selected.
4
checked
Set to checked if you want to select it by default.

Radio Button Control


Radio buttons are used when out of many options, just one option is required to be selected. They are
also created using HTML <input> tag but type attribute is set to radio.

Example
Here is example HTML code for a form with two radio buttons
<!DOCTYPE html>
<html>

<head>
<title>Radio Box Control</title>
</head>

<body>
<form>
<input type = "radio" name = "subject" value = "maths"> Maths
<input type = "radio" name = "subject" value = "physics"> Physics
</form>
</body>

</html>
Output:

Attributes
Following is the list of attributes for radio button.

Sr.No Attribute & Description

1
type
Indicates the type of input control and for checkbox input control it will be set to
radio.
2
name
Used to give a name to the control which is sent to the server to be recognized
and get the value.

3
value
The value that will be used if the radio box is selected.

4
checked
Set to checked if you want to select it by default.

Select Box Control


A select box, also called drop down box which provides option to list down various options in the form
of drop down list, from where a user can select one or more options.

Example
Here is example HTML code for a form with one drop down box
<!DOCTYPE html>
<html>

<head>
<title>Select Box Control</title>
</head>

<body>
<form>
<select name = "dropdown">
<option value = "Maths" selected>Maths</option>
<option value = "Physics">Physics</option>
</select>
</form>
</body>

</html>
Output:
File Upload Box
If you want to allow a user to upload a file to your web site, you will need to use a file upload box, also
known as a file select box. This is also created using the <input> element but type attribute is set to file.

Example
Here is example HTML code for a form with one file upload box
<!DOCTYPE html>
<html>

<head>
<title>File Upload Box</title>
</head>

<body>
<form>
<input type = "file" name = "fileupload" accept = "image/*" />
</form>
</body>

</html>
Output:

Button Controls
 There are various ways in HTML to create clickable buttons.
 You can also create a clickable button using <input>tag by setting its type attribute to button.
 The type attribute can take the following values

Sr.No Type & Description


1
submit
This creates a button that automatically submits a form.

2
reset
This creates a button that automatically resets form controls to their initial values.

3
button
This creates a button that is used to trigger a client-side script when the user clicks
that button.

4
image
This creates a clickable button but we can use an image as background of the
button.

Example
Here is example HTML code for a form with three types of buttons
<!DOCTYPE html>
<html>

<head>
<title>File Upload Box</title>
</head>

<body>
<form>
<input type = "submit" name = "submit" value = "Submit" />
<input type = "reset" name = "reset" value = "Reset" />
<input type = "button" name = "ok" value = "OK" />
<input type = "image" name = "imagebutton" src = "/html/images/logo.png" />
</form>
</body>

</html>
Output:
What is CSS?

 CSS stands for Cascading Style Sheets


 CSS describes how HTML elements are to be displayed on screen, paper, or in other
media
 CSS saves a lot of work. It can control the layout of multiple web pages all at once
 External style sheets are stored in CSS files

CSS Syntax
A CSS rule consists of a selector and a declaration block.

Example:

 The selector points to the HTML element you want to style.


 The declaration block contains one or more declarations separated by semicolons.
 Each declaration includes a CSS property name and a value, separated by a colon.
 Multiple CSS declarations are separated with semicolons, and declaration blocks are
surrounded by curly braces.
Program:
<!DOCTYPE html>

<html>

<head>

<style>

p{

color: red;

text-align: center;

</style>

</head>

<body>

<p>Hello World!</p>

<p>These paragraphs are styled with CSS.</p>

</body>

</html>

Output:
CSS Selectors
A CSS selector selects the HTML element(s) you want to style.

Types of Selectors:

We can divide CSS selectors into five categories

 The CSS element Selector


 The CSS id Selector
 The CSS class Selector
 The CSS Universal Selector
 The CSS Grouping Selector
The CSS element Selector
The element selector selects HTML elements based on the element name.

Example

Here, all <p> elements on the page will be center-aligned, with a red text color:

<!DOCTYPE html>
<html>
<head>
<style>
p{
text-align: center;
color: red;
}
</style>
</head>
<body>

<p>Every paragraph will be affected by the style.</p>


<p id="para1">Me too!</p>
<p>And me!</p>

</body>
</html>
Output :

The CSS id Selector:


 The id selector uses the id attribute of an HTML element to select a specific element.
 The id of an element is unique within a page, so the id selector is used to select one
unique element!
 To select an element with a specific id, write a hash (#) character, followed by the id of
the element.
 Note: An id name cannot start with a number!
Example

The CSS rule below will be applied to the HTML element with id="para1":

<!DOCTYPE html>
<html>
<head>
<style>
#para1 {
text-align: center;
color: red;
}
</style>
</head>
<body>
<p id="para1">Hello World!</p>
<p>This paragraph is not affected by the style. </p>
</body> </html>
The CSS class Selector
 The class selector selects HTML elements with a specific class attribute.
 To select elements with a specific class, write a period (.) character, followed by the class
name.
Example

In this example all HTML elements with class="center" will be red and center-aligned:

<!DOCTYPE html>
<html>
<head>
<style>
.center {
text-align: center;
color: red;
}
</style>
</head>
<body>

<h1 class="center">Red and center-aligned heading</h1>


<p class="center">Red and center-aligned paragraph.</p>

</body>
</html>
The CSS Universal Selector
The universal selector (*) selects all HTML elements on the page.

Example

The CSS rule below will affect every HTML element on the page:

<!DOCTYPE html>
<html>
<head>
<style>
*{
text-align: center;
color: blue;
}
</style>
</head>
<body>

<h1>Hello world!</h1>

<p>Every element on the page will be affected by the


style.</p>
<p id="para1">Me too!</p>
<p>And me!</p>

</body>
</html>

The CSS Grouping Selector


 The grouping selector selects all the HTML elements with the same style definitions.
Look at the following CSS code (the h1, h2, and p elements have the same style
definitions):
h1 {
text-align: center;
color: red;
}
h2 {
text-align: center;
color: red;
}

p{
text-align: center;
color: red;
}

 It will be better to group the selectors, to minimize the code.


 To group selectors, separate each selector with a comma.
<!DOCTYPE html>
<html>
<head>
<style>
h1, h2, p {
text-align: center;
color: red;
}
</style>
</head>
<body>
<h1>Hello World!</h1>
<h2>Smaller heading!</h2>
<p>This is a paragraph.</p>
</body>
</html>
Types of CSS

 CSS (Cascading Style Sheet) describes the HTML elements which are displayed
on screen, paper, or in other media. It saves a lot of time.
 It controls the layout of multiple web pages at one time. It sets the font-size, font-
family, color, background color on the page.
 It allows us to add effects or animations to the website.
 We use CSS to display animations like buttons, effects, loaders or spinners, and
also animated backgrounds.
 Without using CSS, the website will not look attractive. There are 3 types of CSS which
are below

Internal CSS

 The Internal CSS has <style> tag in the <head> section of the HTML document.
 This CSS style is an effective way to style single pages.
 Using the CSS style for multiple web pages is time-consuming because we require
placing the style on each web page.

We can use the internal CSS by using the following steps:

1. Firstly, open the HTML page and locate the <head>

2. Put the following code after the <head>

<style type="text/css">

3. Add the rules of CSS in the new line.

Example: body { background-color: black;


}
h1 {
color: white;
padding: 50px;
}

4. Close the style tag. </style>

After adding the internal CSS, the complete HTML file looks like the following:

<!DOCTYPE html>
<html>
<head>
<style>
body {
background-color: black;
}
h1 {
color: red;
padding: 50px;
}
</style>
</head>
<body>
<h2>CSS types</h2>
<p>Cascading Style sheet types: inline, external and internal</p>
</body>
</html>

Pros of Internal CSS

 Internal CSS cannot upload multiple files when we add the code with the HTML
page.

Cons of Internal CSS:

 Adding code in the HTML document will reduce the page size and loading time of
the webpage.

2. External CSS
 In external CSS, we link the web pages to the external .css file.
 It is created by text editor. The CSS is more efficient method for styling a website.
 By editing the .css file, we can change the whole site at once.
To use the external CSS, follow the steps, given below:

1. Create a new .css file with text editor, and add Cascading Style Sheet rules too.

For example:

.xleftcol {
float: right;
width: 35%;
background:#608800;
}
.xmiddlecol {
float: right;
width: 35%;
background:#eff3df;
}

2. Add a reference to the external .css file right after <title> tag in the <head> section
of HTML sheet:

<link rel="stylesheet" type="text/css" href="style.css" />

Pros of External CSS:

 Our files have a cleaner structure and smaller in size.


 We use the same .css file for multiple web pages in external CSS.

Cons of External CSS:

 The pages cannot be delivered correctly before the external CSS is loaded.
 In External CSS, uploading many CSS files can increase the download time of a website.

3. Inline CSS

 Inline CSS is used to style a specific HTML element. Add a style attribute to each
HTML tag without using the selectors.
 Managing a website may difficult if we use only inline CSS.
 However, Inline CSS in HTML is useful in some situations.
 We have not access the CSS files or to apply styles to element.
In the following example, we have used the inline CSS in <p> and <h1> tag.

<!DOCTYPE html>
<html>
<body style="background-color:white;">
<h1 style="color:Red;padding:20px;">CSS Tutorials</h1>
<p style="color:blue;">It will be useful here.</p>
</body>
</html>

Pros of inline CSS:

 We can create CSS rules on the HTML page.


 We cannot create and upload a separate document in inline CSS.

Cons of inline CSS:

 Inline CSS, adding CSS rules to HTML elements is time-consuming and messes up the
HTML structure.
 It styles multiple elements at the same time which can affect the page size and download
time of the page.
Java Script
Introduction:
 JavaScript is a very powerful client-side scripting language.

 JavaScript is used mainly for enhancing the interaction of a user with the webpage.

 JavaScript was originally created by Netscape in 1996, while Microsoft’s version of


JavaScript is called Jscript.

 In other words, you can make your webpage more lively and interactive, with the help of
JavaScript.

 JavaScript is also being used widely in game development and mobile application
development.

Tools You Need:

 You can use a text editor of your choice including Notepad++, Visual Studio Code,
Sublime Text, Atom or any other text editor.

 You can use any web browser including Google Chrome, Firefox, Microsoft Edge,
Internet Explorer etc.

Adding JavaScript to HTML Pages:

 JavaScript can either be embedded directly inside the HTML page

(or)

 Placed in an external script file and referenced inside the HTML page.

 Both methods use the <script> element.

Embedding JavaScript:

Add the code as the content of a <script> element.

Example:

<!DOCTYPE html>
<head>
<title>Embedding JavaScript</title>
</head>
<body>
<script> document.innerHTML = "Hello World!"; </script>
</body>
</html>
Calling External JavaScript File:
 Place your JavaScript code into a separate file (with a .js extension)
 and call that file in your HTML document through the src attribute of
the <script> tag.
 This is useful if you want the same script available to multiple documents.

Example:
<!DOCTYPE html>
<html lag="en">
<head>
<title>Linking External JavaScript</title>
</head>
<body>
<div id="greet"></div>
<script src="/examples/js/hello.js"></script>
</body>
</html>

Hello.js

<script> document. innerHTML = "Hello World!"; </script>

The HTML no script Element:

 The <noscript> element is used to provide an alternate content for users


 that have either disabled JavaScript in their browser or have a browser that doesn't
support client-side scripting.
 This element can contain any HTML elements, aside from <script>, that can be included
in the <body> element of a normal HTML page.
Example:

<html lang="en">
<head>
<title>Noscript Demo</title>
</head>
<body>
<div id="greet"></div>
<script> document.getElementById("greet").innerHTML = "Hello World!";
</script>
<noscript>
<p>Oops! This website requires a JavaScript-enabled browser.</p> </noscript>
</body>
</html>
Difference between Java and Java Script:

S. No Java JavaScript

1 Java is a programming Java Scriptis a scripting language.


language.

2 Java is an object oriented Java Script is not a object oriented


programming language. programming language.

3 Java is strongly typed Weakly typed language.


language.

4 Objects in java are static. Objects are dynamic.


i.e. fixed at compile time.

Uses of JavaScript :

 JavaScript can be used as an alternative to Java Applets. Java applets


 need to be downloaded, however JavaScript need not be downloaded
 and used as embedded in XHTML document.
 Java Script can be embedded in XHTML.
 JavaScript can be effectively used for interaction with the users.
 Using DOM JavaScript can access and modify the properties of CSS and contents of
XHTML document.
 Used to detect the visitors browsers and can load the page accordingly.
 Used to create cookies.
 Used to validate the data on the web page before submitting it to the server.

Identifiers:
Identifiers are the names given to the variables. These variables hold the
data value.
1. Must begin with either letter or underscore or dollar sign, followed by any number of
letters, underscore, dollars or digits.
2. No limit in the length of identifier.
3. Case sensitive.

Reserved Words:
Various reserved words used in JavaScript are
Comments

break continue delete for in return throw var with

case default else function instanceof switch try void

catch do finally if new this typeof while

JavaScript supports following comments:


1. // Single line comment
2. /* and */ multi line comment
3. <!--> and <--> also allowed

Declaring variables:
 JavaScript variables are containers for storing data values.
 All JavaScript variables must be identified with unique names. These
unique names are called identifiers.
 Identifiers can be short names (like x and y) or more descriptive names
 (age, sum, totalVolume).
The general rules for constructing names for variables (unique identifiers)
are:
• Names can contain letters, digits, underscores, and dollar signs.
• Names must begin with a letter
• Names can also begin with $ and _
• Names are case sensitive (y and Y are different variables)
• Reserved words (like JavaScript keywords) cannot be used as names
• Java Script is identifiers are case sensitive
var x=6;
var x=5;
Primitive Type:
 JavaScript defines two entities- primitive and objects
 primitives- storing the values
 object-storing the reference to the actual value.
Primitive types used in JavaScript are:
1. Number
2. String
3. Boolean
4. Undefined
5. Null
Literals:
JavaScript defines two literals:
a) Numeric Literals(Numbers)- include integer values, floating point or double precision
values.
Eg: 10 10.3 10.0
b) String Literals- Sequence of characters enclosed in double or single quotes.
Eg: “hello” ‘hello’
Other Primitive Types:
1. Boolean – true/false
2. Null- use keyword null- means no value.
3. Undefined- If a variable is explicitly declared and not assigned any value to it then it is
an undefined value. No reserved word for undefined. The browser displays it.

Declaring Variables
In JavaScript variables are declared using the reserved word var.

<html>
<body>
<script type="text/javascript">
var a,b,c; var string; a=2;
b=3;
c=a+b;
string="The result="; document.write("string"); document.write("c");
</center>
</body>
</html>

Scope of variables:

 In JavaScript, objects and functions are also variables.


 In JavaScript, scope is the set of variables, objects, and functions you have
access to.
 JavaScript has function scope: The scope changes inside functions.

Local JavaScript Variables:

 Variables declared within a JavaScript function, become LOCAL to the function.


 Local variables have local scope: They can only be accessed within the function.

// code here can not use carName


function myFunction() { var carName = "Volvo";
// code here can use carName
}
 Since local variables are only recognized inside their functions, variables with the same
name can be used in different functions.
 Local variables are created when a function starts, and deleted when the function is
completed.
Global JavaScript Variables
 A variable declared outside a function, becomes GLOBAL.

 A global variable has global scope: All scripts and functions on a web page can access it.

var carName = " Volvo";

// code here can use carName

function myFunction() {

// code here can use carName

JavaScript Arithmetic Operators

Operator Use

+ Addition

- Subtraction

* Multiplication

/ Division

% Modulus

++ Increment

-- Decrement
JavaScript Assignment Operators

Operator Use

= Assignment

+= Increment assignment

-= Decrement assignment

*= Multiplication assignment

/= Division assignment

%= Modulus assignment

Assignment Operators

Assignment Initial Sample Explanation ASSIGNS


Operator variable expression
Value
+= c=3 c += 7 c=c+7 10 to c

-= d=5 d -= 4 d=d–4 1 to d
*= e=4 e *= 5 e=e*5 20 to e
/= f=6 f /= 3 f=f/3 2 to f

%= g = 12 g %= 9 g=g%9 3 to g

Adding Integers program:


<HTML>
<HEAD>
<TITLE>An Addition Program</TITLE>
<SCRIPT LANGUAGE=“JavaScript”>
var firstNumber, // first string entered by user
secondNumber, // second string entered by user
number1, // first number to add
number2, // second number to add
sum; // sum of number1 and number2

// read in first number from user as string


firstNumber = window.prompt( “Enter first integer”, “0’ );
// read in second number from user as string
secondNumber = window.prompt( “Enter second integer”, “0’ );

// convert numbers from strings to integers


number1 = parseInt(firstNumber);
number2 = parseInt(secondNumber);

// add the numbers


sum = number1 + number2;

// display the results


document.writeln( “<H1>The sum is “ + sum + “</H1>”);

</SCRIPT>
</HEAD>
<BODY>
</BODY>
</HTML>
JavaScript Comparison Operators:

Operator Use

== Is equal to

=== Exactly equal to – in value and type

!= Is not equal to

> Is greater than

< Is less than

>= Is greater than or equal to

<= Is less than or equal to

JavaScript Logical Operators:

Operator Use

&& And

││ Or

! Not
Demonstrating the Logical Operators:

<HTML>
<HEAD>
<TITLE>Demonstrating the logical operators</TITLE>
<SCRIPT LANGUAGE="JavaScript">
document.writeln( "<TABLE BORDER='10' WIDTH='100%'>" );
document.writeln(
"<TR><TD WIDTH= '25%'>Logical AND (&&)</TD>" +
"<TD>false && false: " + ( false && false ) +
"<BR>false && true: " + ( false && true ) +
"<BR>true && false: " + ( true && false ) +
"<BR>true && true: " + ( true && true ) + "</TD>" );
document.writeln(
"<TR><TD WIDTH= '25%'>Logical OR (||)</TD>" +
"<TD>false || false: " + ( false || false ) +
"<BR>false || true: " + ( false || true ) +
"<BR>true || false: " + ( true || false ) +
"<BR>true || true: " + ( true || true ) + "</TD>" );
document.writeln(
"<TR><TD WIDTH= '25%'>Logical NOT (!)</TD>" +
"<TD>!false: " + ( !false ) +
"<BR>!true: " + ( !true ) + "</TD>" );

doccument.writeln( "</TABLE>" );
</SCRIPT>
</HEAD>
<BODY>
</BODY>
</HTML>
Java Script: Functions
 A JavaScript function is a block of code designed to perform a particular
task.
 A JavaScript function is executed when "something" invokes it (calls it).
JavaScript Function Syntax:

function name(parameter1, parameter2, parameter3)


{
// code to be executed
}
Function Invocation
 The code inside the function will execute when
"something" invokes (calls) the function:
 When an event occurs (when a user clicks a button)
 When it is invoked (called) from JavaScript code
 Automatically (self invoked)
Function Return
 When JavaScript reaches a return statement, the function will stop
executing.
 If the function was invoked from a statement, JavaScript will "return"
to execute the code after the invoking statement.
 Functions often compute a return value. The return value is "returned"
back to the "caller“.
<html>
<body>
<h2>JavaScript Functions</h2>
<p>This example calls a function which performs a calculation and
returns the result:</p>
<p id="demo"></p>
<script>
var x = myFunction(4, 3);
document.getElementById("demo").innerHTML = x;
function myFunction(a, b) {
return a * b;
}
</script>
</body>
</html>
JavaScript: Control Statements
 Statements that are used to control the flow of execution in a script are known as control
statements.
 Control statements are used along with compound statements (a set of statements
enclosed in braces).
 If selection Statement
 if…else Selection statement
 while Repetition Statement

if Statement
 Statements which are used to execute a set of statements based on a condition are known
as selection statements.
 In JavaScript selection statements are: if, if-else and switch.
Syntax for an if statement is shown below:
if(expression)
{
statement(s);
}

If – else
Syntax for an if-else statement is shown below:
if(expression)
{
statement(s);
}
else
{
statement(s);
}
Syntax of a switch statement

switch(expression)
{
case label1:
statement(s);
break;
case label2:
statement(s);
break;
...
default:
statement(s);
}

Loop Statements

 Statements which are used to execute a set of statements repeatedly


based on a condition are known as loop statements or iteration
statements.
 Loop statements supported by JavaScript are while, do-while, for and
for-in.

Syntax of while loop

while(condition)
{
statement(s);
}

Syntax for do-while loop

do
{
statement(s);
}
while(condition);
 In a do-while statement condition is evaluated after the body of the loop is
executed.
 So, the difference between while and do-while is, unlike in while loop, the
body of the loop is guaranteed to be executed at least once in a do-while
loop.
Syntax of a for loop

for(initialization; condition; increment/decrement expression)


{
statement(s);
}

POPUP BOXES

alert box:
In this type of popup box some messages will be displayed.

confirm box:

 A confirm box is often used if you want the user to verify or accept something.
 When a confirm box pops up, the user will have to click either "OK" or "Cancel" to
proceed.
 If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box returns
false.
Prompt Box:

 A prompt box is often used if you want the user to input a value before
entering a page.
 When a prompt box pops up, the user will have to click either "OK" or
"Cancel" to proceed after entering an input value.
 If the user clicks "OK" the box returns the input value. If the user clicks
"Cancel" the box returns null.

Example:
<html>
<body>
<script type="text/javascript"> if(confirm("do you agree?"))
alert("You have agreed");
else
p=prompt("Enter something"); alert("Hi"+p);
</script>
</body>
</html>

What is an Event ?

 JavaScript's interaction with HTML is handled through events that occur when the user or
the browser manipulates a page.
 When the page loads, it is called an event. When the user clicks a button, that click too is
an event. Other examples include events like pressing any key, closing a window,
resizing a window, etc.
 Developers can use these events to execute JavaScript coded responses, which cause
buttons to close windows, messages to be displayed to users, data to be validated, and
virtually any other type of response imaginable.
 Events are a part of the Document Object Model (DOM) Level 3 and every HTML
element contains a set of events which can trigger JavaScript Code.

Event Handlers

 Event handler is a script that gets executed in response to these events. Thus event
handler enables the web document to respond the user activities through the browser
window.
 JavaScript supports this special type of programming in which events may occur and
these events get responded by executing the event handlers. This type of programming is
called event-driven programming.
 Events are specified in lowercase letters and these are case-sensitive. The process of
connecting event handler to an event is called event registration.
Events, Attributes and Tags
 On occurrence of events the tag attribute must be assigned with some user defined
functionalities. This will help to execute certain action on occurrence of particular event.

Intrinsic event Meaning Associated Tag


attribute

onblur Losing the focus <button>, <input>,

<a>, <textarea>,

<select>

onchange On occurrence of some <input>, <textarea>,


change
<select>

onclick When user clicks the <a>, <input>

mouse button

onfocus When user acquires the input <a>, <input>,


focus.
<select>, <textarea>
onkeyup When user releases the <input>,<button>,

key from the keyboard <textarea> etc..

Intrinsic event Meaning Associated Tag


attribute

onkeydown When user presses the key <input>, <button>,


down
<textarea> etc..

onkeypress When user presses the key. <input>, <button>,

<textarea> etc..

onmousedown When user clicks the left <input>, <button>,

mouse button <textarea> etc..

onmouseup When user releases the left <input>, <button>,


mouse button
<textarea>

onmousemove When user moves the mouse <input>,<button>,

<textarea> etc..

onmouseout When the user moves the <input>,<button>,


mouse away over some
<textarea> etc..
element

onmouseover When the user moves the <input>,<button>,


mouse away over some
elemnt B. MADHURAVANI <textarea> etc..
 onclick: Use this to invoke JavaScript upon clicking (a link, or form boxes)
 onload: Use this to invoke JavaScript after the page or an image has finished
 loading.
 onmouseover: Use this to invoke JavaScript if the mouse passes by some link
 onmouseout: Use this to invoke JavaScript if the mouse goes pass some link
 onunload: Use this to invoke JavaScript right after someone leaves this page.
 onsubmit: The onsubmit attribute fires when a form is submitted.

Examples:
Example-1:
Onload:
The onload event gets activated as soon as the web page gets loaded in the browsers
window.
<html>
<head>
<script type="text/javascript"> function my_fun()
{
alert("welcome");
}
</script>
</head>
<body onload="my_fun()">
</body>
</html>
Example-2:
onclick
For handling the event using button element we have used the tag attribute onclick.
<html>
<head>
<script type="text/javascript">
function my_fun()
{
alert("Hello I am in Function");
}
</script>
</head>
<body>
<form>
<input type="button" value="CLICK" onclick="my_fun()">
</form>
</body>
</html>
Example 3:
<html>
<head>
<script type="text/javascript">
function my_fun(form_obj)
{
alert("Your favourite color is "+form_obj.value);
}
</script>
</head>
<body>
<form name="form1" method=post>
<div align="left"><br/>
<input type="radio" name="group1" value="RED" onclick=my_fun(this)>RED<br/>
<input type="radio" name="group1" value="BLUE" onclick=my_fun(this)>BLUE<br/>
<input type="radio" name="group1" value="GREEN" onclick=my_fun(this)>GREEN<br/>
<input type="radio" name="group1" value="YELLOW" onclick=my_fun(this)>YELLOW<br/>
<input type="radio" name="group1" value="ORANGE" onclick=my_fun(this)>ORANGE<br/>
</div>
</form>
</body>
</html>

Example-4:
On mouse over, on mouse out:

<html> <head>
<script type = "text/javascript">
function over() {
document.write ("Mouse Over");
}
function out()
{
document.write ("Mouse Out");
}

</script>
</head>
<body>
<p>Bring your mouse inside the division to see the result:</p>
<div onmouseover = "over()" onmouseout = "out()">
<h2> This is inside the division </h2> </div>
</body>
</html>

Example-5:
onsubmit()
<html>
<body>
<p>When you submit the form, a function is triggered which alerts some
text.</p>
<form onsubmit="myFunction()">
Enter name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
<script>
function myFunction() {
alert("The form was submitted");
}
</script>
</body>
</html>

Objects

 In JavaScript object is a collection of properties. These properties are nothing but the
 members of the classes from Java or C++. For instance- in JavaScript the object Date() is
used which happens to the member of class in Java.
 The property can be of two types either a data type or a function type.
The data properties are sometimes called as properties and method properties are called
as methods or functions.
 Object is a root object in JavaScript. All other objects are formed from this Object using
prototype inheritance.

Math Objects
 For performing the mathematical computations there are some useful methods available
from math object.

Eg: document.write(math.min(4.5,7.8))

sqrt(num) abs(num) ceil(num) floor(num) log(num)

pow(a,b) min(a,b) max(a,b) sin(num) cos(num)

tan(num) exp(num)

<html>
<body>
<h3>Square Root of 100 is</h3>
<script type="text/javascript">
var num=100; document.write("<h3>"+Math.sqrt(num)+"</h3>");
</script>
</body>
</html>
Number Objects
Various properties of number object are-

Property Meaning

MAX_VALUE Largest possible number gets displayed.

MIN_VALUE Smallest possible number gets displayed.

NaN When not a number then NaN is displayed

PI The value of PI gets displayed.

POSITIVE_INFINITY The positive infinity gets displayed.

NEGATIVE_INFINITY The negative infinity gets displayed.

Date Objects
This object is used for obtaining the date and time.

Method Meaning

getDate() Returns the day of the month (from 1-31)

getDay() Returns the day of the week (from 0-6)

getFullYear() Returns the year

getHours() Returns the hour (from 0-23)

getMilliseconds() Returns the milliseconds (from 0-999)

getMinutes() Returns the minutes (from 0-59)

getMonth() Returns the month (from 0-11)

getSeconds() Returns the seconds (from 0-59)

getTime() Returns the number of milliseconds since midnight Jan 1 1970, and a
specified date
setDate() Sets the day of the month of a date object

setFullYear() Sets the year of a date object

setHours() Sets the hour of a date object

setMilliseconds() Sets the milliseconds of the date object

Example:
<html>
<body>
<script type="text/javascript">
var my_date=new Date();
document.write("The date is: "+my_date.toString()+"<br>");
document.write("Todays date is: "+my_date.getDate()+"<br>");
document.write("This is the month of: "+my_date.getMonth()+"<br>");
document.write("The current year is: "+my_date.getFullYear()+"<br>");
document.write("NowHour= "+my_date.getHours()+"<br>");
document.write("Minutesr= "+my_date.getMinutes()+"<br>");
document.write("Seconds= "+my_date.getSeconds()+"<br>");
</script>
</body>
</html>

Boolean Objects
 Used to represent true and false values.

<html>
<body>
<script type="text/javascript">
var bb=new Boolean(true);
document.write(“The Boolean Value is..“+bb.toString());
</script>
</body>
</html>

String Objects

concat(str) charAt(Index_val)

substring(begin,end) toLowerCase()

toUpperCase() valueOf()

length() split(delimiter)
Example:
<html>
<body>
<script type="text/javascript">
var str1="Hello"
var str2=”GCET"
document.write("String1 = " +str1+"<br>"); document.write("String2 = " +str2+"<br>");
document.write("String1 Length= " +str1.length+"<br>");
document.write("Concatenation = " +str1.concat(str2)+"<br>");
document.write("String1 in Uppercase= " +str1.toUpperCase()+"<br>");
</script>
</body>
</html>

Document Object Model (DOM)

 The DOM is a W3C (World Wide Web Consortium) standard.


 The DOM defines a standard for accessing documents:
 "The W3C Document Object Model (DOM) is a platform and language-neutral interface
that allows programs and scripts to dynamically access and update the content, structure,
and style of a document."

The W3C DOM standard is separated into 3 different parts:

 Core DOM - standard model for all document types


 XML DOM - standard model for XML documents
 HTML DOM - standard model for HTML documents
 The HTML DOM (Document Object Model)

When a web page is loaded, the browser creates a Document Object Model of the page. The
HTML DOM model is constructed as a tree of Objects:
With the object model, JavaScript gets all the power it needs to create dynamic HTML:
 JavaScript can change all the HTML elements in the page
 JavaScript can change all the HTML attributes in the page
 JavaScript can change all the CSS styles in the page
 JavaScript can remove existing HTML elements and attributes
 JavaScript can add new HTML elements and attributes
 JavaScript can react to all existing HTML events in the page
 JavaScript can create new HTML events in the page

JavaScript HTML DOM Elements


Finding HTML Elements

Often, with JavaScript, you want to manipulate HTML elements.

To do so, you have to find the elements first. There are several ways to do this:

 Finding HTML elements by id


 Finding HTML elements by tag name
 Finding HTML elements by class name
 Finding HTML elements by CSS selectors
 Finding HTML elements by HTML object collections

Finding HTML Element by Id


The easiest way to find an HTML element in the DOM, is by using the element id.
This example finds the element with id="intro":

 If the element is found, the method will return the element as an object (in myElement).
 If the element is not found, myElement will contain null.
Finding HTML Elements by Tag Name

This example finds all <p> elements:

Finding HTML Elements by Class Name


 If you want to find all HTML elements with the same class name,
use getElementsByClassName().
 This example returns a list of all elements with class="intro".

Finding HTML Elements by CSS Selectors

If you want to find all HTML elements that match a specified CSS selector (id, class names,
types, attributes, values of attributes, etc), use the querySelectorAll() method.

This example returns a list of all <p> elements with class="intro".


Finding HTML Elements by HTML Object Collections

This example finds the form element with id="frm1", in the forms collection, and displays all
element values:

<!DOCTYPE html>
<html>
<body>

<h2>Finding HTML Elements Using document.forms</h2>

<form id="frm1" action="/action_page.php">


First name: <input type="text" name="fname" value="Donald"><br>
Last name: <input type="text" name="lname" value="Duck"><br><br>
<input type="submit" value="Submit">
</form>

<p>Click "Try it" to display the value of each element in the form.</p>

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

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

<script>
function myFunction() {
var x = document.forms["frm1"];
var text = "";
var i;
for (i = 0; i < x.length ;i++) {
text += x.elements[i].value + "<br>";
}
document.getElementById("demo").innerHTML = text;
}
</script>

</body>
</html>

Form Validation

 It is important to validate the form submitted by the user because it can have
 inappropriate values. So validation is must. The JavaScript provides you the facility the
validate the form on the client
 side so processing will be fast than server-side validation. So, most of the web
developers prefer JavaScript form validation.
 Through JavaScript, we can validate name, password, email, date, mobile
number etc fields.
 JavaScript provides facility to validate the form on the client-side so data processing will
be faster than server-side validation.
 Through JavaScript, we can validate name, password, email, date, mobile numbers and
more fields.
 In this example, we are going to validate the name and password.
 The name can’t be empty and password can’t be less than 6 characters long.

Example:

<html>
<body>
<script>
function validateform()
{
var name=document.myform.name.value;
var password=document.myform.password.value;
if (name==null || name=="")
{
alert("Name can't be blank");
return false;
}else if(password.length<6){
alert("Password must be at least 6 characters long.");
return false;
}
}
</script>
<body>
<form name="myform" method="post"
action="http://www.javatpoint.com/javascriptpages/valid.jsp" onsubmit="return
validateform()" >
Name: <input type="text" name="name"><br/>
Password: <input type="password" name="password"><br/>
<input type="submit" value="register">
</form>
</body>
</html>

JavaScript Retype Password Validation


<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function matchpass(){
var firstpassword=document.f1.password.value;
var secondpassword=document.f1.password2.value;
if(firstpassword==secondpassword){
return true;
}
else{
alert("password must be same!");
return false;
}
}
</script>
</head>
<body>
<form name="f1"
action="http://www.javatpoint.com/javascriptpages/valid.jsp"
onsubmit="return matchpass()">
Password:<input type="password" name="password" /><br/>
Re-enter Password:<input type="password" name="password2"/><br/>
<input type="submit">
</form>
</body>
</html>

JavaScript email validation


We can validate the email by the help of JavaScript.
There are many criteria that need to be follow to validate the email id such as:
 email id must contain the @ and . character
 There must be at least one character before and after the @.
 There must be at least two characters after . (dot).

<html>
<body>
<script>
function validateemail()
{
var x=document.myform.email.value;
var atposition=x.indexOf("@");
var dotposition=x.lastIndexOf(".");
if (atposition<1 || dotposition<atposition+2 || dotposition+2>=x.length){
alert("Please enter a valid e-mail address \n atpostion:"+atposition+"\n
dotposition:"+dotposition);
return false;
}
}
</script>
<body>
<form name="myform" method="post"
action="http://www.javatpoint.com/javascriptpages/valid.jsp" onsubmit="return
validateemail();">
Email: <input type="text" name="email"><br/>

<input type="submit" value="register">


</form>
</body>
</html>

You might also like