0% found this document useful (0 votes)
41 views178 pages

Introduction to HTML Basics and Structure

HTML (HyperText Markup Language) is the standard language for creating and structuring web content, forming the backbone of all websites. It consists of various tags that define elements like headings, paragraphs, and multimedia, and is complemented by CSS and JavaScript for styling and interactivity. The document also covers HTML's history, advantages, disadvantages, and basic structure, including the use of comments and text formatting.

Uploaded by

t.ambika1991
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views178 pages

Introduction to HTML Basics and Structure

HTML (HyperText Markup Language) is the standard language for creating and structuring web content, forming the backbone of all websites. It consists of various tags that define elements like headings, paragraphs, and multimedia, and is complemented by CSS and JavaScript for styling and interactivity. The document also covers HTML's history, advantages, disadvantages, and basic structure, including the use of comments and text formatting.

Uploaded by

t.ambika1991
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

UNIT – 1

INTRODUCTION TO HTML (HYPERTEXT MARKUP LANGUAGE)

1. Introduction to HTML

HTML stands for HyperText Markup Language. It is the standard language


used to create and structure content on the web.

It provides the basic structure of a webpage, which can be enhanced and


modified by other technologies like CSS (Cascading Style Sheets) and
JavaScript.

HTML is a markup language, not a programming language, meaning it


annotates text to define how it is structured and displayed by web browsers.

It forms the building blocks of all websites and is complemented by CSS for
style and JavaScript for interactivity.

In a nutshell, HTML is all about organizing and displaying information on a


webpage. We can think of it as the bones or structure of a webpage.

Basic HTML Code Example

<!DOCTYPE html>

<html>

<head>

<title>My First Webpage</title>

</head>

<body>

<h1>Welcome to My Webpage</h1>

<p>This is my first paragraph of text!</p>

1
</body>

</html>

Features of HTML

 It is easy to learn and easy to use.


 It is platform-independent.
 Images, videos, and audio can be added to a web page.
 Hypertext can be added to the text.
 It is a markup language.

HTML History

Currently, we are using HTML5, which is the latest and most advanced
version of HTML.

HTML was initially created by Tim Berners-Lee in 1991 as a way to share and
structure documents on the web.

The first-ever version was HTML 1.0, a basic and limited version. However,
the first standardized version, HTML 2.0, was published in 1995, laying the
foundation for web development as we know it today

2
Advantages of HTML

 HTML is used to build websites.


 It is supported by all browsers.
 It can be integrated with other languages like CSS, JavaScript, etc.

Disadvantages of HTML

 HTML can only create static web pages. For dynamic web pages, other
languages have to be used.
 A large amount of code has to be written to create a simple web page.
 The security feature is not good.

HTML Element and HTML Tag

HTML Element and HTML Tags are related but distinct. An HTML element is
the complete structure, including the opening tag, content (if any), and the
closing tag (if applicable).

On the other hand, A tag is the actual keyword or name enclosed in angle
brackets (< >) that tells the browser what kind of content to expect.

3
2. HTML Tag Basics

Every HTML document begins with a document type declaration, setting the
foundation for the webpage. This section introduces basic HTML tags that
structure the page, such as <head>, <body>, and <title>. Although this is not
mandatory, it is a good convention to start the document with the below-
mentioned tag.

Basic Structure Tags

Tag Description Syntax Example


<!DOCTYPE Declares the <!DOCTYPE None
html> document type html>
as HTML5.
<html> Root element of <html> ... <html lang="en"> ...
an HTML </html> </html>
document.
<head> Contains <head> ... <head><title>Title</title>
metadata about </head> </head>
the document.
<body> Defines the <body> ... <body><p>Hello
document's </body> World!</p></body>
body content.
<!--...--> It is used to <!--This <!--This Comment line --
write Comments line >
comments in -->
HTML
documents
<br> It defines a line <br> <p>Hello</p>
break <br>
<hr> It creates a <hr> <p>Hello</p>
horizontal line <hr>
in a webpage

4
<h1> to These are a <h1>..</h1> <h1>This h1 tag</h1>
<h6> group of to <h6>..</h6> <h6>This h6 tag</h6>
heading tags
used to create
heading in a
webpage

Types of Tags:

i). Paired and Unpaired Tags

Paired Tags:

An HTML tag is known as a paired tag when the tag consists of an opening
tag and a closing tag as its companion tag. An HTML Paired tag starts with
an opening tag: the tag name enclosed inside the angle brackets; for example,
a paragraph opening tag is written as ‘<p>’. The content follows the opening
tag, which ends with an ending tag: the tag name starting with a forward
slash; for example, an ending paragraph tag is written as ‘</p>’. The first tag
can be referred to as the ‘Opening Tag’, and the second tag can be called
Closing Tag.

Example 1:

<p> This text is a paragraph. </p>

Output:

This text is a paragraph.

NOTE: Here, the opening tag is, and the closing tag is </p>.

Example 2:

<i> <b> This is a bold and italicized text </b> </i>

Output:

This is a bold and italicized text

5
NOTE: These paired tags are also called Container Tags.

Unpaired Tags:

An HTML tag is called an unpaired tag when the tag only has an opening tag
and does not have a closing tag or a companion tag. The Unpaired HTML tag
does not require a closing tag; an opening tag is sufficient in this type.
Unpaired tags are sometimes also named as Standalone Tags or Singular Tags
since they do not require a companion tag.

Example:

<p> This is a paragraph </p>

<hr>

<i> <b> This is a bold and italicized text </b> </i>

Output:

This is a bold and italicized text

NOTE: Here, the <hr> is the unpaired tag used to create a horizontal line. In
older versions, you might see hr tag written as <hr/> instead of <hr>. These
tags are also called Empty Tag.

ii). Self-Closing Tags

Self-Closing Tags are those HTML tags that do not have a partner tag, where
the first tag is the only necessary tag that is valid for the formatting. The main
and important information is contained WITHIN the element as its attribute.
An image tag is a classic example of a self-closing tag.

Example:

<img src="[Link]" alt="This is an alternate text">

6
Note: In the older versions, the self-closing tags use a ‘forward slash’ before
the ending or closing ‘greater than’ sign/symbol, as written below:

<img src=”[Link]” alt=”This is an alternate text” />

3. HTML Page Structure

The basic structure of an HTML page is shown below. It contains the essential
building-block elements (i.e. doctype declaration, HTML, head, title, and body
elements) upon which all web pages are created.

 <!DOCTYPE html> – This is the document type declaration, not a tag.


It declares that the document is an HTML5 document.
 <html> – This is called the HTML root element. All other elements are
contained within it.

7
 <head> – The head tag contains the “behind the scenes” elements for a
webpage. Elements within the head aren’t visible on the front end of a
webpage. Typical elements inside the <head> include:
o <title>: Defines the title displayed on the browser tab.
o <meta>: Provides information like the character set or viewport
settings.
o <link>: Links external stylesheets or resources.
o <style>: Embeds internal CSS styles.
o <script>: Embeds JavaScript for functionality.
 <title> – The title is what is displayed on the top of your browser when
you visit a website and contains the title of the webpage that you are
viewing.
 <h2> – The <h2> tag is a second-level heading tag.
 <p>– The <p> tag represents a paragraph of text.
 <body> – The body tag is used to enclose all the visible content of a
webpage. In other words, the body content is what the browser will
show on the front end.

Example:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8" />

<meta name="viewport" content=

"width=device-width, initial-scale=1.0" />

<title>Structure of HTML Document</title>

</head>

<body>

8
<!-- Main content of website -->

<h1>GeeksforGeeks</h1>

<p>A computer science portal for geeks</p>

</body>

</html>

HTML Basic Structure

9
4. Adding Comments

HTML Comments are text in an HTML document that is not displayed by the
browser. They allow you to leave notes and explanations directly in the code,
which can be especially helpful during the development process or when you
need to make future updates.

To add a comment in your HTML code, you enclose the text you want to hide
from display within <!-- and -->

HTML Comment – Example:

<!-- This is a comment and will not be displayed on the webpage -->

<p>This is visible text.</p>

In this example:

 The text within the <!-- and --> tags will not appear on the webpage.
 These comments can include reminders, warnings, or explanations
about the code, which can be useful for anyone reading or editing the
HTML document.

Different Ways to Add Comments in HTML

There are two main ways to write comments in HTML: single-line and multi-
line comments. Both use the same basic syntax but differ in how they are
implemented

Comment Description Syntax


Type
Single-line A single-line comment is enclosed within <!-- This is a
<!-- and --> tags. comment -->
Multi-line Multiple lines of comments are enclosed <!-- Line 1 <br>
using the same syntax as single-line Line 2 <br> Line 3 -
comments but span several lines. ->

10
Uses of HTML Comments:

 Code Organization: Comments can help break up sections of code,


making it easier to navigate, especially in larger projects.
 Collaboration: When working with others, comments are crucial for
explaining why certain HTML elements are used, or for leaving
instructions for team members.
 Debugging: Temporarily disabling parts of HTML code by commenting
them out is a common use, allowing developers to isolate issues.
 Documentation: Providing details or documentation within the code
for future reference without the need for external documentation.

5. Working with Texts, Paragraphs, and Line Breaks

i.) Text in HTML

Text in HTML is displayed using various tags that define the structure, style,
and organization of the content. The most common tags used to control text
are <p>, <br>, <h1> to <h6>, <b>, <i>, <u>, and others.

ii.) Paragraphs (<p> tag)

 Paragraphs are used to separate blocks of text for better readability.


 The <p> tag automatically adds space before and after the paragraph,
making the text easier to read.

Example:

<p>This is a paragraph of text in HTML. Paragraphs are used to divide text


into distinct sections.</p>

<p>This is another paragraph.</p>

iii.) Line Breaks (<br> tag)

 The <br> tag is used to create a line break within text without starting
a new paragraph.

11
 Unlike the <p> tag, the <br> tag does not add any extra space and
continues the same paragraph from a new line.

Example:

<p>This is an example of text with a line break.<br>This line will appear right
below without extra spacing.</p>

Tag Description Example


<p> Defines a paragraph of text. <p>This is a
paragraph.</p>
<br> Inserts a line break in the text. First
line.<br>Second
line.
Text Use other tags like <b>, <i>, <u> for bold, <b>Bold</b>,
Styling italic, and underlined text. <i>Italic</i>,
<u>Underline</u>

6. Emphasizing Text

HTML provides several tags to emphasize text, each serving a specific purpose:

12
i.) Bold (<b> and <strong> Tags):

 The <b> tag makes text bold, but it does not add any extra importance
to the text.
 The <strong> tag also makes text bold but indicates that the text is of
strong importance.

Example:

<p>This is <b>bold</b> text.</p>

<p>This is <strong>important</strong> text.</p>

ii.) Italic (<i> and <em> Tags):

 The <i> tag italicizes text without adding any importance.


 The <em> tag italicizes text and indicates that the text has stress
emphasis.

Example:

<p>This is <i>italic</i> text.</p>

<p>This is <em>emphasized</em> text.</p>

iii.) Mark (<mark> Tag):

 The <mark> tag highlights text with a background color, usually yellow,
to indicate relevance.

Example:

<p>This is <mark>highlighted</mark> text.</p>

iv.) Small (<small> Tag):

 The <small> tag makes the text smaller than the surrounding text.

Example:

<p>This is <small>small</small> text.</p>

13
v.) Subscript and Superscript (<sub> and <sup> Tags):

 The <sub> tag displays text as subscript (below the text line).
 The <sup> tag displays text as superscript (above the text line).

Example:

<p>This is <sub>subscript</sub> text.</p>

<p>This is <sup>superscript</sup> text.</p>

vi.) Insert and Delete (<ins> and <del> Tags):

 The <ins> tag underlines text to show inserted text.


 The <del> tag strikes through text to show deleted text.

Example:

<p>This is <ins>inserted</ins> text.</p>

<p>This is <del>deleted</del> text.</p>

Combining Emphasis Tags

You can also combine these tags to create text with multiple forms of
emphasis.

Example:

<!DOCTYPE html>

<html>

<head>

<title>Combining Emphasis Tags</title>

</head>

<body>

<p>This text is <strong><em>strongly emphasized</em></strong> and


<mark>highlighted</mark>.</p>

14
<p>This text is <b>bold</b> and <i>italic</i>, with <sub>subscript</sub>
and <sup>superscript</sup> elements.</p>

<p>This text includes <small>small text</small> and shows


<del>deleted</del> text as well as <ins>inserted</ins> text.</p>

</body>

</html>

Output:

Tag Effect Example


<b> Makes text bold. <b>Bold Text</b>
<strong> Bold with semantic <strong>Important Text</strong>
emphasis.
<i> Makes text italic. <i>Italic Text</i>
<em> Italic with semantic <em>Emphasized Text</em>
emphasis.
<u> Underlines text. <u>Underlined Text</u>
<mark> Highlights text. <mark>Highlighted Text</mark>
<small> Displays smaller text. <small>Smaller Text</small>
<sub> Displays subscript text. <sub>Subscript Text</sub>
<sup> Displays superscript <sup>Superscript Text</sup>
text.
<ins> Underlines inserted text. <ins>Inserted Text</ins>
<del> Strikes through deleted <del>Deleted Text</del>
text.

15
7. Headings and Horizontal Rules

i.) Headings (<h1> to <h6>):

HTML Headings are used to define the content hierarchy and structure of a
webpage. They range from <h1> to <h6>, with <h1> being the most important
heading and <h6> the least important. Proper use of headings helps improve
readability, SEO, and accessibility.

Syntax of HTML Headings:

Here’s the basic syntax for creating headings in HTML:

<!DOCTYPE html>

<html>

<body>

<h1> This is heading h1</h1>

<h2>This is heading h2</h2>

<h3>This is heading h3</h3>

<h4>This is heading h4</h4>

<h5>This is heading h5</h5>

<h6>This is heading h6</h6>

</body>

</html>

NOTE: the ‘h’ inside the tag should always be in lowercase.

16
Output:

<h1> – Main Heading (Largest)

 Represents the primary focus of the page, usually used for the main
title.
 Use only one <h1> tag per page for the best SEO practices.
 Makes it clear to both users and search engines what the main topic is.

<h2> – Subheadings

 Ideal for dividing the content into major sections.


 If the content has further subsections, use <h3> to create a logical flow.

<h3> to <h6> – Smaller Headings

 These heading levels are used for finer subdivisions, gradually


decreasing in size and importance.

17
 <h3> is used for subsections under <h2>, while <h4> to <h6> are used
for additional, less important subdivisions.
 <h6> defines the least important heading.

Customization in HTML Heading Tags

Example: Here’s how you can apply basic styles to HTML heading tags:

<!DOCTYPE html>

<html>

<body>

<h1>H1 Heading</h1>

<!-- With the help of Style attribute you can customize

the size of the heading, As done below-->

<h1 style="font-size: 50px">H1 with new size.</h1>

<!-- Here font-size is the property by which we can

modify the heading. Here we kept it 50px i.e. 50 pixels -->

</body>

</html>

Output:

18
ii.) Horizontal Rule (<hr>):

The <hr> tag in HTML is used to create a horizontal rule or line that visually
separates content.

NOTE: It is a self-closing tag and does not require an end tag. It also supports
the Global Attributes and Event Attributes.

<!DOCTYPE html>

<html>

<body>

<p>

There is a horizontal rule below this paragraph.

</p>

<hr>

<p>

This is a horizontal rule above this paragraph.

</p>

</body>

</html>

Output:

19
8. Lists

An HTML list is a structured record of related information used to display data


or information on web pages in an ordered or unordered form. Lists are
fundamental for organizing content in a clear and readable way.

Types of HTML Lists

There are three main types of lists in HTML:

1. Unordered Lists
2. Ordered Lists
3. Description Lists

Example: Basic example of HTML List

<!DOCTYPE html>

<html>

<head>

<title>GFG</title>

</head>

<body>

<h2>Welcome To GFG Learning</h2>

<h5>List of available courses</h5>

<ul>

<li>Data Structures & Algorithm</li>

<li>Web Technology</li>

<li>Aptitude & Logical Reasoning</li>

<li>Programming Languages</li>

</ul>

<h5>Data Structures topics</h5>

20
<ol>

<li>Array</li>

<li>Linked List</li>

<li>Stacks</li>

<li>Queues</li>

<li>Trees</li>

<li>Graphs</li>

</ol>

</body>

</html>

Output:

21
HTML List Tags

Here is the list of all lists tags HTML:

Tag Description
<ul> Defines an unordered list
<ol> Defines an ordered list
<li> Defines a list item
<dl> Defines a description list
<dt> Defines a term in a description list
<dd> Details the term in a description list

i.) Unordered List or Bulleted List:

The unordered list items are marked with bullets, also known as bulleted lists.
An unordered list starts with the <ul> tag, and each list item begins with the
<li> tag.

Syntax:

<ul> list of items </ul>

Attribute: This tag contains two attributes which are listed below:

 compact: It will render the list smaller.


 type: It specifies which kind of marker is used in the list.

Example: This example describes the unordered list.

<!DOCTYPE html>

<html>

<body>

<h2>Grocery list</h2>

<ul>

<li>Bread</li>

22
<li>Eggs</li>

<li>Milk</li>

<li>Coffee</li>

</ul>

</body>

</html>

Output:

ii.) HTML Ordered List:

In an ordered list, all list items are marked with numbers by default. An
ordered list starts with the <ol> tag, and each list item begins with the <li>
tag.

Syntax:

<ol>

<li>Item1</li>

<li>Item2</li>

<li>Item3</li>

</ol>

Attributes:

 compact: It defines the list should be compacted (compact attribute is


not supported in HTML5. Use CSS instead.).
 reversed: It defines that the order will be descending.

23
 start: It defines from which number or alphabet the order will start.
 type: It defines which type(1, A, a, I, and i) of the order you want in
your list of numeric, alphabetic, or roman numbers.

Example: This example illustrates the use of the reverse attribute, control list
counting & type attribute.

<!DOCTYPE html>

<html>

<head>

<title>HTML ol tag</title>

</head>

<body>

<h1 style="color: green">GFG</h1>

<h3>HTML ol tag</h3>

<p>reversed attribute</p>

<ol reversed>

<li>HTML</li>

<li>CSS</li>

<li>JS</li>

</ol>

<p>start attribute</p>

<ol start="5">

<li>HTML</li>

<li>CSS</li>

<li>JS</li>

</ol>

24
<p>type attribute</p>

<ol type="i">

<li>HTML</li>

<li>CSS</li>

<li>JS</li>

</ol>

</body>

</html>

Output:

25
iii.) Description List:

A description list is a list of terms, with a description of each term. The <dl>
tag defines the description list, the <dt> tag defines the term name, and the
<dd> tag describes each term.

Syntax:

<dl> Contents... </dl>

Example: This example describes the HTML Description List.

<!DOCTYPE html>

<html>

<body>

<h2>A Description List</h2>

<dl>

<dt>Coffee</dt>

<dd>- 500 gms</dd>

<dt>Milk</dt>

<dd>- 1 ltr Tetra Pack</dd>

</dl>

</body>

</html>

Output:

26
9. Font Size, Face, and Color (Deprecated in HTML5)

The HTML <font> Tag plays an important role in the web page to create an
attractive and readable web page. The font tag is used to change the color,
size, and style of a text and it was used in HTML4. The base font tag is used
to set all the text to the same size, color, and face.

NOTE: Font tag is not supported in HTML5.

<!DOCTYPE html>

<html>

<body>

<p>This is sample paragraph</p>

<font face="Arial" size="4" color="green">

This paragrap style by font tag

</font>

</body>

</html>

Output:

Syntax:

<font size="number" face="font_family"


color="color_name|hex_number|rgb_number">

27
Font Attributes

 Font Size
 Font Type
 Font Color

i.) Font Size

The Font size attribute is used to adjust the size of the text in the HTML
document using a font tag with the size attribute. The range of size of the font
in HTML is from 1 to 7 and the default size is 3.

<!DOCTYPE html>

<html>

<body>

<!--HTML font size tag starts here-->

<font size="1">GFG!</font><br />

<font size="2">GFG!</font><br />

<font size="3">GFG!</font><br />

<font size="4">GFG!</font><br />

<font size="5">GFG!</font><br />

<font size="6">GFG!</font><br />

<font size="7">GFG!</font>

<!--HTML font size tag ends here-->

</body>

</html>

28
Output:

ii.) Font Type

The Font type can be set by using face attribute with font tag in HTML
document. But the fonts used by the user need to be installed in the system
first.

<!DOCTYPE html>

<html>

<body>

<font face="Times New Roman" size="6">

Times New Roman!!

</font><br />

<font face="Verdana" size="6">

Verdana!!

</font><br />

29
<font face="Comic sans MS" size=" 6">

Comic sans MS!!

</font><br />

<font face="WildWest" size="6">

WildWest!!

</font><br />

<font face="Bedrock" size="6">

Bedrock!!

</font><br />

</body>

</html>

Output:

30
iii.) Font Color

The Font color is used to set the text color using a font tag with the color
attribute in an HTML document. Color can be specified either with its name
or with its hex code.

<!DOCTYPE html>

<html>

<body>

<font color="#009900">Font color Type 1</font><br />

<font color="green">Font color Type 2</font>

</body>

</html>

Output:

10. Alignment and Links

i.) Alignment:

HTML align Attribute in HTML is used to specify the alignment of the text
content of The Element. This attribute is used in all elements. The Align
attribute can also be set using the CSS property “text-align: ” or in <img>
“vertical-align: “. For horizontal alignment, use align with values like “left,”
“center,” or “right” within appropriate tags.

NOTE: The align attribute is deprecated in HTML5, and styles should be used
via CSS for better practices.

31
Syntax:

<element_name align="left | right | center | justify">

Attribute Values:

Attribute Values Description


left It sets the text left-align.
right It sets the text right-align.
center It sets the text center-align.
justify It stretches the text of a paragraph to set the width of
all lines equal, aligning both edges.

Example 1: This example shows the use of the align attribute with an
example.

<!DOCTYPE html>

<html>

<head>

<title>

HTML p align Attribute

</title>

</head>

<body>

<h1>GFG</h1>

<h2>HTML p align Attribute</h2>

<p align="left">

Left align content

</p>

<p align="center">

32
center align content

</p>

<p align="right">

Right align content

</p>

</body>

</html>

Output:

Example 2: This example shows the use of the align attribute with another
example.

<!DOCTYPE html>

<html>

<head>

<title>align Attribute</title>

</head>

<body>

<h1>GFG</h1>

<h2>

33
div align Attribute

</h2>

<div align="center">

div align="center"

</div>

<div align="left">

div align="left"

</div>

<div align="right">

div align="right"

</div>

<div align="justify">

div align="justify"

</div>

</body>

</html>

Output:

34
ii.) Links:

HTML Links, also known as hyperlinks, are defined by the <a> tag in HTML,
which stands for “anchor.” These links are essential for navigating between
web pages and directing users to different sites, documents, or sections within
the same page.

The basic attributes of the <a> tag include href, title, and target, among
others.

Basic Syntax of an HTML Link:

<a href="[Link] Example</a>

NOTE: A hyperlink can be represented by an image or any other HTML


element, not just text.

A Simple HTML Link Example

In this example, we contains a paragraph instructing users to click on the


link labeled “Example,” which directs to the website
“[Link]

<!DOCTYPE html>

<html>

<head>

<title>HTML Links</title>

</head>

<body>

<p>Click on the following link</p>

<a href="[Link] Example </a>

</body>

</html>

35
Output:

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.

Target Attribute

The target attribute in the <a> tag specifies where to open the linked
document. It controls whether the link opens in the same window, a new
window, or a specific frame.

36
Attribute Description
_blank Opens the linked document in a new window or tab.
_self Opens the linked document in the same frame or window as
the link. (Default behavior)
_parent Opens the linked document in the parent frame.
_top Opens the linked document in the full body of the window.
framename Opens the linked document in a specified frame. The frame’s
name is specified in the attribute.

11. Tables

HTML Tables allow you to arrange data into rows and columns on a web page,
making it easy to display information like schedules, statistics, or other
structured data in a clear format.

HTML Table

An HTML table is created using the <table> tag. Inside this tag, you use

 <tr> to define table rows,


 <th> for table headers, and
 <td> for table data cells

Each <tr> represents a row, and within each row, <th> or <td> tags represent
the cells in that row, which can contain text, images, lists, or even another
table.

37
HTML Table Code Example

<!-- [Link] -->

<!DOCTYPE html>

<html>

<body>

<table>

<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>

38
<td>41</td>

</tr>

</table>

</body>

</html>

Output:

In this example:

 <table>: This tag starts the table. Everything between the opening
<table> and closing </table> tags makes up the table.
 <tr>: Stands for “table row”. Each <tr> tag defines a row in the table.
 <th>: Stands for “table header”. It’s used for the headers of the
columns. In this case, “Firstname“, “Lastname“, and “Age” are headers.
Text in <th> tags is usually bold and centered by default.
 <td>: Stands for “table data”. This tag is used for actual data cells under
each column. For instance, “Priya” is the data under the “Firstname”
header, “Sharma” under the “Lastname“, and “24” under the “Age“.
 The first <tr> has three <th> elements, setting up the column titles.
 The subsequent <tr> tags each contain three <td> elements,
representing the data for each person listed in the table.

When this HTML code is rendered in a web browser, it will display a table with
four rows (one header row plus three data rows) and three columns
(Firstname, Lastname, Age), showing the names and ages of Priya, Arun, and
Sam.

39
Tags used in HTML Tables

HTML Tag Description


<table> Defines the structure for organizing data in rows and
columns within a web page.
<tr> Represents a row within an HTML table, containing
individual cells.
<th> Shows a table header cell that typically holds titles or
headings.
<td> Represents a standard data cell, holding content or data.
<caption> Provides a title or description for the entire table.
<thead> Defines the header section of a table, often containing
column labels.
<tbody> Represents the main content area of a table, separating it
from the header or footer.
<tfoot> Specifies the footer section of a table, typically holding
summaries or totals.
<col> Defines attributes for table columns that can be applied to
multiple columns at once.
<colgroup> Groups together a set of columns in a table to which you
can apply formatting or properties collectively.

Another Example of HTML Table:

Creating a simple table in HTML using a table tag.

<!-- [Link] -->

<!DOCTYPE html>

<html>

<body>

<table>

40
<tr>

<th>Book Name</th>

<th>Author Name</th>

<th>Genre</th>

</tr>

<tr>

<td>The Book Thief</td>

<td>Markus Zusak</td>

<td>Historical Fiction</td>

</tr>

<tr>

<td>The Cruel Prince</td>

<td>Holly Black</td>

<td>Fantasy</td>

</tr>

<tr>

<td>The Silent Patient</td>

<td> Alex Michaelides</td>

<td>Psychological Fiction</td>

</tr>

</table>

</body>

</html>

41
Output:

12. Frames

HTML <frame> tag is used to divide web browser windows into multiple
sections, each capable of loading content independently. This is achieved
using a collection of frames within a frameset tag.

NOTE: The <frame> tag is deprecated in HTML 5.

<!DOCTYPE html>

<html>

<body>

<frameset rows="20%, 60%, 20%">

<frame name="top"

src="./[Link]" />

<frame name="main"

src="./[Link]" />

<frame name="bottom"

src="./[Link]" />

<noframes>

<p>The browser you are using does not support frames.</p>

</noframes>

</frameset>

42
</body>

</html>

The above example basically used to create three horizontal frames i.e. top,
middle and bottom using row attribute of frameset tag and the noframe tag is
used for those browser who doesn’t support noframe.

Syntax

<frameset cols="50%, 50%">

<frame src="[Link]">

<frame src="[Link]">

</frameset>

Difference Between Frames and Iframes

When you use frameset you split the visual real estate of a browser window
into multiple frames. Each frame has it’s own contents and the content in one
don’t spill into the next.

An iframe, on the other hand, embeds a frame directly inline with the other
elements of a webpage.

While both frames and iframes perform a similar function – embedding a


resource into a webpage – they are fundamentally different.

 Frames are layout-defining elements.


 Iframes are a content-adding elements.

Create Frames

While frames should not be used for new websites, learning how to use frames
can be beneficial for webmasters who are managing older websites.

43
The Basic Idea Behind Frames

The basic concept behind frames is pretty simple:

 Use the frameset element in place of the body element in an HTML


document.
 Use the frame element to create frames for the content of the web page.
 Use the src attribute to identify the resource that should be loaded
inside each frame.
 Create a different file with the contents for each frame.

Let’s look at a few examples of how this works. First we need a few HTML
documents to work with. Let’s create four different HTML documents. Here’s
what the first will contain:

<!DOCTYPE html>

<html>

<body>

<h1>Frame 1</h1>

<p>Contents of Frame 1</p>

</body>

</html>

Creating Vertical Columns

To create a set of four vertical columns, we need to use the frameset element
with the cols attribute.

The cols attribute is used to define the number and size of columns the
frameset will contain. In our case, we have four files to display, so we need
four frames. To create four frames we need to assign four comma-separated
values to the cols attribute.

To make things simple we’re going to assign the value * to each of the frames,
this will cause them to be automatically sized to fill the available space.

44
Here’s what our HTML markup looks like.

<!DOCTYPE html>

<html>

<frameset cols="*,*,*,*">

<frame src="../file_path/frame_1.html">

<frame src="frame_2.html">

<frame src="frame_3.html">

<frame src="frame_4.html">

</frameset>

</html>

Output:

Creating Horizontal Rows

Rows of frames can be created by using the rows attribute rather than the
cols attribute as shown in the HTML below.

45
<!DOCTYPE html>

<html>

<frameset rows="*,*,*,*">

<frame src="frame_1.html">

<frame src="frame_2.html">

<frame src="frame_3.html">

<frame src="frame_4.html">

</frameset>

</html>

Output:

46
Mixing Columns and Rows

Columns and rows of frames can both appear on the same webpage by nesting
one frameset inside of another. To do this, we first create a frameset and then
nest a child frameset within the parent element. Here’s an example of how we
could nest two rows within a set of three columns.

<frameset cols="*,*,*">

<frameset rows="*,*">

<frame src="frame_1.html">

<frame src="frame_2.html">

</frameset>

<frame src="frame_3.html">

<frame src="frame_4.html">

</frameset>

Output:

47
One more way to create a combination of rows and columns is to define a grid
of columns and rows in a single frameset. For example, if you wanted a grid
of four equally sized frames, you could use the following code.

<frameset rows="*,*" cols="*,*">

<frame src="frame_1.html">

<frame src="frame_2.html">

<frame src="frame_3.html">

<frame src="frame_4.html">

</frameset>

Output:

--- UNIT – 1 COMPLETED ---

48
UNIT – 2

FORMS & IMAGES USING HTML

1. Graphics in Web Design

Introduction to Graphics in Web Design

Graphic means any visual element represented by the computer. Web


Graphics are those graphics that are used in a website. These graphics can
be photos, videos, logos, banners, etc. Humans are more attracted to visual
elements rather than textual elements. So, to make a website more appealing
and user-friendly addition of web graphics is a necessity.

Web Design is a field related to designing websites on the Internet. Without a


good design, a website fails to perform well and cannot produce a good impact
on the user. Design is a creative process that affects the ranking of the brand.
A good website design helps to create an engaging online presence that
captivates the audience.

Before beginning to design a website a user has to be clear about what web
designing is. It is the art of making websites look and feel good to the user
and providing easy access to the website features to the client. It focuses on
improving the user experience rather than development.

Types of Web design

The following are the types in which you can do Web Design:

 Static Website: This type of design is used when little or no interaction


is required from the user.
 Dynamic Website: When user interaction is required and information
is to be displayed according to the request then a dynamic design
pattern is followed.
 E-commerce Website: This type of website design is required when a
business wants to sell their products to the consumer.

49
 Flat Design: Minimalist approach characterized by clean, simple
elements, vibrant colors, and absence of textures or gradients.
 Neuromorphic Design: Mimics physical interactions and textures,
creating interfaces that blend realism with digital functionality.
 Minimalism Design: Focuses on stripping away unnecessary elements,
favoring simplicity, clean lines, and ample white space for an
uncluttered user experience.

Elements of Web Graphics

There are many types of Web Graphics but let us understand only the most
used Web Graphics.

 Pictures: Pictures can convey information much faster and effectively


than text as the average person responds far better to visual
information compared to just plain text. Pictures are not only more

50
effortless to recognize and process than words but also easier to recall.
There are many image formats such as jpg/jpeg, png, etc.
 Videos: Video can be part of the website UI or be used to convey
additional information that can’t be conveyed using text or images. But
videos can slow down the site and take much more time to load than
any other graphic so it’s better to embed video from other platforms.
Some video formats are mkv, mp4, etc.
 Animations: We can use animations such as GIF in the website or code
directly in the site using CSS, JSS or any other technology. Animation
can be very helpful to boost the UI look and feel. Clever use of animation
make the user experience must better and worth remembering. Micro
interactions are commonly used animation in the websites.
 SVG (Scalable Vector Graphics): One of the most popular format used
in the website to display icon or any scalable graphics. It is because the
width and height of the graphic can be change to any size which is good
for a responsive design. If we want to make our page responsive then
raster images should be changes to SVG if possible.
 Logo: A SVG or image used in the sites to represent brand identity. A
logo if very important for the site because the user can forget the site
name or URL but most of the time user will remember the logo. It better
to create a logo that matches the site name or brand name.

51
Benefits of Using Web Graphics

Web Graphics use in not only limited to websites visual appeal but it is used
for many other reasons:

 Brand Image: We can use logo, banner, videos to increase the brand
identify and its goals. Graphics can be used to sell the brands products.
We always want user to revisit our website so incepting the brand logo
helps a lot. Wherever it is appropriate we must use brand logo and
imagery.
 User Interactions: A button designed to look different is a guaranteed
method to attract attention. User can also get the idea which button is
what based on the looks thus increasing instant response from the
user. A good-looking button or micro interactions always provide a good
user experience but overwhelming amount of it can cause
repercussions.
 SEO (Search Engine Optimization): A site with moderate use of
graphics can result in high page rank and can bring more traffic to the
page. Nowadays crawlers are design to parse the pages as closely as a
normal users would so, adding graphics increases the chance to show
up in the search results.
 Promotion: We can use graphics to promote products or put
advertisement in the site. Most websites are filled with adds and these
add maximum of the time used pictures to advertise. This pictorial adds
are easy to load and very easily catch the attention of the users.
 Scalable: Some graphics are device independent and can be use in site
used in different devices with different width and height. For a
responsive design its better to use SVG as it is scalable and take up
very less size when compare to a raster image of same width and height.

52
Comparison Between Graphic Design and Web Design

Category Graphic Design Web Design


Description Focuses on visuals and Focused on user experience.
appearance.
Objective Sets the foundation of Supports the foundation of that
any project. project.
Purpose Visually communicates Aims to create functional and
messages or ideas user-friendly websites for an
through typography, optimal user experience.
images, colors, and
illustrations.
Function Focuses on how things Considers search engine
look. optimization (SEO) when
constructing websites.
Material Media The output can be in The output can only be seen on
different materials like screens.
cloth, paper, etc.
Interaction Involves static Includes designing interactive
compositions. elements within websites or web
applications.
Layout May use grids or Considers screen resolutions,
Considerations templates but typically responsiveness across devices,
do not design for and user flow when designing
dynamic layouts. layouts.
Technical Does not necessarily Requires knowledge of HTML,
Skills require coding CSS, and other web development
knowledge. languages to create functional
and responsive designs.

53
2. Work Efficiently with Images in Web Pages

Use Images in Web Design

First, we will understand why images are being used in web design, The
following are reasons we use images for

 Benefits in SEO: If you use well-optimized images they are good points
for website SEO and also users will spend more time on the website if
you use engaging images.
 Visual Communication: Images explain very complex things in a
simple way. Instead of using lengthy descriptions, you can use images
or drawings. for example, e-commerce websites have different angle
images of their products so that users can choose.
 Brand Identity: You can create your brand identity using eye-catching
icons and logos for your websites. Images are shared very often on social
media and google instead of texts.
 Easy Navigation: Images can be used to guide users through a
website's content. They can serve as navigation elements, such as icons
or buttons, helping users find what they're looking for or prompting
specific actions.

54
 Sense of Trust: High-quality front and background images help build
a sense of trust while if you do not images or use bad-quality images
people will start thinking your site is fake or boring to look at.

Use Images Efficiently in Web Design

Step 1. Choosing right Images

First step of creating an efficient design is choosing right images, if images


are bad then it does'nt matter where they are placed. So how will you choose
right images just keep three things in mind

 Relevance: Images should be relevant to the content of your site. You


should choose images which portray the your message and brand
identity, not distract or confuse the users For example if you have site
related to health and foods, you can show images of different foods or
nutrients but not random images of landscapes.
 Quality: Images should be clear, high quality and not blurry. Images
should not be like cut from between or half. They should also have good
contrast, lighting and colors.
 Size: Image should be of size which would fit properly in web design
and does not look too small big or strange. If the size of image is larger
you can change its dimensions with help of online image resizing tools
in few clicks.
 Format: Images can be in many formats like Webp, JPG, SVG, GIF Png
etc you should use appropriate format images with proper research
because each format have there own advantages and disadvantages.

Step 2. Optimising Image Placement

Now after choosing the right image, its time to optimise the image placement
in your web design. Following aspects should be considered for optimising
image placement.

55
 Alignment: Images should be aligned properly with other elements of
webpage. There should not be gaps between that would disrupt the
readibitlity of page You can use CSS properties like float, display,
position, margin, padding, and flexbox to control the alignment of your
images.
 Balance: There should be a proper balance between images and text of
webpage. There should not be like lot of images and less text or lot of
text but no images. You should aim for a harmonious and proportional
distribution of visual weight and white space on your web page.
 Hierarchy: The images should be arranged accordingly on page, for ex.
you should place the images which are very important content above in
page while use less important images below. Because showing less
important images which distract users. You can use various techniques
such as proper scaling, colors, shapes and use of animation to create
visual hierarchy of images

Step 3. Enhance the accessibility of Image

If we found right image and right place for it. Then the third step is to make
is easily accessible to users. For you consider following things

 Alt Text: It means alternative text, it is shown in the case the image
does not open or fails to open. It should represent he content of image
in form of text. Its also very good for seo, because it helps understanding
the search engine what the image is about?
 Captions: The images should have captions that provide additional
information or context about the image content to users who can see
them. Captions are also useful for SEO, as they can include keywords
and phrases that relate to your content.
 Fixing problems: You should prevent and fix the errors which are
causing your images fail to open, like sometimes images does not open
because the size of image is too big, sometimes its on server which have
problem.

56
Benefits of Efficient Placement of Images

 Use of high quality, relevant images at good place on page will grab
users attention in first look and will be memorable for them.
 Clear relevant images clarify concepts when combined with images.
 Good image placement ensures a balanced layout.
 Images enhance storytelling by illustrating concepts or narratives.
Sequential images can guide users through a story or process.
 High-resolution images in the wrong places can slow down your
website's loading time, resulting in a poor user experience and potential
loss of visitors But the good placement do exactly opposite

Things to Avoid

 Avoid using poor quality or blurry images on your webpage or design


 Don’t overcrowd slides with too many images. Choose one high-quality
image that best represents the main theme of the slide.
 Ensure that characters in an image look within the slide content.
Human behavior naturally follows where others are looking, so align
characters’ gaze with your message
 Avoid using images which are too flashing, animated or visually
distracting they may distract users from the content.
 Using the images which have bigger size, will make your website slow.
You can use images of webp extension which is good for web images.

Example of Image Tag:

<img src="[Link]" alt="A descriptive text for the image" width="300"


height="200">

57
3. Image Maps

An HTML Image Map is a type of image that contains one or more clickable
areas. These clickable areas, known as “hotspots,” are defined using
coordinates on the image. Each hotspot can link to different URLs or trigger
different actions when clicked. Image maps are often used in web applications
where images represent navigational elements, such as maps, diagrams, or
complex graphics.

Basic Syntax of an Image Map

<img src="[Link]" usemap="#imagemap" alt="Demo Image" />

<map name="imagemap">

<area shape="rect" coords="x1,y1,x2,y2"

href="[Link]" alt="Description 1" />

<area shape="circle" coords="x,y,radius"

href="[Link]" alt="Description 2" />

<area shape="poly" coords="x1,y1,x2,y2,x3,y3,..."

href="[Link]" alt="Description 3" />

58
</map>

Where:

 src Attribute: Specifies the image source.


 usemap Attribute: Links the image to a map element by its name.
 name Attribute: Identifies the map element, referenced by the image.
 shape Attribute: Defines the shape of the clickable area (rect, circle,
poly).
 coords Attribute: Specifies the coordinates of the clickable area.
 href Attribute: Defines the link or action for the clickable area.
 alt Attribute: Provides alternative text for accessibility.

Image Map Work

An image map works on an image using <map> and <area> elements. Each
<area> element defines a clickable region on the image using shape attributes
(like rect, circle, poly) and coordinates.

The basic components of an image map include:

 <img> Tag: Displays the image on the page.


 <map> Tag: Defines the map of clickable areas.
 <area> Tag: Specifies the clickable regions within the image.

Defining Areas within an Image Map

The <area> tag within a <map> tag defines the clickable regions of the image
map. You can create different shapes, including rectangles, circles, and
polygons.

Rectangular Area

To define a rectangular clickable area, use the rect shape with four
coordinates: top-left corner (x1, y1) and bottom-right corner (x2, y2).

59
<area shape="rect" coords="34,44,270,350" href="[Link]" alt="Rectangle
Link">

Circular Area

To create a circular clickable area, use the circle shape with three values:
center point (x, y) and radius.

<area shape="circle" coords="140,75,50" href="[Link]" alt="Circle Link">

Polygonal Area

For more complex shapes, use the poly shape with multiple coordinates
defining each point of the polygon.

<area shape="poly" coords="130,80,180,60,230,80,220,120,170,140"


href="[Link]" alt="Polygon Link">

Example: Basic Image Map with Rectangular Image Links

Let’s create a simple image map where we use rectangular areas to create
clickable sections.

<html>

<head>

<title>HTML Image Maps</title>

</head>

<body>

<img src="[Link]
content/uploads/20190227165729/[Link]"alt="" width="300"
height="119" class="aligncenter size-medium wp-image-910965"

usemap="#shapemap" />

<map name="shapemap">

<!-- area tag contained image. -->

<area shape="poly" coords="59,31,28,83,91,83"

60
href="[Link]
content/uploads/20190227165802/[Link]" alt="Triangle">

<area shape="circle" coords="155,56,26"

href="[Link]
content/uploads/20190227165934/[Link]" alt="Circle">

<area shape="rect" coords="224,30,276,82"

href="[Link]
content/uploads/20190227170021/[Link]" alt="Square">

</map>

</body>

</html>

Output:

4. GIF Animation

GIFs (Graphics Interchange Format) are widely used on the web for creating
simple animations. They are advantageous for adding visual interest to a
webpage without the complexity or bandwidth requirements of video files.

61
Advantages of GIFs:

 Lightweight and Fast-loading: GIFs are typically smaller in size


compared to video files, making them faster to load and less demanding
on bandwidth. This is especially useful for webpages where quick load
times are critical.

 Supports Transparency: GIFs can include transparent areas, allowing


them to blend seamlessly with various backgrounds. This makes them
versatile for design purposes.

 Animation: GIFs can display short, looped animations. This capability


is useful for adding subtle motion to a webpage, making it more
engaging.

Example of GIF Integration:

To integrate a GIF into your HTML document, use the <img> tag. Here is a
simple example:

<!DOCTYPE html>

<html>

<head>

<title>GIF Animation Example</title>

</head>

<body>

<h1>GIF Animation in HTML</h1>

<p>Here is an example of embedding a GIF:</p>

<img src="[Link]
alt="Animated Example">

62
</body>

</html>

Explanation:

 <img> Tag: The HTML tag used to embed images in a webpage.


 src Attribute: Specifies the path to the image file. This can be a relative
path to a file on the same server or an absolute URL to a file hosted
elsewhere.
 alt Attribute: Provides alternative text for the image, which is displayed
if the image fails to load. It is also used by screen readers to describe
the image to visually impaired users.

5. Adding Multimedia

A variety of tags such as the <img> tag, <video> tag, and <audio> tag are
available in HTML to include media on your web page. Multimedia combines
different media, such as images, audio, and videos. Users will have a better
experience when multimedia is embedded into HTML. Early web browsers
only supported text and were limited to a single font in a single color. However,
later browsers introduced support for various fonts, images, and multimedia
elements.

NOTE: Provide multiple video formats such as .wav, .mp3, .mp4, .mpg, .wmv,
etc.

Syntax:

// Embedding image

<img src="[Link]" alt="Example Image">

// Embedding video

<video width="500px" height="300px" controls>

63
<source src="Small_movie.mp4" type="video/mp4">

</video>

// Embedding audio

<audio controls>

<source src="Small_audio.mp3" type="audio/mp3">

</audio>

Embedding Image

The <img> tag is self-closing because they don't have a closing tag. The src
attribute is the required attributes in the <img> tag, it helps to specify the
source URL. The alt attribute provides the alternative text to an image. If the
image does not load up then this message will be displayed.

Example: Illustration of embedding image in HTML.

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Embedding Image in HTML Document</title>

</head>

<body>

<img src="[Link]
[Link]" alt="web-design stock image">

</body>

</html>

64
Output:

Embedding Video

The <video> tag helps us to embed the required video into the webpage. The
width and height properties determine the size of the video. The control
property adds playback control like play, pause, volume. etc. The <source>
tag specifies the specific video file and the type attribute is used to specify the
MIME (Multipurpose Internet Mail Extensions) type. If the browser does not
support a video tag then the content present inside will be displayed. Provide
multiple video formats such as MP4, MOV, AVI, WEBM.. etc.

Example: Illustration of embedding video in an HTML Document.

<!DOCTYPE html>

<html>

<style>

h1:first-letter{

color:skyblue ;

65
</style>

<body>

<center>

<h1 style="color:red;">DM</h1>

<h3>HTML video tag</h3>

<p>Adding video on the webpage</p>

<video width="450" height="250"

controls preload="auto">

<source src=

"[Link]
content/uploads/20190616234019/Canvas.move_.mp4" type="video/mp4">

</video>

</center>

</body>

</html>

Output:

66
Embedding Audio

The <audio> tag, helps us to embed the required audio into the webpage. The
control property adds playback control like play, pause, volume. etc. The
<source> tag specifies the specific audio file and the type attribute is used to
specify the MIME (Multipurpose Internet Mail Extensions) type. If the browser
does not support video a tag then the content present inside will be displayed.

Example: Illustration of embedding audio in an HTML document.

<!DOCTYPE html>

<html>

<body>

<p>Audio Sample</p>

<!-- Audio tag starts here -->

<audio controls>

<source src="test.mp3" type="audio/mp3">

</audio>

<!-- Audio tag ends here -->

</body>

</html>

Output:

67
6. Data Collection with HTML Forms

The HTML <form> Tag are essential for collecting user input on web pages.
They provide a structured way for users to submit data, which can then be
processed and used for various purposes, such as user registration, feedback,
surveys, and more. HTML forms consist of multiple input elements, allowing
for diverse types of data collection.

The <form> Tag serves the following purposes:

 Input Collection: It provides a container to collect user input, such as


text, checkboxes, radio buttons, and more.
 User Interaction: Forms facilitate interactive elements like buttons and
drop-down menus, enhancing user engagement.
 Data Submission: When a user submits a form, the data entered into
the form fields is sent to the server for further processing.
 Action and Method Attributes: The 'action' attribute specifies the URL
where the form data should be submitted, and the 'method' attribute
defines the HTTP method (e.g., GET or POST) used for the submission.

Form Elements:

 <form>: The main container for form elements. Defines how and where
to send the form data.
 Text Input (<input type="text">): Single-line text entry.
 Password Input (<input type="password">): Secure text entry with
masked characters.
 Email Input (<input type="email">): For collecting email addresses.
 Number Input (<input type="number">): Numeric input with optional
range limits.
 Textarea (<textarea>): Multi-line text entry.
 Checkbox (<input type="checkbox">): Selection of multiple options.
 Radio Button (<input type="radio">): Selection of one option from a
set.
 Drop-down List (<select>): Dropdown selection.

68
 File Input (<input type="file">): File uploads.
 Hidden Input (<input type="hidden">): Stores data not visible to the
user.
 Submit Button (<input type="submit">): Submits form data.
 Reset Button (<input type="reset">): Resets form fields.
 Button (<button>): Custom actions with buttons.

Syntax:

<form action="/submit" method="POST">

<!-- Form fields go here -->

<label for="username">Username:</label>

<input type="text" id="username" name="username">

<label for="password">Password:</label>

<input type="password" id="password" name="password">

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

</form>

NOTE: In this example, the form is set to submit data to "/submit" using the
POST method when the user clicks the "Submit" button. The actual form fields
can vary depending on the information you want to collect.

Example:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content=

"width=device-width, initial-scale=1.0">

<title>HTML form tag</title>

69
</head>

<body>

<h2>HTML &lt;form&gt; tag</h2>

<form action="/submit" method="post">

<label for="username">Username:</label>

<input type="text"

id="username"

name="username" required>

<br><br>

<label for="password">Password:</label>

<input type="password"

id="password"

name="password" required>

<br><br>

<input type="submit"

value="Submit">

</form>

</body>

</html>

Output:

70
7. Tools for Building Web Pages

Building web pages involves a combination of different tools and technologies


that make the process efficient, effective, and versatile. Here’s an overview of
some essential tools used for creating web pages:

i.) Text Editors and Integrated Development Environments (IDEs)

 VS Code: A popular code editor by Microsoft, known for its flexibility,


extensions, and robust debugging capabilities.
 Sublime Text: A sophisticated text editor for code, markup, and prose,
with a powerful, customizable interface.
 Atom: An open-source text editor built by GitHub, known for its
hackability and wide range of plugins.
 Brackets: An open-source editor focused on web development, created
by Adobe.

ii.) Web Browsers

 Google Chrome: Widely used for its extensive developer tools, including
the ability to inspect elements, debug JavaScript, and emulate mobile
devices.
 Mozilla Firefox: Known for its strong adherence to web standards and
powerful development tools.
 Microsoft Edge: Modern browser with built-in tools for web
development and testing.
 Safari: The default browser for macOS, with tools to inspect and debug
web pages on Apple devices.

iii.) Frameworks and Libraries

 React: A JavaScript library for building user interfaces, particularly


known for its component-based architecture.
 Angular: A platform and framework for building single-page client
applications using HTML and TypeScript.
 [Link]: A progressive framework for building user interfaces, easy to
integrate with other projects and libraries.

71
 Bootstrap: A popular framework for building responsive, mobile-first
websites using CSS, JavaScript, and HTML.

iv.) CSS Preprocessors

 Sass: A preprocessor scripting language that is interpreted or compiled


into CSS, adding features such as variables, nested rules, and mixins.
 LESS: A backwards-compatible language extension for CSS that is the
same language, but with additional features.

v.) Version Control

 Git: A distributed version control system to track changes in source


code during software development.
 GitHub: A web-based platform that uses Git for version control and also
provides a collaborative environment for developers.

vi.) Online Code Playgrounds

 CodePen: An online community for testing and showcasing HTML,


CSS, and JavaScript code snippets.
 JSFiddle: An online IDE for JavaScript that lets you write, share, and
test your code snippets in a collaborative environment.
 CodeSandbox: An online editor tailored for web application
development, supporting a wide array of front-end and back-end
frameworks.

vii.) Design Tools

 Adobe XD: A vector-based tool for designing and prototyping user


experiences for web and mobile apps.
 Sketch: A design toolkit built to help you create your best work—from
your earliest ideas, through to final art.
 Figma: A cloud-based design tool that lets teams collaborate in real-
time.

72
viii.) Content Management Systems (CMS)

 WordPress: A widely-used CMS for creating websites and blogs with a


vast ecosystem of plugins and themes.
 Joomla: A flexible CMS with extensive options for extensions and
templates, suitable for a wide range of websites.
 Drupal: A powerful CMS for building complex, content-heavy websites
with robust user management and flexibility.

ix.) Deployment Platforms

 Netlify: A web developer platform that multiplies productivity by


simplifying the development, deployment, and management of modern
web projects.
 Vercel: A cloud platform for static sites and frontend frameworks, built
to integrate with your headless CMS of choice.
 GitHub Pages: Host your personal, organization, or project pages
directly from a GitHub repository.

Conclusion

These tools, when used effectively, can greatly enhance the web development
process, making it easier to build, test, and deploy web pages. By leveraging
the right combination of text editors, frameworks, version control systems,
design tools, and deployment platforms, developers can create robust, user-
friendly, and visually appealing websites.

--- UNIT – 2 COMPLETED ---

73
UNIT – 3

XML & DHTML

1. Cascading Style Sheets (CSS)

What is CSS?

CSS, which stands for Cascading Style Sheets is a language in web


development that enhances the presentation of HTML elements. By applying
styles like color, layout, and spacing, CSS makes web pages visually appealing
and responsive to various screen sizes.

CSS allows you to control the look and feel of websites, enabling design
consistency across different devices. It also helps optimize performance
through reusable stylesheets and allows customization of default browser
styles.

Why Cascade Matters

When you declare multiple styles for the same element (e.g., from an external
stylesheet, inline styling, or browser defaults), the cascade helps ensure the
correct styles are applied based on the following order of precedence:

 Inline Styles (Highest Priority)


 Internal and External Styles (Next Priority)
 Browser Defaults (Lowest Priority)

The cascade simplifies the process of managing complex stylesheets,


especially in large-scale web projects where different teams may contribute
styles.

CSS Integration Techniques

There are several ways to include CSS in an HTML file. Each technique has
its own use case, and choosing the right one depends on the project
requirements.

74
Technique Description Syntax
Internal CSS Internal CSS is written directly <style>
within the <style> element inside h1 { color: crimson; }
the <head> section of an HTML </style>
document.
External CSS External CSS uses a separate .css <link rel="stylesheet"
file, linked to the HTML document. href="[Link]">
This is ideal for maintaining large
projects with multiple pages.
Inline CSS Inline CSS applies styles directly to <p
specific HTML elements using the style="color:green;">
style attribute. It is not GeeksforGeeks
recommended for large-scale </p>
projects due to maintainability
concerns.

CSS Selectors

A CSS selector selects the HTML element(s) for styling purposes. CSS selectors
select HTML elements according to their id, class, type, attribute, etc. The
HTML Elements can be styled either as a single or grouped with the help of
the following CSS Selectors, depending on the styled-type used:

Selector Description Syntax


Element Selector Targets all elements of a specific p { color: blue; }
type.
CSS id Selector Applies styles to elements with a #header {
specific id attribute. IDs must be background-color:
unique within a page. lightgray; }
Class Selector Targets all elements that belong .box { border: 1px
to a particular class. solid black; }
Universal (*) Applies styles to all elements in * { margin: 0;
Selector an HTML document. padding: 0; }

75
Attribute Selector Targets elements based on input[type="text"] {
attribute values. border: 1px solid
gray; }
Pseudo-classes Defines a special state of an a:hover { color: red; }
Selector element, such as when it is
hovered or focused.
Pseudo-elements Styles specific parts of an p::first-letter { font-
Selector element, such as the first letter or size: 2em; }
first line.

CSS Properties

CSS Property are used to style HTML elements. Each property consists of two
parts:

 Property name: The CSS feature being styled.


 Property value: The settings applied to that feature.

Syntax:

property: "value";

Advantages of CSS

 Responsive Design: CSS makes websites responsive with the help of


media queries, enabling them to adapt to different screen sizes.
 Animations and Transitions: CSS allows developers to create engaging
animations that make websites visually dynamic.
 Reusability: Stylesheets can be reused across multiple pages or
projects, improving efficiency and maintainability.

Uses of CSS

Helps in Styling

 Because of CSS, It is easier to add font style, background color,


alignment, and many other properties to web pages.

76
 We can target the tags of HTML for decorating the web pages by using
these features or attributes provided by CSS.
 It mainly helps in the responsiveness of a web page so that we can
access the web page on any existing device with proper height, width,
and other required specifications.

Time efficient

There are three ways by which we can implement or apply CSS on web pages.

 Internal CSS: Used in the head tag of HTML within the style tag.
 External CSS: This external CSS file is linked to the HTML using a link
tag in the head section of the HTML file.
 Inline CSS: It is used in HTML files directly. CSS styling is used in
elements of HTML.
External CSS mainly helps save a lot of time while loading web pages on
Bowser. As external CSS changes will not break the code of HTML and for
change in any kind of design only CSS files need to be changed.

Many more attributes

CSS has lots of styling that helps in adding more and more features to web
pages.

Some of the important attributes are:

 Grid
 Flexbox
 Position
 Background properties

Helps in the maintenance of web pages

 CSS has many properties that help to change and provide many extra
features to the web page.
 We only need to change the CSS file for any change in web page design.
 CSS is convenient for any change in web pages.

77
Applications of CSS

 Used in animation, As many web pages use animation for more user
interactivity so it helps in implementing that features on web browsers.
 Used in creating social media. It is highly used in styling the UI of social
media.
 Used in dynamic templates. Many CSS frameworks help to create the
dynamic element of the web page.

Adding CSS to Web Pages

CSS (Cascading Style Sheets) is used to style and layout of web pages, and
controlling the appearance of HTML elements. CSS targets HTML elements
and applies style rules to dictate their appearance.

Below are the types of CSS:

 Inline CSS
 Internal or Embedded CSS
 External CSS

1. Inline CSS

Inline CSS involves applying styles directly to individual HTML elements using
the style attribute. This method allows for specific styling of elements within
the HTML document, overriding any external or internal styles.

<p style="color:#009900;

font-size:50px;

font-style:italic;

text-align:center;">

Inline CSS

</p>

78
Output:

2. Internal or Embedded CSS

Internal or Embedded CSS is defined within the HTML document’s <style>


element. It applies styles to specified HTML elements. The CSS rule set should
be within the HTML file in the head section i.e. the CSS is embedded within
the <style> tag inside the head section of the HTML file.

<!DOCTYPE html>

<html>

<head>

<style>

.main {

text-align: center;

.GFG {

color: #009900;

font-size: 50px;

font-weight: bold;

79
.geeks {

font-style: bold;

font-size: 20px;

</style>

</head>

<body>

<div class="main">

<div class="GFG">Internal CSS</div>

<div class="geeks">

Implementation of Internal CSS

</div>

</div>

</body>

</html>

Output:

80
3. External CSS

External CSS contains separate CSS files that contain only style properties
with the help of tag attributes (For example class, id, heading, … etc). CSS
property is written in a separate file with a .css extension and should be linked
to the HTML document using a link tag. It means that, for each element, style
can be set only once and will be applied across web pages.

HTML:

<!DOCTYPE html>

<html>

<head>

<link rel="stylesheet" href="[Link]">

</head>

<body>

<div class="main">

<div class="GFG">External CSS </div>

<div id="geeks">

This shows implementation of External CSS

</div>

</div>

</body>

</html>

CSS:

body {

background-color: powderblue;

81
.main {

text-align: center;

.GFG {

color: #009900;

font-size: 50px;

font-weight: bold;

#geeks {

font-style: bold;

font-size: 20px;

Output:

NOTE: Inline CSS has the highest priority, so it overrides internal and
external styles. Internal CSS comes next, overriding external styles, while
external CSS is applied only if no inline or internal styles are set.

82
Grouping in CSS

Grouping allows you to apply common styling properties to multiple elements


at once. This reduces the length of your code, makes it easier to read, and
speeds up page load times.

Syntax:

selector1, selector2 {

property: value;

Instead of writing this long code, specifying the same properties to different
selectors:

h1 {

padding: 5px;

color: grey;

p{

padding: 5px;

color: grey;

We can group them and write like this & we need the comma(,) to group the
various selectors.

h1, p {

padding: 5px;

color: grey;

83
Approach:

 Add <style>tag inside <head> tag.


 Add various tags inside <body> tag with content.
 Inside <style> tag, we can group our selectors containing the same
properties.

Example: In this example, we will group various selectors together.

<!DOCTYPE html>

<html>

<head>

<style>

h1, h2, p, a {

text-align: center;

color: green;

</style>

</head>

<body>

<h1>GFG</h1>

<h2>Smaller heading!</h2>

<p>This is

<a href="[Link]

anchor tag

</a>

</p>

<p>This is a paragraph.</p>

84
</body>

</html>

Output:

2. Extensible Markup Language (XML)

Extensible Markup Language (XML) is a type of markup language that


establishes a set of guidelines for encoding texts in a way that is both
machine- and human-readable. For storing and transferring data on the web
and in many other applications, XML is widely used. XML steps in as a
versatile tool for encoding and organizing data in a way that both humans
and machines can comprehend.

History of XML

XML emerged in the late 1990s as a revolutionary concept in the evolving


landscape of the internet. Before XML, HTML served as the predominant
language for web content, but it lacked the flexibility needed for complex data
representation. XML arrived as a solution, offering a standardized format for
expressing diverse types of data in a hierarchical structure.

Different ways of using XML

In the realm of XML, everything revolves around tags. Think of tags as


containers that hold different pieces of information. Each tag has a name and
can optionally carry attributes, providing additional details about the
enclosed data. Here's a simple breakdown:

85
<element attribute="value">Text content</element>

Let's unpack this: <element> represents the name of the container, attribute
is like a label describing the container's contents, and Text content is the
actual information stored within the container.

Simple XML Document

<book> acts as the main container, housing details about a book such as its
title, author, and publication year.

Example:

<book>

<title>Harry Potter and the Sorcerer's Stone</title>

<author>J.K. Rowling</author>

<year>1997</year>

</book>

XML with Attributes

Here, <student> serves as the container for student information, with


attributes like id providing additional identifiers.

Example:

<student id="001">

<name>John Doe</name>

<age>25</age>

<grade>A</grade>

</student>

Example: the <book> element serves as the primary container, encompassing


information pertaining to a book such as its title, author, and year of
publication.

86
<book>

<title>Harry Potter and the Sorcerer's Stone</title>

<author>J.K. Rowling</author>

<year>1997</year>

</book>

Applications of XML

 In the world of web development, XML serves as a handy tool for sorting
and moving data around. It's like the organizer of the digital world,
helping to structure everything from news feeds to website maps and
setup files. And when it comes to web services like SOAP, XML plays a
crucial role in enabling different systems to share information
seamlessly over the internet.
 When it comes to exchanging data between different computer systems,
XML acts as a kind of universal translator. It bridges the gap between
systems that speak different languages, making it possible for
businesses and organizations to communicate effectively, even if their
software systems don't normally understand each other.
 Think of XML as a digital filing cabinet for managing documents. It's
used across industries like publishing, healthcare, and law to store and
organize documents in a way that's easy to find and manage. Whether
it's technical manuals or legal documents, XML-based standards like
DocBook and DITA provide a structured framework for storing
important information.
 Imagine XML as the settings menu of your favorite app. It's the behind-
the-scenes tool that developers use to create organized lists of options
and preferences for users to customize their experience. With XML, you
can tweak your app settings without needing to know the ins and outs
of coding.

87
 XML is like a shared language between computers and humans. It's
perfect for storing data in databases because it provides a clear and
structured way to organize information. And with tools like XML
Schema Definition (XSD), you can ensure that your data follows specific
rules and formats, making it easier to work with.
 In the world of software integration, XML plays the role of a mediator
between different systems. It helps bridge the gap between apps that
speak different "languages," allowing them to communicate and share
information seamlessly. This makes it easier for businesses to
streamline their operations by connecting all their software systems
together.
 And finally, XML has inspired popular data formats like JSON and
YAML. These simplified versions of XML are easier for computers to read
and write, making them perfect for exchanging data between
applications and services. They're the modern-day equivalents of XML,
designed to make data interchange faster and more efficient.

Advantages of XML

 Human-readable: XML's straightforward tag-based syntax makes it


easy for humans to read and understand. This readability promotes
collaboration and understanding among developers and other
stakeholders.
 Interoperability: Like a skilled interpreter, XML bridges the
communication gap between disparate systems, enabling seamless data
exchange. Whether it's sharing data between different applications or
integrating systems from different vendors, XML ensures
interoperability and compatibility.
 Flexibility: XML's adaptability allows it to handle a wide range of data
types and structures, offering a canvas for expressing diverse
information. Whether it's simple text data, complex hierarchical data,
or metadata describing data relationships, XML can accommodate it all.

88
3. Introduction to DHTML

DHTML, or Dynamic HTML, is a technology that differs from traditional HTML.


DHTML combines HTML, CSS, JavaScript, and the Document Object Model
(DOM) to create dynamic content. It uses the Dynamic Object Model to modify
settings, properties, and methods. Scripting is also an essential component of
DHTML, which was part of earlier computing trends. It is supported by some
versions of Netscape Navigator and Internet Explorer 4.0 and higher.

 HTML: HTML stands for Hypertext Markup Language and it is a client-


side markup language. It is used to build the block of web pages.
 JavaScript: It is a Client-side Scripting language. JavaScript is
supported by most of browsers, and also has cookie collection to
determine the user’s needs.
 CSS: The abbreviation of CSS is Cascading Style Sheet. It helps in the
styling of the web pages and helps in designing of the pages. The CSS
rules for DHTML will be modified at different levels using JS with event
handlers which adds a significant amount of dynamism with very little
code.
 DOM: It is known as a Document Object Model which acts as the
weakest link in it. The only defect in it is that most of the browsers does
not support DOM. It is a way to manipulate the static content.

DHTML is not a technology; rather, it is the combination of three different


technologies, client-side scripting (JavaScript or VBScript), cascading style
sheets and document object model.

89
NOTE: Many times DHTML is confused with being a language like HTML but
it is not. It must be kept in mind that it is an interface or browsers
enhancement feature which makes it possible to access the object model
through Javascript language and hence make the webpage more interactive.

Key Features:

 Tags and their properties can be changed using DHTML.


 It is used for real-time positioning.
 Dynamic fonts can be generated using DHTML.
 It is also used for data binding.
 It makes a webpage dynamic and be used to create animations, games,
applications along with providing new ways of navigating through
websites.
 The functionality of a webpage is enhanced due to the usage of low-
bandwidth effect by DHTML.
 DHTML also facilitates the use of methods, events, properties, and
codes.

Use of DHTML

DHTML makes a webpage dynamic but Javascript also does, the question
arises that what different does DHTML do? So the answer is that DHTML has
the ability to change a webpages look, content and style once the document
has loaded on our demand without changing or deleting everything already
existing on the browser’s webpage. DHTML can change the content of a
webpage on demand without the browser having to erase everything else, i.e.
being able to alter changes on a webpage even after the document has
completely loaded.

90
Advantages:

 Size of the files are compact in compared to other interactional media


like Flash or Shockwave, and it downloads faster.
 It is supported by big browser manufacturers like Microsoft and
Netscape.
 Highly flexible and easy to make changes.
 Viewer requires no extra plug-ins for browsing through the webpage
that uses DHTML, they do not need any extra requirements or special
software to view it.
 User time is saved by sending less number of requests to the server. As
it is possible to modify and replace elements even after a page is loaded,
it is not required to create separate pages for changing styles which in
turn saves time in building pages and also reduces the number of
requests that are sent to the server.
 It has more advanced functionality than a static HTML. it is capable of
holding more content on the web page at the same time.

Difference between HTML and DHTML

Aspect HTML DHTML


Definition A markup language. A collection of technologies.
Functionality Used to create static web Capable of creating dynamic
pages. web pages.
Capabilities Cannot create animations Used to create animations and
or dynamic menus. dynamic menus.
Speed Sites are slower upon Sites are comparatively faster.
client-side technologies.
Styling and Creates simple web pages Uses HTML, CSS, and
Complexity with no styling (uses only JavaScript, resulting in more
one language). presentable web pages.
Server-Side Cannot be used as server- Can be used as server-side
Use side code. code.

91
Database Does not require database Requires database connectivity.
Connectivity connectivity.
File Files are stored using .htm Files are stored using .dhtm
Extensions or .html extensions. extension.
Browser Requires no processing Requires processing from the
Processing from the browser. browser.

--- UNIT – 3 COMPLETED ---

92
UNIT – 4

DYNAMIC HTML AND JAVASCRIPT

1. Dynamic HTML (DHTML)

DHTML stands for Dynamic Hypertext Markup language i.e., Dynamic HTML.

Dynamic HTML is not a markup or programming language but it is a term


that combines the features of various web development technologies for
creating the web pages dynamic and interactive.

The DHTML application was introduced by Microsoft with the release of the
4th version of IE (Internet Explorer) in 1997.

Components of Dynamic HTML

DHTML consists of the following four components or languages:

 HTML 4.0
 CSS
 JavaScript
 DOM.

1.1 Document Object Model (DOM)

The HTML DOM (Document Object Model) is a programming interface that


represents the structure of a web page in a way that programming languages
like JavaScript can understand and manipulate.

93
Think of it as a tree of objects where each part of your HTML document
(elements, attributes, text) is represented as a node, allowing you to
dynamically change or interact with the content and structure of the page.

HTML DOM Look Like

Imagine your webpage as a tree

 The document is the root.


 HTML tags like <html>, <head>, and <body> are branches.
 Attributes, text, and other elements are the leaves.

DOM Required

The DOM is essential because

 Dynamic Content Updates: Without reloading the page, the DOM


allows content updates (e.g., form validation, AJAX responses).
 User Interaction: It makes your webpage interactive (e.g., responding
to button clicks, form submissions).
 Flexibility: Developers can add, modify, or remove elements and styles
in real-time.

94
 Cross-Platform Compatibility: It provides a standard way for scripts
to interact with web documents, ensuring browser compatibility.

DOM Works

The DOM connects your webpage to JavaScript, allowing you to:

 Access elements (like finding an <h1> tag).


 Modify content (like changing the text of a <p> tag).
 React to events (like a button click).
 Create or remove elements dynamically.

Properties of the DOM

 Node-Based: Everything in the DOM is represented as a node (e.g.,


element nodes, text nodes, attribute nodes).
 Hierarchical: The DOM has a parent-child relationship, forming a tree
structure.
 Live: Changes made to the DOM using JavaScript are immediately
reflected on the web page.
 Platform-Independent: It works across different platforms, browsers,
and programming languages.

Commonly Used DOM Methods

Method Description
getElementById(id) Selects an element by its ID.
getElementsByClassName(class) Selects all elements with a given class.
querySelector(selector) Selects the first matching element.
querySelectorAll(selector) Selects all matching elements.
createElement(tag) Creates a new HTML element.
appendChild(node) Adds a child node to an element.
remove() Removes an element from the DOM.
addEventListener(event, fn) Attaches an event handler to an element.

95
Example: In this example, We use HTML element id to find the DOM HTML
element.

<html>

<body>

<h2>GFG</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 = [Link]("intro");

[Link]("demo").innerHTML =

"GFG introduction is: " + [Link];

</script>

</body>

</html>

96
Output:

Example: This example describes the representation of the HTML elements


in the tree structure.

<table>

<ROWS>

<tr>

<td>Car</td>

<td>Scooter</td>

</tr>

<tr>

<td>MotorBike</td>

<td>Bus</td>

</tr>

</ROWS>

</table>

97
Output:

DOM is not

 It is not a binary description where it does not define any binary source
code in its interfaces.
 It is not used to describe objects in XML or HTML whereas the DOM
describes XML and HTML documents as objects.
 It is not represented by a set of data structures; it is an interface that
specifies object representation.
 It does not show the criticality of objects in documents i.e it doesn’t
have information about which object in the document is appropriate to
the context and which is not.

98
Example: This example illustrates the dom-manipulation using
getElementById() Method.

<html>

<head>

<title>DOM manipulation</title>

</head>

<body>

<label>Enter Value 1: </label>

<input type="text" id="val1" />

<br />

<br />

<label>Enter Value 2: </label>

<input type=".text" id="val2" />

<br />

<button onclick="getAdd()">Click To Add</button>

<p id="result"></p>

<script type="text/javascript">

function getAdd() {

// Fetch the value of input with id val1

const num1 = Number([Link]("val1").value);

// Fetch the value of input with id val2

const num2 = Number([Link]("val2").value);

const add = num1 + num2;

[Link](add);

99
// Displays the result in paragraph using dom

[Link]("result").innerHTML = "Addition : " + add;

// Changes the color of paragraph tag with red

[Link]("result").[Link] = "red";

</script>

</body>

</html>

Output:

1.2 Accessing HTML and CSS Through DOM

The Document Object Model (DOM) is a programming interface for web


documents. It represents the page so that programs can change the document
structure, style, and content dynamically. The DOM provides a way to access
and manipulate HTML and CSS using JavaScript.

Get HTML element by Id

Generally, most developers use unique ids in the whole HTML document. The
user has to add the id to the particular HTML element before accessing the
HTML element with the id. Users can use getElementById() method to access
the HTML element using the id. If any element doesn’t exist with the passed
id into the getElementById method, it returns the null value.

100
Syntax:

[Link](element_ID);

Example: This example demonstrates the use of the getElementsById


method. Also, it prints the inner HTML of a returned object into the console
of the browser. Users can open the console in the Chrome web browser by
pressing ctrl + shift + I.

<!DOCTYPE html>

<html lang="en">

<head>

<title>Document</title>

</head>

<body>

<!-- Heading element with GFG id-->

<h1 id="GFG">

GFG

</h1>

<p>DOM getElementById() Method</p>

<script>

// Accessing the element by getElementById method

let temp = [Link]("GFG");

[Link](temp);

[Link]([Link]);

</script>

</body>

</html>

101
Output:

Get HTML element by className

In javascript, the getElementsByClassName() method is useful to access the


HTML elements using the className. The developers can use a single
className multiple times in a particular HTML document. When users try to
access an element using the className, it returns the collection of all objects
that include a particular class.

Syntax:

[Link](element_classnames);

Example: This example demonstrates the use of the


getElementsByClassName() method. It prints every element of the returned
collection object into the console.

<!DOCTYPE html>

<html lang="en">

<head>

<title>Document</title>

</head>

<body>

<!-- Multiple html element with GFG class name -->

<h1 class="GFG">GFG sample 1</h1>

<h1 class="GFG">GFG sample 2</h1>

<h1 class="GFG">GFG sample 3</h1>

102
<p>DOM getElementsByclassName() Method</p>

<script>

// Accessing the element by getElementsByclassName method

let temp = [Link]("GFG");

[Link](temp[0]);

[Link](temp[1]);

[Link](temp[2]);

</script>

</body>

</html>

Output:

Get HTML elements by CSS Selector

Users can select the HTML elements using the different CSS selectors such
as class, id, and tag name at a single time. HTML elements can be retrieved
using CSS selectors in two ways. The querySelector() method returns the first
element that matches the particular CSS selector. The querySelectorAll()
method returns all element that matches the particular CSS selector.

To use id/class as a parameter users have to add the ‘#‘/’.‘ sign before it.
Users can pass directly the tag name into the above 2 methods. Users don’t
need to separate CSS selectors when passing multiple CSS selectors as
parameters.

103
Syntax:

[Link](selectors);

[Link](selectors);

Example: This example demonstrates the use of the querySelector method.


In the below, code we have used the different CSS selectors to access the
HTML elements from the DOM.

<!DOCTYPE html>

<html lang="en">

<head>

<title>Document</title>

</head>

<body>

<!-- html element with classnames and id -->

<h1 class="gfg1" id="g1">GFG sample 1</h1>

<h1 class="gfg1" id="g2">GFG sample 2</h1>

<p class="gfg1">GFG sample 3</p>

<script>

// Accessing the element by class name

// using querySelector

let temp = [Link](".gfg1");

[Link](temp);

// Accessing the element by id using querySelector

temp = [Link]("#g2");

[Link](temp);

// Accessing the element by class name and


104
// id using querySelector

temp = [Link](".gfg1#g2");

[Link](temp);

// Accessing the element by tag name that

// includes the particular class

temp = [Link]("p.gfg1");

[Link](temp);

</script>

</body>

</html>

Output:

1.3 Dynamic Content Styles and Positioning

Dynamic content styles and positioning enable elements on a web page to


move, resize, or change appearance based on user interactions, timers, or
other conditions. This feature enhances user experience by making web pages
more interactive and visually appealing.

Dynamic styles and positioning involve the use of JavaScript in conjunction


with CSS to modify the visual properties of HTML elements in real time. These
changes can be triggered by events such as user input, page load, timers, or
other conditions.

105
Key Concepts:

i.) Dynamic Styles:

 Refers to changing CSS properties of elements such as color, size,


visibility, etc., using JavaScript.
 Enhances the visual appearance and interactivity of web pages.

ii.) Dynamic Positioning:

 Involves moving elements around the page using CSS properties like
left, top, right, and bottom.
 Uses absolute, relative, fixed, or sticky positioning to control the
placement of elements.

Example:

<!DOCTYPE html>

<html>

<head>

<title>Dynamic Content Styles and Positioning</title>

<style>

#dynamicDiv {

position: absolute;

left: 50px;

top: 50px;

background-color: blue;

width: 100px;

height: 100px;

transition: all 0.5s ease;

106
</style>

</head>

<body>

<h1>Dynamic Content Example</h1>

<div id="dynamicDiv"></div>

<script>

function moveAndStyleDiv() {

let div = [Link]("dynamicDiv");

[Link] = "200px";

[Link] = "100px";

[Link] = "red";

[Link] = "150px";

[Link] = "150px";

setTimeout(moveAndStyleDiv, 2000);

</script>

</body>

</html>

Output:

Before Transition O/P:

107
After Transition O/P:

Explanation

 HTML Structure: Contains a div element with an initial position and


style.
 CSS:
o #dynamicDiv: Defines the initial styles for the div, including
position, size, and background color.
o transition: all 0.5s ease;: Adds a smooth transition effect when
the styles change.
 JavaScript:
o moveAndStyleDiv(): A function that changes the position, size,
and color of the div element.
o setTimeout(moveAndStyleDiv, 2000);: Calls the function after
a 2-second delay.

Dynamic Styling Techniques

i.) Changing Colors:

 Use JavaScript to change the backgroundColor, color, borderColor, etc.

[Link] = "red";

108
ii.) Resizing Elements:

 Modify the width and height properties to resize elements dynamically.

[Link] = "150px";

[Link] = "150px";

iii.) Moving Elements:

 Adjust the left, top, right, and bottom properties for dynamic
positioning.

[Link] = "200px";

[Link] = "100px";

1.4 Event Bubbling

Event bubbling is a way that events (like clicks or key presses) move through
the elements in an HTML document. When an event happens in a specific
element (like a button), it first affects that element and then moves up to its
parent elements, triggering any event listeners attached to those parents. This
process is called “bubbling” because it starts at the bottom (the innermost
element) and bubbles up to the top (the outer elements).

Event Bubbling Works

 Starting Point: When you interact with an element, such as clicking a


button, the event starts with that element.
 Propagation: The event then moves up through its parent elements in
the DOM (Document Object Model) tree, triggering any event listeners
that are set up for that event type.
 Order of Execution: The innermost element’s event listener is executed
first, followed by the outer elements in the order they appear in the
DOM.

109
Syntax:

addEventListener(type, listener, useCapture)

 type: Use to refer to the type of event.


 listener: Function we want to call when the event of the specified type
occurs.
 userCapture: Boolean value. The boolean value indicates the event
phase. By Default useCapture is false. It means it is in the bubbling
phase.

Example: This example we emonstrates event bubbling in JavaScript. When


the “Child” button is clicked, both the child and parent event listeners are
triggered, displaying alerts. Event bubbling causes the event to propagate up
the DOM hierarchy.

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport"

content="width=device-width, initial-scale=1.0">

<title>Bubbling Event in Javascript</title>

</head>

<body>

<h2>Bubbling Event in Javascript</h2>

<div id="parent">

<button>

<h2>Parent</h2>

</button>

110
<button id="child">

<p>Child</p>

</button>

</div><br>

<script>

[Link](

"child").addEventListener("click", function () {

alert("You clicked the Child element!");

}, false);

[Link](

"parent").addEventListener("click", function () {

alert("You clicked the parent element!");

}, false);

</script>

</body>

</html>

Output:

111
1.5 Data Binding

Data Binding: Data binding in DHTML using JavaScript refers to the process
of automatically updating the user interface (UI) based on changes in the data
model and vice versa. This is achieved by linking HTML elements to JavaScript
variables or objects so that any change in the data model is immediately
reflected in the UI.

Key Concepts

i.) Two-Way Data Binding:

 Changes in the UI elements automatically update the underlying data


model.
 Changes in the data model automatically update the UI elements.

ii.) One-Way Data Binding:

 Only updates the UI when the data model changes, but not the other
way around.

Two-Way Data Binding

In two-way data binding, changes in the UI elements automatically update


the underlying data model, and changes in the data model automatically
update the UI elements.

Example Program for Two-Way Data Binding:

<!DOCTYPE html>

<html>

<head>

<title>Two-Way Data Binding Example</title>

<style>

.inputField {

display: block;

112
margin: 10px 0;

</style>

</head>

<body>

<h1>Two-Way Data Binding Example</h1>

<label for="nameInput">Enter your name:</label>

<input type="text" id="nameInput" class="inputField"


oninput="updateName()">

<p>Your name is: <span id="nameOutput"></span></p>

<script>

// Data Model

let userName = '';

// Function to update data model and UI

function updateName() {

userName = [Link]("nameInput").value;

[Link]("nameOutput").innerText = userName;

// Initial Binding

[Link]("nameInput").value = userName;

[Link]("nameOutput").innerText = userName;

</script>

</body>

</html>

113
Output:

Explanation:

 The input field is bound to the userName variable.


 As the user types, the updateName function updates the userName
variable and the content of the <span> element.

One-Way Data Binding

In one-way data binding, the UI elements are updated based on changes in


the data model, but changes in the UI do not automatically update the data
model.

Example Program for One-Way Data Binding:

<!DOCTYPE html>

<html>

<head>

<title>One-Way Data Binding Example</title>

<style>

.inputField {

display: block;

margin: 10px 0;

</style>

114
</head>

<body>

<h1>One-Way Data Binding Example</h1>

<label for="ageInput">Enter your age:</label>

<input type="number" id="ageInput" class="inputField">

<p>Your age is: <span id="ageOutput"></span></p>

<button onclick="displayAge()">Display Age</button>

<script>

// Data Model

let userAge = 0;

// Function to update UI from data model

function displayAge() {

userAge = [Link]("ageInput").value;

[Link]("ageOutput").innerText = userAge;

</script>

</body>

</html>

Output:

115
Explanation:

 The input field allows the user to enter their age.


 The displayAge function updates the UI to display the age based on the
value of the userAge variable when the button is clicked.

Benefits of Data Binding

i.) Ease of Synchronization:

 Automatically keeps the data model and UI in sync, reducing the need
for manual updates.

ii.) Enhanced User Experience:

 Provides immediate feedback to users as they interact with the UI,


making the web page more responsive and interactive.

iii.) Simplified Code Maintenance:

 Reduces boilerplate code for updating the UI, making the code easier to
maintain and understand.

2. JavaScript

JavaScript is a client-side scripting language used to add interactivity to web


pages. It enhances user experience by enabling dynamic content updates,
form validation, and event handling.

2.1 What is JavaScript?

JavaScript is a powerful and flexible programming language for the web that
is widely used to make websites interactive and dynamic. JavaScript can also
able to change or update HTML and CSS dynamically. JavaScript can also
run on servers using tools like [Link], allowing developers to build entire
applications with it.

116
2.2 How to Develop JavaScript

Developing JavaScript involves embedding it within HTML files or linking


external .js files. The <script> tag is used to include JavaScript in web pages.

Example of Inline JavaScript:

<script>

alert("Hello, World!");

</script>

Example of External JavaScript:

<!-- HTML File -->

<script src="[Link]"></script>

<!-- [Link] File -->

[Link]("External JavaScript File Loaded!");

2.3 Variables in JavaScript

Variables are used to store data in JavaScript so that we can later access the
data. JavaScript is a dynamically typed language so the type of variables is
decided at runtime. Therefore there is no need to explicitly define the type of
a variable. We can declare variables in JavaScript in three ways:

 JavaScript var keyword


 JavaScript let keyword
 JavaScript const keyword

117
Example:

var a = 10 // Old style

let b = 20; // Prferred for non-const

const c = 30; // Preferred for const (cannot be changed)

[Link](a);

[Link](b);

[Link](c);

Output:

10

20

30

i.) var keyword

The var keyword is used to declare variables that are function-scoped or


globally-scoped, depending on where they are declared. Variables declared
with var can be re-declared and updated.

Example Program:

<!DOCTYPE html>

<html>

<head>

<title>var Example</title>

</head>

<body>

<script>

var name = "Alice";


118
[Link](name); // Output: Alice

var name = "Bob";

[Link](name); // Output: Bob

</script>

</body>

</html>

ii.) let keyword

The let keyword is used to declare block-scoped variables. Variables declared


with let can be updated but not re-declared within the same scope.

Example Program:

<!DOCTYPE html>

<html>

<head>

<title>let Example</title>

</head>

<body>

<script>

let age = 25;

[Link](age); // Output: 25

age = 30;

[Link](age); // Output: 30

119
[Link](age);// Output: Error: age is not defined

</script>

</body>

</html>

iii.) const keyword

The const keyword is used to declare block-scoped variables that must be


initialized at the time of declaration and cannot be reassigned. However, the
contents of objects and arrays declared with const can be mutated.

Example Program:

<!DOCTYPE html>

<html>

<head>

<title>const Example</title>

</head>

<body>

<script>

const country = "India";

[Link](country); // Output: India

country = "America";

[Link](country); // Output: Error: Assignment to constant variable.

</script>

</body>

</html>

120
Comparison of properties of let, var, and const keywords in JavaScript:

Property var let const


Scope Function scoped Block scoped Block scoped
Updation Mutable Mutable Immutable
Redeclaration Can be redeclared Cannot be Cannot be
redeclared redeclared
Hoisting Hoisted at the top Hoisted at the top Hoisted at the top
Origins Pre ES2015 ES2015 (ES6) ES2015 (ES6)
Support Supported in older Not supported in Not supported in
browsers older browsers older browsers

2.4 Functions in JavaScript

A function in JavaScript is a reusable block of code that performs a specific


task. You define it once, and then you can run (or “call”) it whenever you need
that task done in your program.

Example:

function sum(x, y) {

return x + y;

[Link](sum(6, 9));

Output:

15

Function Syntax and Working

A function definition is sometimes also termed a function declaration or


function statement. Below are the rules for creating a function in JavaScript:

 Begin with the keyword function followed by,


 A user-defined function name (In the above example, name is sum)

121
 A list of parameters enclosed within parentheses and separated by
commas (In the above example, parameters are x and y)
 A list of statements composing the body of the function enclosed within
curly braces {} (In the above example, statement is “return x + y”).

Return Statement

There are some situations when we want to return some values from a
function after performing some operations. In such cases, we make use of the
return. This is an optional statement. In the above function, “sum()” returns
the sum of two as result.

Function Parameters

Parameters are input passed to a function. In the above example, sum() takes
two parameters, x and y.

Calling Functions

After defining a function, the next step is to call them to make use of the
function. We can call a function by using the function name separated by the
value of parameters enclosed between the parenthesis.

Example:

// Function Definition

function welcomeMsg(name) {

return ("Hello " + name + " welcome to GFG");

let nameVal = "User";

// calling the function

[Link](welcomeMsg(nameVal));

122
Output:

Hello User welcome to GFG

Why Functions?

 Functions can be used multiple times, reducing redundancy.


 Break down complex problems into manageable pieces.
 Manage complexity by hiding implementation details.
 Can call themselves to solve problems recursively.

Function Invocation

The function code you have written will be executed whenever it is called.

 Triggered by an event (e.g., a button click by a user).


 When explicitly called from JavaScript code.
 Automatically executed, such as in self-invoking functions.

Function Expression

It is similar to a function declaration without the function name. Function


expressions can be stored in a variable assignment.

Syntax:

let geeksforGeeks= function(paramA, paramB) {

// Set of statements

const square = function (number) {

return number * number;

};

const x = square(4); // x gets the value 16

[Link](x);

123
Output:

16

Arrow Function:

Arrow Function is one of the most used and efficient methods to create a
function in JavaScript because of its comparatively easy implementation. It is
a simplified as well as a more compact version of a regular or normal function
expression or syntax.

Syntax:

let function_name = (argument1, argument2 ,..) => expression

const a = ["Hydrogen", "Helium", "Lithium", "Beryllium"];

const a2 = [Link](function (s) {

return [Link];

});

[Link]("Normal way ", a2); // [8, 6, 7, 9]

const a3 = [Link]((s) => [Link]);

[Link]("Using Arrow Function ", a3); // [8, 6, 7, 9]

Output:

Normal way [ 8, 6, 7, 9 ]

Using Arrow Function [ 8, 6, 7, 9 ]

2.5 Conditions in JavaScript

JavaScript conditional statements allow you to execute specific blocks of code


based on conditions. If the condition is met, a particular block of code will
run; otherwise, another block of code will execute based on the condition.

124
i.) Using if Statement

The if statement is used to evaluate a particular condition. If the condition


holds true, the associated code block is executed.

Example:

let x = 20;

if (x % 2 === 0) {

[Link]("Even");

if (x % 2 !== 0) {

[Link]("Odd");

};

Output:

Even

ii.) Using if-else Statement

The if-else statement will perform some action for a specific condition. Here
we are using the else statement in which the else statement is written after
the if statement and it has no condition in their code block.

Example:

let age = 25;

if (age >= 18) {

[Link]("Adult")

} else {

[Link]("Not an Adult")

};

125
Output:

Adult

iii.) else if Statement

The else if statement in JavaScript allows handling multiple possible


conditions and outputs, evaluating more than two options based on whether
the conditions are true or false.

Example:

const x = -3;

if (x > 0) {

[Link]("Positive.");

} else if (x < 0) {

[Link]("Negative.");

} else {

[Link]("Zero.");

};

Output:

Negative.

iv.) Using Switch Statement (JavaScript Switch Case)

As the number of conditions increases, you can use multiple else-if


statements in JavaScript. but when we dealing with many conditions, the
switch statement may be a more preferred option.

126
Example:

const marks = 95;

let Branch;

switch (true) {

case marks >= 90:

Branch = "Computer science engineering";

break;

case marks >= 80:

Branch = "Mechanical engineering";

break;

case marks >= 70:

Branch = "Chemical engineering";

break;

case marks >= 60:

Branch = "Electronics and communication";

break;

case marks >= 50:

Branch = "Civil engineering";

break;

default:

Branch = "Bio technology";

break;

[Link](`Student Branch name is : ${Branch}`);

127
Output:

Student Branch name is : Computer science engineering

v.) Using Ternary Operator ( ?: )

The conditional operator, also referred to as the ternary operator (?:), is a


shortcut for expressing conditional statements in JavaScript.

Example:

let age = 21;

const result =

(age >= 18) ? "You are eligible to vote."

: "You are not eligible to vote.";

[Link](result);

Output:

You are eligible to vote.

vi.) Nested if…else

Nested if…else statements in JavaScript allow us to create complex


conditional logic by checking multiple conditions in a hierarchical manner.
Each if statement can have an associated else block, and within each if or else
block, you can nest another if…else statement. This nesting can continue to
multiple levels, but it’s important to maintain readability and avoid excessive
complexity.

Example:

let weather = "sunny";

let temperature = 25;

if (weather === "sunny") {

128
if (temperature > 30) {

[Link]("It's a hot day!");

} else if (temperature > 20) {

[Link]("It's a warm day.");

} else {

[Link]("It's a bit cool today.");

} else if (weather === "rainy") {

[Link]("Don't forget your umbrella!");

} else {

[Link]("Check the weather forecast!");

};

Output

It's a warm day.

Conditional Description
Statement
if statement Executes a block of code if a specified condition is true.
else statement Executes a block of code if the condition of the
preceding if statement is false.
else if statement Adds more conditions to the if statement, allowing
multiple alternative conditions to be tested.
switch statement Evaluates an expression, then executes the case
statement that matches the expression’s value.
Ternary operator Provides a concise way to write if-else statements in a
single line.
Nested if-else Allows for multiple conditions to be checked in a
statement hierarchical manner.

129
2.6 Loops and Repetition

JavaScript loops are essential for efficiently handling repetitive tasks. They
execute a block of code repeatedly as long as a specified condition remains
true. These loops are powerful tools for automating tasks and streamlining
your code.

For example, suppose we want to print “Hello World” 5 times. This can be
done using JS Loop easily. In Loop, the statement needs to be written only
once and the loop will be executed 5 times as shown below:

for (let i = 0; i < 5; i++) {

[Link]("Hello World!");

Output:

Hello World!

Hello World!

Hello World!

Hello World!

Hello World!

Types of Loops and Repetition in JavaScript

 for Loop
 while Loop
 do-while Loop
 for-in Loop
 for-of Loop
 Labeled Statement
 Break Statement
 Continue Statement
 Infinite Loop (Loop Error)

130
i.) JavaScript for Loop

The JS for loop provides a concise way of writing the loop structure. The for
loop contains initialization, condition, and increment/decrement in one line
thereby providing a shorter, easy-to-debug structure of looping.

Syntax:

for (initialization; testing condition; increment/decrement) {

statement(s)

Flowchart:

 Initialization condition: It initializes the variable and mark the start


of a for loop. An already declared variable can be used or a variable can
be declared, local to loop only.
 Test Condition: It is used for testing the exit condition of a for loop. It
must return a boolean value. It is also an Entry Control Loop as the
condition is checked prior to the execution of the loop statements.
 Statement execution: Once the condition is evaluated to be true, the
statements in the loop body are executed.
 Increment/ Decrement: It is used for updating the variable for the
next iteration.

131
 Loop termination: When the condition becomes false, the loop
terminates marking the end of its life cycle.

Example:

// JavaScript program to illustrate for loop

let x;

// for loop begins when x = 2

// and runs till x <= 4

for (x = 2; x <= 4; x++) {

[Link]("Value of x: " + x);

Output:

Value of x: 2

Value of x: 3

Value of x: 4

ii.) JavaScript while Loop

The JS while loop is a control flow statement that allows code to be executed
repeatedly based on a given Boolean condition. The while loop can be thought
of as a repeating if statement.

Syntax:

while (boolean condition) {

loop statements...

132
Flowchart:

 While loop starts with checking the condition. If it is evaluated to be


true, then the loop body statements are executed otherwise first
statement following the loop is executed. For this reason, it is also called
the Entry control loop
 Once the condition is evaluated to be true, the statements in the loop
body are executed. Normally the statements contain an updated value
for the variable being processed for the next iteration.
 When the condition becomes false, the loop terminates which marks
the end of its life cycle.

Example:

// JavaScript code to use while loop

let val = 1;

while (val < 6) {

[Link](val);

val += 1;

133
Output:

iii.) JavaScript do-while Loop

The JS do-while loop is similar to the while loop with the only difference is
that it checks for the condition after executing the statements, and therefore
is an example of an Exit Control Loop. It executes loop content at least once
event the condition is false.

Syntax:

do {

Statements...

while (condition);

Flowchart:

134
 The do-while loop starts with the execution of the statement(s). There
is no checking of any condition for the first time.
 After the execution of the statements and update of the variable value,
the condition is checked for a true or false value. If it is evaluated to be
true, the next iteration of the loop starts.
 When the condition becomes false, the loop terminates which marks
the end of its life cycle.
 It is important to note that the do-while loop will execute its statements
at least once before any condition is checked and therefore is an
example of the exit control loop.

Example:

let test = 1;

do {

[Link](test);

test++;

} while(test <= 5)

Output:

iv.) JavaScript for-in Loop

JS for-in loop is used to iterate over the properties of an object. The for-in loop
iterates only over those keys of an object which have their enumerable
property set to “true”.

135
Syntax:

for(let variable_name in object_name) {

// Statement

Example: This example shows the use of for-in loop.

let myObj = { x: 1, y: 2, z: 3 };

for (let key in myObj) {

[Link](key, myObj[key]);

Output:

x1

y2

z3

v.) JavaScript for-of Loop

JS for-of loop is used to iterate the iterable objects for example – array, object,
set and map. It directly iterate the value of the given iterable object and has
more concise syntax than for loop.

Syntax:

for(let variable_name of object_name) {

// Statement

Example: This example shows the use of for-of loop.

let arr = [1, 2, 3, 4, 5];


136
for (let value of arr) {

[Link](value);

Output:

vi.) JavaScript Labeled Statement

JS label keyword does not include a goto keyword. Users can use the continue
keyword with the label statement. Furthermore, users can use the break
keyword to terminate the loop/block. You can also use the break keyword
without defining the label but it terminates only the parent loop/block. To
terminate the outer loop from the inner loop using the break keyword, users
need to define the label.

Syntax:

Label:

statement (loop or block of code)

Example:

let sum = 0, a = 1;

// Label for outer loop

outerloop: while (true) {

a = 1;

137
// Label for inner loop

innerloop: while (a < 3) {

sum += a;

if (sum > 12) {

// Break outer loop from inner loop

break outerloop;

[Link]("sum = " + sum);

a++;

Output:

sum = 1

sum = 3

sum = 4

sum = 6

sum = 7

sum = 9

sum = 10

sum = 12

vii.) JavaScript Break Statement

JS break statement is used to terminate the execution of the loop or switch


statement when the condition is true.

138
Syntax:

break;

Example:

for (let i = 1; i < 6; i++) {

if (i == 4)

break;

[Link](i);

Output:

viii.) JavaScript Continue Statement

JS continue statement is used to break the iteration of the loop and follow
with the next iteration. The break in iteration is possible only when the
specified condition going to occur. The major difference between the continue
and break statement is that the break statement breaks out of the loop
completely while continue is used to break one statement and iterate to the
next statement.

Syntax:

continue;

139
Example:

for (let i = 0; i < 11; i++) {

if (i % 2 == 0)

continue;

[Link](i);

Output:

ix.) JavaScript Infinite Loop (Loop Error)

One of the most common mistakes while implementing any sort of loop is that
it may not ever exit, i.e. the loop runs for infinite times. This happens when
the condition fails for some reason.

Example: This example shows an infinite loop.

// JavaScript program to illustrate infinite loop

// Infinite loop because condition is not false

// condition should have been i>0.

for (let i = 5; i != 0; i -= 2) {

[Link](i);

let x = 5;
140
// Infinite loop because update statement

// is not provided

while (x == 5) {

[Link]("In the loop");

Output:

-1

-3

... (continues indefinitely for the for loop)

"In the loop" (repeats indefinitely for the while loop)

--- UNIT – 4 COMPLETED ---

141
UNIT – 5

ADVANCED JAVASCRIPT AND OBJECTS

1. Advanced Scripting in JavaScript

Advanced scripting in JavaScript involves using more complex features and


techniques to build dynamic and interactive web applications. This includes
working with objects, handling events, manipulating the DOM, and
performing client-side validations.

1.1 JavaScript and Objects

An object in JavaScript is a data structure used to store related data


collections. It stores data as key-value pairs, where each key is a unique
identifier for the associated value. Objects are dynamic, which means the
properties can be added, modified, or deleted at runtime.

There are two primary ways to create an object in JavaScript: Object Literal
and Object Constructor.

1.) Creation sing Object Literal

The object literal syntax allows you to define and initialize an object with curly
braces {}, setting properties as key-value pairs.

Example:

let obj = {

name: "Sourav",

age: 23,

job: "Developer"

};

[Link](obj);

Output:

{ name: 'Sourav', age: 23, job: 'Developer' }

142
2.) Creation Using new Object() Constructor

Example:

let obj = new Object();

[Link]= "Sourav",

[Link]= 23,

[Link]= "Developer"

[Link](obj);

Output:

{ name: 'Sourav', age: 23, job: 'Developer' }

Basic Operations on JavaScript Objects

i.) Accessing Object Properties

You can access an object’s properties using either dot notation or bracket
notation

let obj = { name: "Sourav", age: 23 };

// Using Dot Notation

[Link]([Link]);

// Using Bracket Notation

[Link](obj["age"]);

Output:

Sourav

23

143
ii.) Modifying Object Properties

Properties in an object can be modified by reassigning their values.

let obj = { name: "Sourav", age: 22 };

[Link](obj);

[Link] = 23;

[Link](obj);

Output:

{ name: 'Sourav', age: 22 }

{ name: 'Sourav', age: 23 }

iii.) Adding Properties to an Object

You can dynamically add new properties to an object using dot or bracket
notation.

let obj = { model: "Tesla" };

[Link] = "Red";

[Link](obj);

Output:

{ model: 'Tesla', color: 'Red' }

iv.) Removing Properties from an Object

The delete operator removes properties from an object.

let obj = { model: "Tesla", color: "Red" };

delete [Link];

[Link](obj);

144
Output:

{ model: 'Tesla' }

v.) Checking if a Property Exists

You can check if an object has a property using the in operator or


hasOwnProperty() method.

let obj = { model: "Tesla" };

[Link]("color" in obj);

[Link]([Link]("model"));

Output:

false

true

vi.) Iterating Through Object Properties

Use for…in loop to iterate through the properties of an object.

let obj = { name: "Sourav", age: 23 };

for (let key in obj) {

[Link](key + ": " + obj[key]);

Output:

name: Sourav

age: 23

145
vii.) Merging Objects

Objects can be merged using [Link]() or the spread syntax { …obj1,


…obj2 }.

let obj1 = { name: "Sourav" };

let obj2 = { age: 23};

let obj3 = { ...obj1, ...obj2 };

[Link](obj3);

Output:

{ name: 'Sourav', age: 23 }

viii.) Object Length

You can find the number of properties in an object using [Link]().

let obj = { name: "Sourav", age: 23 };

[Link]([Link](obj).length);

Output:

Recognizing a JavaScript Object

To check if a value is an object, use typeof and verify it’s not null.

let obj = { name: "Sourav" };

[Link](typeof obj === "object" && obj !== null);

Output:

true

146
Key Differences Between {} and new Object()

Feature {} (Object Literal) new Object() (Object


Constructor)
Ease of Use More concise and readable. Less commonly used.
Performance Faster and more efficient. Slightly slower due to the
constructor call.
Prototypal Directly inherits from Same, but adds an extra
Inheritance [Link]. layer of abstraction.
Customization Literal syntax is sufficient Useful only in rare
for most use cases. scenarios.

1.2 JavaScript’s Built-In Objects

JavaScript includes several built-in objects for handling data and operations
efficiently. These built-in objects come with pre-defined methods and
properties that make it easier to perform common tasks such as mathematical
calculations, date and time manipulation, and string operations. Here is a
detailed explanation of some of the most commonly used built-in objects in
JavaScript:

i.) Math Object

The Math object is used for mathematical operations. It provides properties


and methods for performing mathematical tasks, such as finding the square
root, rounding numbers, generating random numbers, and more. The Math
object is not a constructor, so you don't need to create an instance of it.

Example of Math Object:

let result = [Link](16);

[Link](result); // Output: 4

147
Explanation:

 [Link](16): Calculates the square root of 16, which is 4.


 [Link](result): Outputs the result, which is 4.

ii.) Date Object

The Date object is used for working with dates and times. It allows you to
create, manipulate, and format dates and times. You can create a new date
object using the new Date() constructor, and there are various methods
available to get and set different components of a date (such as year, month,
day, hour, minute, second).

Example of Date Object:

let today = new Date();

[Link]([Link]()); // Outputs current date in string format

Explanation:

 new Date(): Creates a new Date object representing the current date and
time.
 [Link](): Converts the date to a readable string format.
 [Link]([Link]()): Outputs the current date as a string.

iii.) String Object

The String object is used for string manipulation. It provides methods for
various string operations, such as finding the length of a string, converting to
uppercase or lowercase, finding substrings, replacing parts of a string, and
more.

Example of String Object:

let message = "Hello, World!";

[Link]([Link]()); // Output: HELLO, WORLD!

148
Explanation:

 [Link](): Converts the string to uppercase letters.


 [Link]([Link]()): Outputs the uppercase string.

2. The Document Object Model (DOM)

The DOM represents the structure of a web page as a tree of nodes. It enables
developers to dynamically interact with HTML elements, modify styles, or
create new elements.

2.1 DOM and Web Browser Environments

The web browser environment is a crucial aspect of web development,


providing various objects that allow developers to interact with the browser
and the web page. Three primary objects in this environment are the Window
object, the Document object, and the Navigator object. Each of these objects
provides specific functionalities that enable developers to manipulate the
browser window, the content of web pages, and gather information about the
browser.

1.) Window Object

The Window object represents the browser window or frame. It is the global
object in a web browser environment, meaning all global JavaScript objects,
functions, and variables automatically become members of the Window
object. This object provides methods to manipulate the browser window, such
as opening, closing, resizing, and moving the window, as well as controlling
the history and setting timeouts.

Key Methods and Properties:

 [Link](): Displays an alert dialog with a specified message.


 [Link](): Opens a new browser window or tab.
 [Link](): Closes the current browser window.

149
 [Link] and [Link]: Get the height and width
of the window's content area.

Example:

// Display an alert

[Link]("Hello, World!");

// Open a new window

let newWindow = [Link]("[Link] "_blank",


"width=600,height=400");

// Get the window dimensions

let width = [Link];

let height = [Link];

[Link](`Window dimensions: ${width}x${height}`);

2.) Document Object

The Document object represents the web page loaded in the browser. It is part
of the DOM (Document Object Model) and provides methods and properties
to access and manipulate the content, structure, and style of the web page.
This object allows developers to dynamically modify the HTML and CSS of a
page.

Key Methods and Properties:

 [Link](): Selects an element by its ID.


 [Link](): Creates a new HTML element.
 [Link](): Selects the first element that matches a
specified CSS selector.
 [Link]: Represents the <body> element of the document.

150
Example:

// Create a new paragraph element

let paragraph = [Link]("p");

[Link] = "This is a dynamically created paragraph.";

[Link](paragraph);

// Select an element by ID and change its content

let header = [Link]("header");

[Link] = "Updated Header Text";

// Use querySelector to select an element and change its style

let div = [Link](".my-div");

[Link] = "lightblue";

3.) Navigator Object

The Navigator object provides information about the web browser and the
user's environment. It includes properties that reveal details about the
browser's version, the user's operating system, and whether certain browser
features are enabled. This information is useful for tailoring the user
experience based on the user's browser and device capabilities.

Key Methods and Properties:

 [Link]: Returns the user-agent string of the browser.


 [Link]: Provides information about the operating system.
 [Link]: Indicates whether the browser is connected to the
internet.
 [Link]: Returns the preferred language of the user.

151
Example:

// Get browser user-agent

let userAgent = [Link];

[Link](`User-Agent: ${userAgent}`);

// Check if the browser is online

let onlineStatus = [Link] ? "online" : "offline";

[Link](`The browser is currently ${onlineStatus}.`);

// Get the user's platform

let platform = [Link];

[Link](`Platform: ${platform}`);

// Get the user's preferred language

let language = [Link];

[Link](`Preferred Language: ${language}`);

3. Forms and Validations

JavaScript Form Validation is a way to ensure that the data users enter into
a form is correct before it gets submitted. This helps ensure that things like
emails, passwords, and other important details are entered properly, making
the user experience smoother and the data more accurate.

3.1 HTML Form Elements

The HTML <form> comprises several elements, each serving a unique


purpose. For instance, the <label> element defines labels for other <form>
elements. On the other hand, the <input> element is versatile and can be used
to capture various types of input data such as text, password, email, and more
simply by altering its type attribute.

152
Commonly Used Input Types in HTML Forms

In HTML forms, various input types are used to collect different types of data
from users. Here are some commonly used input types:

HTML Forms Example

Example 1: Basic HTML Forms

Example: This HTML form collects user personal information such as


username and password with a button to submit the form.

<!DOCTYPE html>

<html lang="en">

<head>

<title>Html Forms</title>

</head>

<body>

<h2>HTML Forms</h2>

<form>

<label for="username">Username:</label><br>

<input type="text" id="username" name="username"><br><br>

<label for="password">Password:</label><br>

<input type="password" id="password" name="password"><br><br>

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

</form>

</body>

</html>

153
Output:

Example 2: Advance HTML Forms

This HTML form collects user personal information, including name, email,
password, gender, date of birth, and address. It features proper styling for
input fields and submission buttons.

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>HTML Form</title>

<style>

body {

display: flex;

154
justify-content: center;

align-items: center;

height: 100vh;

margin: 0;

background-color: #f0f0f0;

form {

width: 400px;

background-color: #fff;

padding: 20px;

border-radius: 8px;

box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);

fieldset {

border: 1px solid black;

padding: 10px;

margin: 0;

legend {

font-weight: bold;

margin-bottom: 10px;

155
label {

display: block;

margin-bottom: 5px;

input[type="text"],

input[type="email"],

input[type="password"],

textarea,

input[type="date"] {

width: calc(100% - 20px);

padding: 8px;

margin-bottom: 10px;

box-sizing: border-box;

border: 1px solid #ccc;

border-radius: 4px;

.gender-group {

margin-bottom: 10px;

.gender-group label {

display: inline-block;

margin-left: 10px;

156
input[type="radio"] {

margin-left: 10px;

vertical-align: middle;

input[type="submit"] {

padding: 10px 20px;

border-radius: 5px;

cursor: pointer;

</style>

</head>

<body>

<form>

<fieldset>

<legend>User Personal Information</legend>

<label for="name">Enter your full name:</label>

<input type="text" id="name" name="name" required />

<label for="email">Enter your email:</label>

<input type="email" id="email" name="email" required />

<label for="password">Enter your password:</label>

<input type="password" id="password" name="pass" required />

<label for="confirmPassword">Confirm your password:</label>

<input type="password" id="confirmPassword" name="confirmPass" required


/>

157
<label>Enter your gender:</label>

<div class="gender-group">

<input type="radio" name="gender" value="male" id="male" required />

<label for="male">Male</label>

<input type="radio" name="gender" value="female" id="female" />

<label for="female">Female</label>

<input type="radio" name="gender" value="others" id="others" />

<label for="others">Others</label>

</div>

<label for="dob">Enter your Date of Birth:</label>

<input type="date" id="dob" name="dob" required />

<label for="address">Enter your Address:</label>

<textarea id="address" name="address" required></textarea>

<input type="submit" value="Submit" />

</fieldset>

</form>

</body>

</html>

158
Output:

Here are some of the key attributes that can be used with the <form> element:

 action: This attribute specifies where to send the form-data when a


form is submitted. The value of this attribute is typically a URL.
 method: This attribute defines the HTTP method used to send the form-
data. The values can be “get” or “post”.

159
 target: This attribute specifies where to display the response received
after submitting the form. The values can be “_blank”, “_self”, “_parent”,
“_top”, or the name of an iframe.
 enctype: This attribute is used when method=“post”. It specifies how
the form-data should be encoded when submitting it to the server. The
values can be “application/x-www-form-urlencoded”, “multipart/form-
data”, or “text/plain”.
 autocomplete: This attribute specifies whether a form should have
autocomplete on or off. When autocomplete is on, the browser
automatically completes values based on values that the user has
entered before.
 novalidate: This Boolean attribute specifies that the form-data should
not be validated on submission.

3.2 JavaScript Form Validation

JavaScript Form Validation is a way to ensure that the data users enter into
a form is correct before it gets submitted. This helps ensure that things like
emails, passwords, and other important details are entered properly, making
the user experience smoother and the data more accurate.

Steps for Form Validation in JavaScript

When we validate a form in JavaScript, we typically follow these steps:

Data Retrieval:

The first step is to get the user’s values entered into the form fields (like name,
email, password, etc.). This is done using [Link], which
refers to the form with the name “RegForm”.

Data Validation:

Name Validation: We check to make sure the name field isn’t empty and
doesn’t contain any numbers.

Address Validation: We check that the address field isn’t empty.

160
Email Validation: We make sure that the email field isn’t empty and that it
includes the “@” symbol.

Password Validation: We ensure that the password field isn’t empty and that
the password is at least 6 characters long.

Course Selection Validation: We check that a course has been selected from
a dropdown list.

Error Handling:

If any of the checks fail, an alert message is shown to the user using
[Link], telling them what’s wrong.

The form focuses on the field that needs attention, helping the user easily fix
the error.

Submission Control:

If all the validation checks pass, the function returns true, meaning the form
can be submitted. If not, it returns false, stopping the form from being
submitted.

Focus Adjustment:

The form automatically focuses on the first field that has an error, guiding the
user to fix it.

HTML:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8" />

<meta name="viewport" content=

"width=device-width, initial-scale=1.0" />

<title>Form Validation</title>

161
<link rel="stylesheet" href="[Link]" />

</head>

<body>

<h1>REGISTRATION FORM</h1>

<form name="RegForm" onsubmit="return validateForm()">

<p>

<label for="name">Name:</label>

<input type="text" id="name" name="Name"

placeholder="Enter your full name" />

<span id="name-error" class="error-message"></span>

</p>

<p>

<label for="address">Address:</label>

<input type="text" id="address" name="Address"

placeholder="Enter your address" />

<span id="address-error" class="error-message"></span>

</p>

<p>

<label for="email">E-mail Address:</label>

<input type="text" id="email" name="EMail"

placeholder="Enter your email" />

<span id="email-error" class="error-message"></span>

</p>

<p>

162
<label for="password">Password:</label>

<input type="password" id="password" name="Password" />

<span id="password-error" class="error-message"></span>

</p>

<p>

<label for="subject">Select Your Course:</label>

<select id="subject" name="Subject">

<option value="">

Select Course

</option>

<option value="BTECH">

BTECH

</option>

<option value="BBA">

BBA

</option>

<option value="BCA">

BCA

</option>

<option value="[Link]">

[Link]

</option>

</select>

<span id="subject-error" class="error-message"></span>

163
</p>

<p>

<label for="comment">College Name:</label>

<textarea id="comment" name="Comment"></textarea>

</p>

<p>

<input type="checkbox" id="agree" name="Agree" />

<label for="agree">I agree to the above

information</label>

<span id="agree-error" class="error-message"></span>

</p>

<p>

<input type="submit" value="Send" name="Submit" />

<input type="reset" value="Reset" name="Reset" />

</p>

</form>

<script src="[Link]"></script>

</body>

</html>

CSS:

body {

font-family: Arial, sans-serif;

background-color: #f5f5f5;

164
h1 {

text-align: center;

color: #333;

form {

max-width: 600px;

margin: 0 auto;

padding: 20px;

background-color: #fff;

border-radius: 8px;

box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);

input[type="text"],

input[type="password"],

select,

textarea {

width: 100%;

padding: 10px;

margin: 5px 0;

border: 1px solid #ccc;

border-radius: 5px;

box-sizing: border-box;

font-size: 16px;

165
select {

width: 100%;

padding: 10px;

margin: 5px 0;

border: 1px solid #ccc;

border-radius: 5px;

box-sizing: border-box;

font-size: 16px;

background-color: #fff;

appearance: none;

-webkit-appearance: none;

-moz-appearance: none;

textarea {

resize: vertical;

input[type="submit"],

input[type="reset"],

input[type="checkbox"] {

background-color: #007bff;

color: #fff;

border: none;

border-radius: 5px;

padding: 10px 20px;

166
cursor: pointer;

font-size: 16px;

input[type="submit"]:hover,

input[type="reset"]:hover,

input[type="checkbox"]:hover {

background-color: #0056b3;

.error-message {

color: red;

font-size: 14px;

margin-top: 5px;

JAVASCRIPT:

function validateForm() {

const name = [Link]("name").value;

const address = [Link]("address").value;

const email = [Link]("email").value;

const password = [Link]("password").value;

const subject = [Link]("subject").value;

const agree = [Link]("agree").checked;

const nameError = [Link]("name-error");

const addressError = [Link]("address-error");

const emailError = [Link]("email-error");

167
const passwordError = [Link]("password-error");

const subjectError = [Link]"subject-error");

const agreeError = [Link]("agree-error");

[Link] = "";

[Link] = "";

[Link] = "";

[Link] = "";

[Link] = "";

[Link] = "";

let isValid = true;

if (name === "" || /\d/.test(name)) {

[Link] =

"Please enter your name properly.";

isValid = false;

if (address === "") {

[Link] =

"Please enter your address.";

isValid = false;

if (email === "" || ![Link]("@")) {

[Link] =

"Please enter a valid email address.";

isValid = false;

168
}

if (password === "" || [Link] < 6) {

[Link] =

"Please enter a password with at least 6 characters.";

isValid = false;

if (subject === "") {

[Link] =

"Please select your course.";

isValid = false;

if (!agree) {

[Link] =

"Please agree to the above information.";

isValid = false;

return isValid;

169
Output:

Types of Form Validation

Client-side Validation:

This is done in the user’s browser before the form is submitted. It provides
quick feedback to the user, helping them fix errors without sending data to
the server first.

Server-side Validation:

Even though client-side validation is useful, it’s important to check the data
again on the server. This ensures that the data is correct, even if someone
tries to bypass the validation in the browser.

Various Use case

Below are the some use cases of Form Validation in JavaScript.

1.) Form validation using jQuery

Here, we have validated a simple form that consists of a username, password,


and a confirmed password using jQuery,

170
2.) Number validation in JavaScript

Sometimes the data entered into a text field needs to be in the right format
and must be of a particular type in order to effectively use the form. For
instance, Phone number, Roll number, etc are some details that must be in
digits not in the alphabet.

3.) Password Validation Form Using JavaScript

The password Validation form is used to check the password requirements


such as the password must have at least one Uppercase, or lowercase,
number, and the length of the password.

4.) How to validate confirm password using JavaScript?

You can validate a confirm password field using JavaScript by comparing it


with the original password field.

5.) JavaScript Program to Validate Password using Regular Expressions

A Regular Expression is a sequence of characters that forms a search pattern.


The search pattern can be used for text search and text to replace operations.
A regular expression can be a single character or a more complicated pattern.

4. JavaScript Object-Oriented Programming (OOP)

Object-Oriented Programming (OOP) is a programming paradigm that uses


"objects" to represent data and methods to manipulate that data. JavaScript
is a versatile language that supports OOP principles, allowing developers to
create modular, reusable, and maintainable code. Let's delve into the key
concepts of OOP in JavaScript, including examples to illustrate each concept.

4.1 Creating Classes and Objects

In Java, classes and objects are basic concepts of Object Oriented


Programming (OOPs) that are used to represent real-world concepts and
entities. The class represents a group of objects having similar properties and
behavior. For example, the animal type Dog is a class while a particular dog
named Tommy is an object of the Dog class.

171
Classes

A class in Java is a set of objects which shares common characteristics/


behavior and common properties/ attributes. It is a user-defined blueprint or
prototype from which objects are created. For example, Student is a class
while a particular student named Ravi is an object.

Properties of Java Classes

 Class is not a real-world entity. It is just a template or blueprint or


prototype from which objects are created.
 Class does not occupy memory.
 Class is a group of variables of different data types and a group of
methods.
 A Class in Java can contain:
o Data member
o Method
o Constructor
o Nested Class
o Interface

Class Declaration in Java

access_modifier class <class_name>

data member;

method;

constructor;

nested class;

interface;

172
Objects

An object in Java is a basic unit of Object-Oriented Programming and


represents real-life entities. Objects are the instances of a class that are
created to use the attributes and methods of a class. A typical Java program
creates many objects, which as you know, interact by invoking methods. An
object consists of:

1) State : It is represented by attributes of an object. It also reflects the


properties of an object.
2) Behavior : It is represented by the methods of an object. It also reflects
the response of an object with other objects.
3) Identity : It gives a unique name to an object and enables one object to
interact with other objects.

Example of an object: dog

Objects correspond to things found in the real world. For example, a graphics
program may have objects such as “circle”, “square”, and “menu”. An online
shopping system might have objects such as “shopping cart”, “customer”, and
“product”.

NOTE: When we create an object which is a non primitive data type, it’s
always allocated on the heap memory.

173
Declaring Objects (Also called instantiating a class)

When an object of a class is created, the class is said to be instantiated . All


the instances share the attributes and the behavior of the class. But the
values of those attributes, i.e. the state are unique for each object. A single
class may have any number of instances.

Example:

Difference between Java Class and Objects

The differences between class and object in Java are as follows:

Class Object
A class is the blueprint of an An object is an instance of the class.
object. It is used to create objects.
No memory is allocated when a Memory is allocated as soon as an
class is declared. object is created.
A class is a group of similar An object is a real-world entity such as
objects. a book, car, etc.
A class is a logical entity. An object is a physical entity.
A class can only be declared once. Objects can be created many times as
per requirement.

174
Example: A class can represent a Example: Objects of the class car can
car. be BMW, Mercedes, Ferrari, etc.

Encapsulation

Encapsulation is the practice of bundling the data (properties) and methods


(functions) that operate on the data into a single unit, or class. It restricts
direct access to some of the object's components, preventing accidental
interference and misuse of the data.

Example:

class BankAccount {

constructor(owner, balance) {

[Link] = owner;

this._balance = balance; // Private property convention

// Method to deposit money

deposit(amount) {

if (amount > 0) {

this._balance += amount;

[Link](`Deposited ${amount}. New balance: ${this._balance}`);

// Method to get the balance

getBalance() {

return this._balance;

175
}

let account = new BankAccount("Alice", 1000);

[Link](500); // Output: Deposited 500. New balance: 1500

[Link]([Link]()); // Output: 1500

Inheritance

Inheritance is a mechanism where a new class (subclass) inherits properties


and methods from an existing class (superclass). This promotes code reuse
and establishes a natural hierarchy between classes.

Example:

// Superclass

class Animal {

constructor(name) {

[Link] = name;

speak() {

[Link](`${[Link]} makes a sound.`);

// Subclass

class Dog extends Animal {

constructor(name, breed) {

super(name); // Call the superclass constructor

[Link] = breed;

176
}

speak() {

[Link](`${[Link]} barks.`);

let dog = new Dog("Rex", "Labrador");

[Link](); // Output: Rex barks.

Polymorphism

Polymorphism is the ability to process objects differently based on their data


type or class. It allows one interface to be used for a general class of actions.
In JavaScript, polymorphism is often achieved through method overriding and
interface implementation.

Example:

class Shape {

draw() {

[Link]("Drawing a shape.");

class Circle extends Shape {

draw() {

[Link]("Drawing a circle.");

class Square extends Shape {

177
draw() {

[Link]("Drawing a square.");

let shapes = [new Shape(), new Circle(), new Square()];

[Link](shape => {

[Link]();

});

// Output:

// Drawing a shape.

// Drawing a circle.

// Drawing a square.

Conclusion

JavaScript's support for Object-Oriented Programming (OOP) principles, such


as classes, objects, encapsulation, inheritance, and polymorphism, provides
a robust framework for building complex and maintainable applications.

--- UNIT- 5 COMPLETED ---

178

You might also like