0% found this document useful (0 votes)
57 views48 pages

Valid HTML5 Code and Structure Guide

The document provides an overview of HTML and XHTML, detailing their structure, syntax, and key elements. It explains how to create basic HTML programs, use headings, hyperlinks, images, forms, and lists, as well as the attributes associated with each. Additionally, it touches on tables and frames, highlighting their functions and examples in web development.
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)
57 views48 pages

Valid HTML5 Code and Structure Guide

The document provides an overview of HTML and XHTML, detailing their structure, syntax, and key elements. It explains how to create basic HTML programs, use headings, hyperlinks, images, forms, and lists, as well as the attributes associated with each. Additionally, it touches on tables and frames, highlighting their functions and examples in web development.
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

-: Explain in detail about HTML :-

-: Write about XHTML :-


HTML :
HTML stands for Hypertext Markup Language, which XHTML, which stands for Extensible Hypertext
is a markup language used to create and structure Markup Language, is a markup language that is a
content on the web. HTML provides a set of elements stricter and more structured version of HTML.
that define the structure of a web page and its XHTML follows the same basic syntax as HTML
content, such as headings, paragraphs, links, images, but adheres to XML rules and syntax.
forms, and more. * XHTML has several benefits over HTML,
* Steps to write a basic HTML program : including stricter syntax that enforces cleaner
(i) Open a text editor such as Notepad, Sublime Text, coding practices, improved accessibility, and
or Visual Studio Code. better compatibility with other web technologies.
(ii) Create a new file and save it with a .html XHTML documents can be parsed by XML
extension. parsers, which enables the use of XML tools such
(iii) Start the HTML document by typing <!DOCTYPE as XSLT, XPath, and XML Schema.
html> at the top of the file. This tells the browser that * To form a valid XHTML document, the following
the document is written in HTML5. rules must be followed :
(iv) Add the <html> element, which serves as the root (i) Start with a DOCTYPE declaration: A DOCTYPE
element of the document. Inside the <html> element, declaration is a statement that specifies the
you can add two other elements: the <head> element version of XHTML being used. The DOCTYPE
and the <body> element. declaration must be the first line of an XHTML
(v) Inside the <head> element, you can add metadata document.
such as the document title, description, and (ii) XHTML elements must be properly nested: All
keywords using the <title>, <meta>, and <link> elements in an XHTML document must be
elements, respectively. You can also include CSS properly nested. This means that each element
stylesheets and JavaScript files here. must be completely contained within another
(vi) Inside the <body> element, you can add the element and that no elements can overlap.
content of the web page using various HTML (iii) XHTML elements must be properly closed: All
elements such as headings (<h1> - <h6>), paragraphs XHTML elements must be properly closed. This
(<p>), lists (<ul>, <ol>, <li>), links (<a>), images means that every opening tag must have a
(<img>), forms (<form>, <input>, <button>), and more. corresponding closing tag.
(vii) Save the file and open it in a web browser to see (iv) XHTML element and attribute names are case
the result. sensitive: XHTML element and attribute names
HTML program : must be written in lowercase letters. However,
<!DOCTYPE html> values of attributes can be written in uppercase
<html> letters.
<head> (v) All XHTML documents must have a root
<title>My First Web Page</title> element: The root element is the top-level element
</head> in an XHTML document. It must contain all other
<body> elements in the document.
<h1>Welcome it's me Harshavardhan</h1> (vi) XHTML attributes must have values: All
<p>This is my first web page.</p> attributes in an XHTML document must have
</body> values.
</html> (vii) XHTML documents must be well-formed: A
* In this example, we have a basic HTML document well-formed XHTML document adheres to all of
that contains a heading, a paragraph, an unordered the above rules and is syntactically correct
list, and a link. The <title> element in the <head> according to XML rules.
section sets the title of the web page, which appears * By following these rules, we can create valid
in the browser tab. The <h1> element is used to XHTML documents that are compatible with XML
define the main heading of the page, and the <p> tools and offer several benefits over traditional
element is used to define a paragraph of text. The HTML documents.
<ul> element defines an unordered list, and each item
in the list is defined with the <li> element. Finally, the
<a> element is used to define a hyperlink to another
web page, and the href attribute specifies the URL of
the destination page.
-: Write about headings :-
-: What are hyperlinks? Explain about anchor tag :-
Headings in HTML are used to provide structure
Hyperlink :-
and hierarchy to the content on a web page.
Hyperlinks, or simply links, are clickable elements that
HTML provides six levels of headings, from the
take you from one webpage or document to another.
most important <h1> to the least important
They are used to connect different pages, websites or
<h6>. The importance of headings is conveyed
documents on the internet. Hyperlinks are often
through their size, with <h1> being the largest
indicated by underlined, differently colored or bold
and <h6> being the smallest.
text, or they can be images, buttons or other elements
that the user can click on.
-: Heading tags :-
Anchor Tag :
The HTML `<a>` tag, also known as the anchor tag, is
(a) <h1> : This is the most important heading
used to create hyperlinks. The `href` attribute of the
and is used for the main title of a web page.
`<a>` tag specifies the URL or destination of the
(b) <h2> : This heading is used for major
hyperlink.
sections within the web page.
example :
(c) <h3> : This heading is used for subsections
<a href="https://www.example.com">Click here to
within the major sections.
visit Example.com</a>
(d) <h4> : This heading is used for sub-
* In the above example, the text "Click here to visit
subsections within the subsections.
"Example.com" is the visible part of the link, and the
(e) <h5> : This heading is used for sub-sub-
URL "https://www.example.com" is the destination of
subsections within the sub-subsections.
the link. When the user clicks on the link, their browser
(f) <h6> : This is the least important heading and
will take them to the Example.com website.
is used for minor headings within the content.
Program :
Program :
<!DOCTYPE html>
<html>
<!DOCTYPE html>
<head>
<html>
<title>Hyperlink Anchor tag Example</title>
<head>
</head>
<title>Headings Example</title>
<body>
</head>
<h1>Welcome to my website</h1>
<body>
<p>Click the link below to visit Google:</p>
<h1>This is the Main Heading</h1>
<a href="https://www.google.com">Visit
<h2>This is a Major Section</h2>
Google</a>
<h3>This is a Subsection</h3>
</body>
<h4>This is a Sub-Subsection</h4>
</html>
<h5>This is a Sub-Sub-Subsection</h5>
<h6>This is a Minor Heading</h6>
Output :
</body>
Welcome to my website
</html>
Click the link below to visit Google
Vist Google
output :
* When we open this HTML file in a web browser, we
see the heading "Welcome to my website" and a
# This is the Main Heading
paragraph that says "Click the link below to visit
## This is a Major Section
Google:". The text "Visit Google" is a link, and when
### This is a Subsection
you click on it, the browser will take to Google website.
#### This is a Sub-Subsection
##### This is a Sub-Sub-Subsection
###### This is a Minor Heading
-: Explain about Images and supported
-: Write about forms Also explain about different
attributes in HTML :-
types of form controls :-
Images : it is often an observed fact that
images increase the visibility of web pages.
Forms are an essential element of user interaction
These images are stored in computer by
on the web. They allow users to input data and send
following formats are BMP, JPEG, GIF,
it to servers for processing. Forms are used for a
PMP,PNG etc.
wide range of purposes, such as logging into a
* HTML allows you to add images to your web
website, submitting a job application, or completing
pages using the `<img>` tag. This tag is an
an online survey.
empty tag, meaning that it doesn't need a
* A form typically contains one or more form controls
closing tag. Instead, you'll use attributes to
that allow users to enter or select data. Form
provide information about the image.
controls can be of different types, including text
* Here are some of the most commonly used
fields, checkboxes, radio buttons, drop-down lists,
attributes for the `<img>` tag:
and more. Each type of form control serves a
(1) src : This attribute specifies the URL of the
specific purpose and has its unique characteristics.
image you want to display.
* form controls :
(2) alt : This attribute provides alternative text
(i) Text fields : Text fields are used for entering text
for the image. This text is displayed if the image
data, such as names, addresses, or email addresses.
can't be loaded or if the user is using a screen
They can be of different types, such as single-line
reader.
text fields, multi-line text fields, or password fields.
(3) width : This attribute specifies the width of
(ii) Checkboxes : Checkboxes are used to allow
the image in pixels.
users to select one or more options from a list of
(4) height : This attribute specifies the height of
choices. They are often used for binary choices, such
the image in pixels.
as "yes" or "no" options.
* example to use these attributes to display an
(iii) Radio buttons : Radio buttons are similar to
image :
checkboxes, but users can only select one option
<html>
from a list of choices. They are often used when
<head>
there are multiple options, but users can only choose
<title> Displaying an Image</title>
one.
<img src="https://Google. com/images/
(iv) Drop-down lists : Drop-down lists are used to
gooogle" alt="image not found" width="300"
provide a list of options, and users can select one
height="300">
option from the list. They conserve space and can be
* In this example, we're using a google image to
used when there are many options.
display incase if google image was not loaded
(v) Buttons : Buttons are used to submit the form,
the text will be shown as "image not found"
reset the form, or perform other actions. Submit
Output :
buttons are used to send the data to the server, while
__________
reset buttons clear the form data.
| Google |
(vi) Hidden fields : Hidden fields are used to store
|_________|
data that is not visible to users. They are often used
to store session IDs or other data that needs to be
If Image was not loaded :
passed to the server.
* In addition to these form controls, there are other
__________
advanced form controls, such as file upload controls,
| iimage |
date pickers, and range sliders. These controls offer
| not |
more advanced functionality and can help make the
| Found |
form more user-friendly and easier to use.
|_________|
* Overall, forms and form controls are essential
elements of web design, and understanding how to
use them effectively can help improve user
experience and increase the likelihood of successful
form submissions.
-: Define List. What are the different types of lists * `<ul>` tag is used to indicate the start of the
in html ? Explain how these lists are created in unordered list. Each item in the list is contained
HTML with suitable Example :- within an `<li>` tag. The result of the above code
will be a bulleted list with three items.
List : (3) Definition list (DL) : A definition list is a list of
In HTML, a list is a collection of items that are terms and their definitions. Each term is defined
organized in a specific order. Lists are used to by its corresponding definition.
present information in an organized and structured * Program :
manner. <html>
* There are three types of lists in HTML : <head>
(1) Ordered List(ol) <title> Theory</title>
(2) Unordered List(ul) </head>
(3) Defination List (dl) <body>
(1) Ordered list (OL) : An ordered list is a numbered <dl>
list of items. The items in the list are numbered <dt>Theory 1</dt>
sequentially. <dd>Definition 1</dd>
Program : <dt>Theory 2</dt>
<html> <dd>Definition 2</dd>
<head> <dt>Theory 3</dt>
<title> Items </title> <dd>Definition 3</dd>
</head> </dl>
<body> </body>
<ol> </html>
<li>First item</li> output :
<li>Second item</li> Theory 1
<li>Third item</li> Definition 1
</ol> Theory 2
</body> Definition 2
</html> Theory 3
output : Definition 3
1 First item * In this example, the `<dl>` tag is used to indicate
2 Second item the start of the definition list. Each term is
3 third item contained within a `<dt>` tag and each definition is
* `<ol>` tag is used to indicate the start of the contained within a `<dd>` tag. The result of the
ordered list. Each item in the list is contained within above code will be a list of three terms and their
an `<li>` tag. The result of the above code will be a corresponding definitions.
numbered list with three items.
(2) Unordered list (UL) : An unordered list is a
bulleted list of items. The items in the list are
preceded by a bullet.
Program :
<html>
<head>
<title> Fruits </title>
</head>
<body>
<ul>
<li>Orange</li>
<li>Apple</li>
<li>Grapes</li>
</ul>
</body>
</html>
output :
. Orange
. Apple
. Grapes
What is Table? Explain the attribute of <table> in
HTML -: what is frame? Explain working of the frames with
examples :-
In HTML, a table is a markup element that displays
data in a tabular format. It is defined using the In the context of web development, a frame is an
`<table>` tag, and the content is placed within rows HTML element that allows the content of a webpage
and cells using the `<tr>` and `<td>` tags to be divided into separate areas, each of which can
respectively. display a different webpage or part of a webpage.
Here are some of the attributes that can be used Frames were commonly used in the early days of the
with the `<table>` tag : web, but they are now considered outdated and are
(i) border : Specifies the width of the border rarely used.
around the table cells. * Frames work by dividing the web page into separate
(ii) cellpadding : Specifies the amount of space sections or panes. Each pane contains its own HTML
between the cell content and the cell border. document, which can be loaded from a different
(iii) cellspacing : Specifies the amount of space source than the main document. The frames are
between cells. defined in the HTML code using the <frame> or
(iv) width : Specifies the width of the table. <iframe> tag.
(v) height : Specifies the height of the table. * For example, the following HTML code defines a
Example program that demonstrates how to page with two frames :
create a simple table with three rows and three <html>
columns : <head>
<!DOCTYPE html><html><head> <title>Table <title>Example Page</title>
Example</title></head><body> <table </head>
border="1" cellpadding="5" cellspacing="0" <frameset cols="25%,75%">
width="400"> <frame src="menu.html" name="menu">
<tr> <frame src="content.html" name="content">
<th>: NAME :</th> </frameset>
<th>: COURSE :</th> </html>
<th>: ROLLNO :</th> * In this example, the <frameset> element defines the
</tr> layout of the frames, specifying that there should be
<tr> two frames side by side with widths of 25% and 75%,
<td>k.Harshavardhan</td> respectively. The <frame> elements define the content
<td>BSC</td> of each frame, with the "src" attribute specifying the
<td>018</td> source HTML document to be loaded into each frame.
</tr> * When the user loads this page, the browser will
<tr> display the two frames side by side. The left frame will
<td>N.Kiran Kumar</td> display the "menu.html" document, while the right
<td>B.COM</td> frame will display the "content.html" document. Each
<td>023</td> frame can be addressed using its assigned name (in
</tr> this case, "menu" and "content"), allowing links and
</table> other elements in one frame to interact with content in
</body> the other frame.
</html> * Frames can be useful for creating certain types of
Output : layouts, such as a navigation menu that stays fixed in
------------------------------------------------------- one frame while the main content changes in another.
| : NAME : | : COURSE : |: ROLLNO :| However, frames can also cause issues with search
|K.Harshavardhan | BSC | 018 | engines, bookmarking, and accessibility, and are
|N.Kiran Kumar | B.Com | 023 | generally not recommended for modern web
development.
* In this program, we have used the `<table>` tag to
create the table, and specified the attributes
`border="1"`, `cellpadding="5"`, `cellspacing="0"`,
and `width="400"` to define the appearance of the
table. We have also used the `<tr>` tag to define
the rows, and the `<td>` tag to define the cells
within each row. The content of each cell is simply
some text that indicates its position in the table.
-: what are different types of form controls in -: What is cascading style sheet (Css) ? Explain the
xhtml :- types of css :-

XHTML, or eXtensible HyperText Markup Cascading Style Sheets (CSS) is a styling language used
Language, supports a variety of form controls to describe the presentation of a document written in
that allow users to enter data or make selections. markup languages such as HTML or XML. It allows you
form controls in XHTML : to control the layout, colors, fonts, and other visual
(1) Text input : A text input control allows users aspects of your web page.
to enter text, such as their name or email address, There are three types of CSS :
into a form field. (1) Inline CSS : This type of CSS is used to style
(2) Password input : A password input control is individual HTML elements using the style attribute. The
similar to a text input, but the characters entered styles defined in the style attribute are applied only to the
are obscured, making it useful for password element in which it is used.
fields. Example :
(3) Checkbox : A checkbox control allows users <p style="color: red; font-size: 18px;">This is a
to select one or more options from a list of paragraph</p>
choices. (2) Internal CSS : This type of CSS is used to define
(4) Radio buttons : Radio buttons are similar to styles for an entire HTML page in the head section of the
checkboxes, but only one option can be selected document. The styles defined in the head section are
from a list. applied to all elements in the HTML document. Example :
(5) Select dropdown : A select dropdown control <head>
displays a list of options from which users can <style>
choose one. p{
(6) Textarea : A textarea control allows users to color: red;
enter multiple lines of text, such as a message or font-size: 18px;
comment. }
(7) Button : A button control can be used to </style>
submit a form or trigger an action. </head>
(8) Hidden input : A hidden input control is used (3) External CSS : This type of CSS is used to define
to store data that is not displayed to the user, styles in an external file with a .css extension. The
such as a session ID. external CSS file is linked to the HTML document using
* These are some of the most common form the link tag. The styles defined in the external file are
controls in XHTML, but there are others as well, applied to all elements in the HTML document that are
such as file upload controls, image buttons, and associated with the CSS selectors.
more. Example :
<head>
<link rel="stylesheet" type="text/css"
href="style.css">
</head>
* Overall, using CSS, we can separate the presentation of
website from its content, making it easier to maintain and
update the website's design.
Advantages of css :

* CSS separates the presentation of a website from its


content. This makes it easier to update the layout and
design of the website without having to modify the HTML
markup.
* CSS files are cached by web browsers, which means that
subsequent page views will load faster.
* CSS allows for easy maintenance of website's design's
* CSS allows web developers to create websites that are
optimized for different devices such as desktops, tablets,
and smartphones.
-: Write the Css rule for controlling the positioning
-: Special Characters and horizontal rule :-
of elements in XHTML document :-
Special Characters in HTML :
CSS is used to control the presentation and layout
Special characters, also known as escape
of HTML or XHTML documents. Here are some
characters or entities, are used in HTML to
examples of CSS rules that can be used to control
display characters that are not normally
the positioning of elements in an XHTML
supported by the standard character set. For
document:
example, if you want to include a copyright
(1) Positioning an element absolutely :
symbol (©) in your HTML document, you can
To position an element absolutely, you can use the
use the special character entity `&copy;`
"position" property set to "absolute". You can then
instead of the actual symbol itself.
use the "top", "bottom", "left", and "right" properties
Some common special characters and their
to position the element relative to its closest
corresponding entity codes in HTML are:
positioned ancestor.
(i) &lt; for the less-than sign (<)
Example :
(ii) &gt; for the greater-than sign (>)
.element {
(iii) &amp; for the ampersand (&)
position: absolute;
(iv) &quot; for the double quote (")
top: 20px;
(v) &apos; for the single quote (')
left: 50px;
(vi) &copy; for the copyright symbol (©)
}
(vii) &reg; for the registered trademark symbol
(2) Positioning an element relatively :
(®)
To position an element relatively, you can use the
(viii) &trade; for the trademark symbol (™)
"position" property set to "relative". You can then
(ix) &nbsp; for a non-breaking space
use the "top", "bottom", "left", and "right" properties
Horizontal Rule in HTML :
to offset the element from its normal position.
A horizontal rule, or "hr" for short, is a
Example :
horizontal line that is used to separate content
.element {
in an HTML document. It can be used to break
position: relative;
up paragraphs, sections, or other blocks of
top: 10px;
content to make the page more readable and
left: 20px;
organized.
}
* To create an hr in HTML, we can use the
(3) Positioning an element fixed :
`<hr>` tag. This tag does not require a closing
To position an element fixed, you can use the
tag and can be used by itself.
"position" property set to "fixed". You can then use
For example, the following code will create a
the "top", "bottom", "left", and "right" properties to
horizontal line that spans the width of the
position the element relative to the viewport.
page : <hr>
Example :
we can also use attributes with the `<hr>` tag
.element {
to customize its appearance. Some of the
position: fixed;
commonly used attributes include:
top: 0;
(i) `size`: sets the height of the line
left: 0;
(ii) `color`: sets the color of the line
}
(iii) `width`: sets the width of the line
(4) Positioning an element statically :
For example, the following code will create a
To position an element statically, you can use the
horizontal line that is 2 pixels thick, red in color,
"position" property set to "static". This is the
and spans only half the width of the page :
default value, and it means that the element will
<html>
flow in the normal document flow.
<head>
Example :
<title>horizontal hr test</title>
.element {
</head>
position: static;
<body>
}
<hr size="2" color="red" width="50%">
* These are just a few examples of the CSS rules
</body>
that can be used to control the positioning of
</html>
elements in an XHTML document. There are many
other properties and values that can be used to
achieve different layouts and effects.
-: Explain BOX Model :-
This is the content area.
box model is a concept that defines how HTML </div>
elements are structured visually, including their (2) Padding Area : The padding area is the space
dimensions, padding, borders, and margins. Every between the content area and the border. It is used
HTML element is represented as a rectangular box, to add space or cushioning around the content. Its
and the box model describes the properties of this size is determined by the padding property.
box. Example :
(a) Block level box : <div style="width: 200px; height: 100px;
Block-level elements are those that create a background-color: red; padding: 20px;">
rectangular box that takes up the full width of their This is the content area with padding.
parent container, and typically cause a new line to be </div>
created after the element. Examples of block-level (3) Border Area : The border area is the space
elements include <div>, <p>, <h1>-<h6>, <ul>, <ol>, and between the padding area and the margin. It is
<li>. used to create a visible boundary around the
* The block-level box model consists of four parts: content. Its size is determined by the border
content, padding, border, and margin. The content is property.
the actual text or images within the box. Padding is the Example :
space between the content and the border. The border <div style="width: 200px; height: 100px;
is a line that surrounds the padding and content, and background-color: red; padding: 20px; border: 2px
the margin is the space between the border and the solid black;">
next element on the page. This is the content area with padding and a
* Example of a block-level element with a box model : border.
<div style="border: 1px solid black; padding: 10px; </div>
margin: 10px;"> (4) Margin Area : The margin area is the space
This is a block-level element with a box model. outside the border and is used to create space
</div> between elements. Its size is determined by the
(b) Inline box : margin property.
Inline elements are those that do not create a new line Example :
after the element, and typically only take up as much <div style="width: 200px; height: 100px;
width as their content. Examples of inline elements background-color: red; padding: 20px; border: 2px
include <a>, <span>, <strong>, and <em>. solid black; margin: 10px;">
* The inline box model only consists of two parts: This is the content area with padding, a border,
content and padding. Borders and margins cannot be and a margin.
applied to inline elements. </div>
* Example of inline element with a box model : * In summary, the Box Model is used to control the
<span style="background-color: yellow; padding: size and spacing of HTML elements on a web
5px;"> page. By adjusting the properties of each
This is an inline element with a box model. component, developers can create visually
</span> appealing and well-structured web pages.
* In this example, the background color and padding
are applied to the content of the <span> element,
which is only as wide as the text it contains.
* The Box Model is a concept in web design and
development that describes how HTML elements are
visually represented on a web page. It consists of four
main components :
the (1) content area, (2) padding area, (3) border area,
and (4) margin area.

(1) Content Area : The content area is the innermost


part of the box and contains the actual content of the
HTML element, such as text, images, or videos. Its size
is determined by the width and height properties of the
element.
Example :
<div style="width: 200px; height: 100px; background-
color: red;">
-: Explain about text flow model :-

Text Flow : Example :


Text flow model is used to apply visual effects <html>
around the selected text area. Text effects <head>
have the following properties : <title>word-wrap testing</title>
(a) Text overflow <style>
(b) Word-wrap p{
(c) Word-break width: 200px;
(a) Text overflow : Text overflow occurs when word-wrap: break-word;
the content within a container overflows its }
boundaries. In other words, if the content of a </style>
block-level element extends beyond its width </head>
or height, it will overflow the container. In <body>
HTML and CSS, you can use the `overflow` <p>Harsha is a computer specialist</p>
property to control what happens when this </body>
occurs. There are four possible values for the </html>
`overflow` property : Output : Harsha is a computer specialist
* visible : The default value, which allows the (3) Word-break : Word-break is a CSS property that
content to overflow the container. controls how words are broken and wrapped when they
* hidden : Hides any overflow that occurs. exceed the width of a container. By default, words will
* scroll : Adds a scrollbar to the container so break only at spaces, hyphens, or other specified break
that the user can scroll to view the overflow. points. The `word-break` property allows you to control
* auto : Adds a scrollbar only when necessary. how words break, even when there are no spaces or
Syntax : hyphens present.
p{ Syntax :
overflow: visible|hidden|scroll|auto; p{
} word-break: keep-all;
Example : }
<html> Example :
<head> <html>
<title>text overflow test</title> <head>
<style> <title>word-break testing</title>
p{ <style>
width: 200px; p{
overflow: hidden; width: 200px;
} word-break: keep-all;
</style> }
</head> </style>
<body> </head>
<p>Harsha is computer scientist</p> <body>
</body> <p>Harsha is a Front-end Devloper and freelancer</p>
</html> </body>
Output : Harsha is a computer scientist </html>
(2) Word-wrap : Word-wrap is a CSS property Output : Harsha is a Front-end Devloper and freelancer
that controls whether long words can be * In the context of the text flow model, these CSS
broken and wrapped onto the next line in a properties can be used to control the layout and display
block-level element. By default, long words will of text within a container, ensuring that the text is
not break and will instead overflow the readable and comprehensible to readers.
container. The `word-wrap` property allows you
to force long words to break and wrap onto the
next line, preventing text overflow.
Syntax :
p{
word-wrap: break-word;
}
-: Discuss about building/creating a CSS drop-down (2) Style the basic menu : Add some basic styling
menu :- to the menu, such as removing the default list
styles and adding padding and a background
(1) Create the HTML structure : Start by creating an color.
unordered list (ul) with list items (li) for each item in css :
your menu. For the items that have sub-menus, you can nav ul {
add another unordered list inside the parent list item. list-style: none;
<html> padding: 0;
<head> background-color: #f1f1f1;
<title>dropp-down menu test</title> }
<style type="text/css"> nav li {
nav ul { display: inline-block;
list-style: none; position: relative;
padding: 0; }
background-color: #f1f1f1; nav a {
} display: block;
nav li { padding: 10px;
display: inline-block; color: #333;
position: relative; text-decoration: none;
} }
nav a { (3) Hide the sub-menus : To hide the sub-menus,
display: block; set the display property to none.
padding: 10px; nav ul ul {
color: #333; display: none;
text-decoration: none; }
} (4) Show the sub-menus on hover : To show the
nav ul ul { sub-menus when the parent item is hovered over,
display: none; use the :hover pseudo-class.
} nav li:hover > ul {
nav li:hover > ul { display: block;
display: block; }
} (5) Position the sub-menus : To position the sub-
nav ul ul { menus below the parent item, use the position
position: absolute; property.
top: 100%; nav ul ul {
left: 0; position: absolute;
} top: 100%;
nav ul ul { left: 0;
background-color: #fff; }
border: 1px solid #ccc; (6) Style the sub-menus : Finally, add some styling
} to the sub-menus, such as a different background
</style> color and border.
<nav> nav ul ul {
<ul> background-color: #fff;
<li><a href="#">Home</a></li> border: 1px solid #ccc;
<li> }
<a href="#">About Us</a> And that's it! With these basic steps, we can create
<ul> functional CSS drop-down menu.
<li><a href="#">Our Story</a></li>
<li><a href="#">Meet the Team</a></li>
</ul>
</li>
<li><a href="#">Services</a></li>
<li><a href="#">Contact Us</a></li>
</ul>
</nav>
</html>
-: Discuss in detail about Javascript :-
(5) Rich functionality : JavaScript provides rich
Javascript : functionality for developing web applications,
JavaScript is a high-level, dynamic, and interpreted including event handling, DOM manipulation,
programming language. It is commonly used for animations, and form validation.
creating dynamic and interactive web pages, as Disadvantages of JavaScript :-
well as for developing complex web applications (1) Security : JavaScript can be vulnerable to
and games security threats such as cross-site scripting (XSS)
program : attacks, which can compromise the security of
<html> web applications.
<head> (2) Browser compatibility : Different browsers may
<title>Finding Even or Odd Numbers using js</title> interpret JavaScript code differently, which can
</head> lead to compatibility issues.
<body> (3) Limited performance : JavaScript is an
<script language = "JAVASCRIPT"> interpreted language, which can lead to slower
var n; performance compared to compiled languages.
n=parseInt(window.promot("Enter the value")); (4) Lack of static typing : JavaScript is a
if (n%2 == 0) dynamically typed language, which can make it
{ more difficult to catch errors during development.
document.writeIn("<h2>The given value is even</ Features of JavaScript :-
h2>"); (1) Object-oriented programming (OOP) :
} JavaScript supports OOP concepts such as
else inheritance, encapsulation, and polymorphism.
{ (2) Dynamic typing : JavaScript is a dynamically
document.writeIn("<h2>The given value is odd</ typed language, which means that variable types
h2>); are determined at runtime.
} (3) First-class functions : Functions are first-class
</script> citizens in JavaScript, which means that they can
</body> be assigned to variables, passed as arguments to
</html> other functions, and returned as values from
output : functions.
|------------------------| (4) Prototype-based inheritance : JavaScript uses
| | prototype-based inheritance, which allows objects
| Enter the value | to inherit properties and methods from other
| _________________ | objects.
| |___2____________| | (5) Asynchronous programming : JavaScript
| OK cancel | supports asynchronous programming using
| | callbacks, promises, and async/await, which
|_____________________| allows for non-blocking I/O and better
it is a even number performance in web applications.

Advantages of JavaScript :-
(1) Easy to learn : JavaScript has a syntax similar
to other popular programming languages, making it
easy to learn and understand.
(2) Client-side scripting : JavaScript is executed on
the client-side, which means that it can be used to
create dynamic and interactive web pages without
the need for server-side processing.
(3) Large developer community : JavaScript has a
large and active developer community that provides
support, resources, and libraries for developers.
(4) Cross-platform compatibility : JavaScript is
compatible with all major web browsers and
operating systems, making it a versatile language
for web development.
-: Discuss in detail about prompt dialog box,
alert dialog box :- In JavaScript, an alert box can be created using the
`alert()` method. Here is an example program that uses
* Prompt Dialog Box : an alert box to display a message to the user:
A prompt dialog box is a graphical user Syntax :
interface element used to obtain input from the alert("Welcome to our website.");
user. It is commonly used to ask the user for Example Program :
input in order to proceed with an action, such as <html>
confirming a deletion or entering data. A prompt <head>
dialog box displays a message to the user along <title>Alert Box Example</title>
with an input field where the user can enter their </head>
response. The response is then used by the <body>
program to proceed with the action. <script>
* In JavaScript, a prompt dialog box can be alert("Welcome to our website.");
created using the `prompt()` method. Here is an </script>
example program that uses a prompt dialog box </body>
to obtain the user's name and then displays a </html>
personalized greeting : Output :
Syntax : When the program is executed in a browser, an alert
let name = prompt("What is your name?"); box will be displayed with the message "Welcome to
alert("Hello, " + name + "! Welcome to our our website.". The user can click the "OK" button to
website."); dismiss the alert box.
Example Program : * In this example, the `alert()` method is used to display
<html> a message to the user when they visit the website. The
<head> message is displayed in an alert box with an "OK"
<title>Prompt Dialog Box Example</title> button that the user can click to dismiss the message.
</head> * Overall, prompt dialog boxes and alert boxes are both
<body> important graphical user interface elements used to
<script> obtain input from the user or display messages to the
let name = prompt("What is your name?"); user in a program.
alert("Hello, " + name + "! Welcome to our
website.");
</script>
</body>
</html>
output :
When the program is executed in a browser, a
prompt dialog box will be displayed asking the
user for their name. If the user enters "John", for
example, then the output will be an alert box
with the message "Hello, John! Welcome to our
website.".
* In this example, the `prompt()` method is used
to display a message to the user asking for their
name. The user's response is then stored in the
`name` variable. The `alert()` method is then
used to display a personalized greeting to the
user.
* Alert Box :
An alert box is a graphical user interface
element used to display a message to the user.
It is commonly used to provide information to
the user or to notify the user of an error. An alert
box displays a message to the user along with
an "OK" button that the user can click to dismiss
the message.
-: Explain the memory concept in javascript with
-: What is data type, Explain various data types
an example program :-
available in javascript :-
In JavaScript, memory refers to the space
allocated by the computer to store the values of
DataType :
variables and objects used in a program. The
A data type is a classification of the type of data that
memory is dynamically allocated as the program
a variable or constant can hold in a programming
runs, and it is automatically managed by the
language. In JavaScript, there are several data types
JavaScript engine.
that are used to define the nature and behavior of
* example program that demonstrates the
data, and how they can be stored, processed, and
memory concept in JavaScript :
manipulated in a program.
<html>
* The various data types available in JavaScript :
<head>
(1) Primitive data types : These are the basic data
<title>Javascript Memory Concept</title>
types that are not objects and have a fixed size in
</head>
memory. There are six primitive data types in
<body>
JavaScript:
<script type = "text/javascript">
(i) Boolean : A true or false value.
let x = 10;
(ii) Null : A value that represents the absence of any
let y = "Hello";
object value.
let z = {name: "Harsha", age: 21};
(iii) Undefined : A value that represents an
uninitialized or non-existent value.
function printValues() {
(iv) Number : A numeric value, including integers and
console.log(x);
floating-point numbers.
console.log(y);
(v) String : A sequence of characters enclosed in
console.log(z.name);
quotation marks.
}
(vi) Symbol : A unique and immutable value that may
printValues();
be used as the key of an object property.
</script>
(2) Object data type : This data type is used to store
</body>
complex data structures, including arrays, functions,
<html>
and objects. Objects are a collection of key-value
output :-
pairs, where each key is a string (or symbol) and
10
each value can be of any data type, including other
Hello
objects.
Harsha
(3) Special data types : There are two special data
* In this program, we declare three variables: `x`,
types in JavaScript :
`y`, and `z`.
(i) NaN : A value representing an invalid number,
* The first variable `x` is assigned a value of `10`,
typically the result of a mathematical operation that
which is a number. The second variable `y` is
cannot be performed.
assigned a value of `"Hello"`, which is a string. The
(ii) Infinity : A value representing positive infinity.
third variable `z` is assigned an object with two
properties: `name` and `age`.
* In JavaScript, data types are dynamically assigned,
* Then, we define a function called `printValues`
meaning that the data type of a variable can change
that logs the values of the three variables to the
at runtime. For example, a variable that was
console.
previously holding a number can be assigned a string
* When we call the `printValues` function, the
value. This dynamic typing feature of JavaScript
JavaScript engine allocates memory to store the
makes it flexible, but it also requires careful attention
values of `x`, `y`, and `z`. The values are stored in
to type handling to avoid unexpected behavior in a
different memory locations depending on their
program.
data types. For example, the number `10` is stored
in a different memory location than the string
`"Hello"`.
* The `printValues` function accesses the memory
locations where the values of `x`, `y`, and `z` are
stored and logs them to the console.
* Once the function finishes executing, the memory
allocated to store the values of `x`, `y`, and `z` is
automatically released by the JavaScript engine,
which ensures efficient memory management.
-: Java Script Operators :- -: OPERATORS (1) :- document.write(linebreak);
document.write("a*b="+(a*b));
Operator : In JavaScript, an operator is a special document.write(linebreak);
symbol or keyword used to perform various types of document.write("a/b="+(a/b));
operations on values or variables. There are several document.write(linebreak);
types of operators in JavaScript, including arithmetic document.write("a%b="+(a%b));
operators, comparison operators, logical operators, document.write(linebreak);
bitwise operators, assignment operators, and more. document.write("++a="+(++a));
Types of Operators : document.write(linebreak);
(1) Arithmetic operators : document.write("a++="+(a++));
arithmetic operators are used to perform document.write(linebreak);
mathematical operations on values. The most document.write("--b="+(--b));
common arithmetic operators are addition, document.write(linebreak);
subtraction, multiplication, division, and modulus. document.write("b--="+(b--));
(i) Addition (+) : Used to add two or more numbers, or document.write(linebreak);
to concatenate strings. </script>
Example : </body>
var sum = 66+4; //result will be 70 </html>
(ii) Subtraction (-) : Used to subtract one number output :
from another. a+b=9
Example : a-b=1
result = 70-4; //result will be 66 a*b=20
(iii) Multiplication (*) : Used to multiply two or more a/b=1.25
numbers. a%b=1
Example : ++a=6
result = 2*2; //result will be 4 a++=6
(iv) Division (/) : Used to divide one number by --b=3
another. b--=3
Example :
result = 10/2; //result will be 5
(v) Modulus (%) : Used to get the remainder of a
division operation.
Example :
result = 5%2; //result will be 1
(vi) Increment and decrement operators : Used to
increase or decrease the value of a variable by 1.
Example :
let a = 5;
a++; // equivalent to a = a + 1;
console.log(a); // output: 6
let b = 10;
b--; // equivalent to b = b - 1;
console.log(b); // output: 9
program :
<html>
<head>
<title>Arithmetic operators test</title>
</head>
<body>
<script>
var a=5;
var b=4;
var linebreak = "<br>";
document.write("a+b="+(a+b));
document.write(linebreak);
document.write("a-b="+(a-b));
-: Operators (2) :-
(2) Assignment operators : document.write(result);
In JavaScript, assignment operators are used to assign document.write(linebreak);
values to variables. There are several types of assignment document.write("Value of a =>(a+=b)=>");
operators in JavaScript, which include: result = (a+=b);
(i) The equal sign (=) operator : This is the simplest document.write(result);
assignment operator and is used to assign a value to a document.write(linebreak);
variable. document.write("Value of a =>(a-=b)=>");
Example : result = (a-=b);
let x = 5; document.write(result);
(ii) The addition assignment (+=) operator : This operator is document.write(linebreak);
used to add a value to a variable and then assign the result document.write("Value of a =>(a*=b)=>");
to the variable. result = (a*=b);
Example : document.write(result);
let x = 5; document.write(linebreak);
x += 3; // equivalent to x = x + 3 document.write("Value of a =>(a/=b)=>");
console.log(x); // output: 8 result = (a/=b);
(iii) The subtraction assignment (-=) operator : This document.write(result);
operator is used to subtract a value from a variable and then document.write(linebreak);
assign the result to the variable. document.write("Value of a =>(a%=b)=>");
Example : result = (a%=b);
let x = 5; document.write(result);
x -= 3; // equivalent to x = x - 3 document.write(linebreak);
console.log(x); // output: 2 </script>
(iv) The multiplication assignment (*=) operator : This </html>
operator is used to multiply a variable by a value and then output :
assign the result to the variable. Value of a => (a = b) => 12
Example : Value of a => (a += b) => 24
let x = 5; Value of a => (a -= b) => 12
x *= 3; // equivalent to x = x * 3 Value of a => (a *= b) => 144
console.log(x); // output: 15 Value of a => (a /= b) => 12
(v) The division assignment (/=) operator : This operator is Value of a => (a %= b) => 0
used to divide a variable by a value and then assign the * Assignment operators are very useful in
result to the variable. JavaScript because they allow us to modify
Example : the value of a variable without having to create
let x = 15; a new variable or write a longer statement.
x /= 3; // equivalent to x = x / 3
console.log(x); // output: 5
(vi) The modulus assignment (%=) operator : This operator
is used to find the remainder of a variable divided by a value
and then assign the result to the variable.
Example :
let x = 15;
x %= 4; // equivalent to x = x % 4
console.log(x); // output: 3
program :
<html>
<head>
<title>Assignment operators test</title>
</head>
<body>
<script type="text/javascript">
var a = 15;
var b = 12;
var linebreak = "<br>";
document.write("Value of a =>(a=b)=>");
result = (a=b);
(3) Comparison Operators :
-: Operators (3) :-
Comparison operators are used to compare two values
or variables in JavaScript and return a Boolean value var a = 7;
(true or false) based on the comparison result. There are var b = 25;
six comparison operators in JavaScript: var linebreak = "<br>"; document.write("(a ==
(i) Equal to (==) operator : This operator compares two b) =>"); result = (a == b);
values and returns true if they are equal. document.write(result);
Example : document.write(linebreak);
2 == 2 // returns true document.write("(a < b) =>"); result = (a < b);
2 == '2' // returns true (type coercion) document.write(result);
2 == 3 // returns false document.write(linebreak);
* The double equal to (==) operator performs type document.write("(a > b) =>"); result = (a > b);
coercion, which means that it converts the operands to a document.write(result);
common type before comparing them. document.write(linebreak);
(ii) Not equal to (!=) operator : This operator compares document.write("(a != b) =>"); result = (a != b);
two values and returns true if they are not equal. document.write(result);
Example : document.write(linebreak);
2 != 3 // returns true document.write("(a >= b) =>"); result = (a >=
2 != '2' // returns false (type coercion) b);
(iii) Strict equal to (===) operator : This operator document.write(result);
compares two values and returns true if they are equal document.write(linebreak);
and of the same type. document.write("(a <= b) =>"); result = (a <=
Example : b);
2 === 2 // returns true document.write(result);
2 === '2' // returns false document.write(linebreak); </script>
* The triple equal to (===) operator does not perform </body>
type coercion, which means that it compares the </html>
operands based on their type and value. output :
(iv) Strict not equal to (!==) operator : This operator (a == b) => false
compares two values and returns true if they are not (a < b) => true
equal or of different types. (a > b) => false
Example : (a != b) => true
2 !== '2' // returns true (a >= b) => false
2 !== 2 // returns false (a <= b) => true
(v) Greater than (>) operator : This operator compares
two values and returns true if the first value is greater
than the second value.
Example :
3 > 2 // returns true
2 > 3 // returns false
(vi) Less than (<) operator : This operator compares two
values and returns true if the first value is less than the
second value.
Example :
2 < 3 // returns true
3 < 2 // returns false
* These comparison operators are useful in conditional
statements and loops to control the flow of execution
based on certain conditions.
program :
<html>
<head>
<title>Comparison operators test</title>
</head>
<body>
<script type="text/javascript">
-: Operators (4) :-
(4) Logical/Boolean and Relational operators :

Logical operators are used to combine multiple conditions and evaluate them as a single
Boolean value. There are three logical operators in JavaScript: `&&` (AND), `||` (OR), and `!`
(NOT).
Examples :
let x = 5;
let y = 10;
let z = 15;
// Using the AND operator
if (x < y && y < z) {
console.log("x is less than y and y is less than z");
}
// Using the OR operator
if (x > y || y > z) {
console.log("Either x is greater than y or y is greater than z");
}
// Using the NOT operator
if (!(x == y)) {
console.log("x is not equal to y");
}
* In the above example, the `&&` operator is used to check if `x` is less than `y` and `y` is
less than `z`. If both conditions are true, the `console.log()` statement will be executed.
* The `||` operator is used to check if either `x` is greater than `y` or `y` is greater than `z`. If
either condition is true, the `console.log()` statement will be executed.
* The `!` operator is used to negate a condition. In the example, the `if` statement checks
if `x` is equal to `y`. If the condition is false, the `console.log()` statement will be executed
because the `!` operator negates the condition.
program :
<html>
<head>
<title>Logical operators test</title>
</head>
<body>
<script type="text/javascript">
var a = true;
var b = false;
var linebreak = "<br>";
document.write("(a && b) =>");
result = (a && b);
document.wriite(result);
document.write(linebreak);
document.write("(a || b) =>");
result = (a || b);
document.wriite(result);
document.write(linebreak);
document.write("!(a && b) =>");
result = (!(a && b));
document.wriite(result);
document.write(linebreak);
</script>
</body>
</html>
(5) Relational operators : -: Operators (5) :- var value7 = "hello";
Relational operators in JavaScript are used to var value8 = "hello";
compare two values and return a Boolean result (true document.write(value7 + " != " + value8 + ": " +
or false) based on the comparison. There are six (value7 != value8) + "<br>");
relational operators in JavaScript: // Strictly equal to (===)
(i) Equal to (==) : This operator compares two values var value9 = 5;
and returns true if they are equal. var value10 = 5;
Example : document.write(value9 + " === " + value10 + ": " +
5 == 5 // true (value9 === value10) + "<br>");
'hello' == 'world' // false var value11 = 5;
(ii) Not equal to (!=) : This operator compares two var value12 = "5";
values and returns true if they are not equal. document.write(value11 + " === " + value12 + ": " +
Example : (value11 === value12) + "<br>");
5 != 3 // true // Strictly not equal to (!==)
'hello' != 'hello' // false var value13 = 5;
(iii) Strictly equal to (===) : This operator compares var value14 = 3;
two values and returns true if they are equal in both document.write(value13 + " !== " + value14 + ": " +
value and data type. (value13 !== value14) + "<br>");
Example : var value15 = 5;
5 === 5 // true var value16 = "5";
5 === '5' // false document.write(value15 + " !== " + value16 + ": " +
(iv) Strictly not equal to (!==) : This operator (value15 !== value16) + "<br>");
compares two values and returns true if they are not // Greater than (>)
equal in either value or data type. var value17 = 5;
Example : var value18 = 3;
5 !== 3 // true document.write(value17 + " > " + value18 + ": " +
5 !== '5' // true (value17 > value18) + "<br>");
(v) Greater than (>) : This operator compares two var value19 = "hello";
values and returns true if the first value is greater than var value20 = "world";
the second value. document.write(value19 + " > " + value20 + ": " +
Example : (value19 > value20) + "<br>");
5 > 3 // true // Less than (<)
'hello' > 'world' // false var value21 = 5;
(vi) Less than (<) : This operator compares two values var value22 = 10;
and returns true if the first value is less than the document.write(value21 + " < " + value22 + ": " +
second value. (value21 < value22) + "<br>");
Program : var value23 = "hello";
<html> var value24 = "world";
<head> document.write(value23 + " < " + value24 + ": " +
<title>Relational Operators Example</title> (value23 < value24) + "<br>");
</head> </script>
<body> </body>
<script> </html>
// Equal to (==) output :
var value1 = 5; 5 == 5: true
var value2 = 5; hello == world: false
document.write(value1 + " == " + value2 + ": " + 5 != 3: true
(value1 == value2) + "<br>"); hello != hello: false
var value3 = "hello"; 5 === 5: true
var value4 = "world"; 5 === 5: false
document.write(value3 + " == " + value4 + ": " + 5 !== 3: true
(value3 == value4) + "<br>"); 5 !== 5: false
// Not equal to (!=) 5 > 3: true
var value5 = 5; hello > world: false
var value6 = 3; 5 < 10: true
document.write(value5 + " != " + value6 + ": " + hello < world: true
(value5 != value6) + "<br>"); * These relational operators are commonly used in
conditional statements and loops to make decisions
-: Control structures (or) Decision-making Example :
statements in javascript :- for (let i = 0; i < 10; i++) {
if (i === 5) {
JavaScript has three main types of control break;
structures : }
(1) Conditional Statements : Conditional console.log(i);
statements allow you to execute certain code }
only if a certain condition is true. The two most (ii) continue statement : The `continue` statement skips
common conditional statements in JavaScript one iteration of a loop
are: Example :
(i) if statement : The `if` statement executes a for (let i = 0; i < 10; i++) {
block of code if a specified condition is true. if (i === 5) {
Example : continue;
if (x > 5) { }
console.log("x is greater than 5"); console.log(i);
} }
(ii) switch statement : The `switch` statement * These are the main control structures in JavaScript
executes different blocks of code depending on that allows to control the flow of code.
different cases.
Example : Program :
console.log(i);
switch (day) { <html>
}
case 0: <head>
// Use a break statement
console.log("Sunday"); <title>JavaScript Control
to exit the loop when a
break; Structures Example</title>
certain condition is met
case 1: </head>
for (let i = 0; i <= largest; i+
console.log("Monday"); <body>
+) {
break; <script>
if (i === num1) {
case 2: // Prompt the user to enter
console.log(num1 + " is
console.log("Tuesday"); three numbers
one of the entered
break; let num1 =
numbers!");
default: parseInt(prompt("Enter the
break;
console.log("Invalid day"); first number:"));
}
} let num2 =
console.log(i);
(2) Looping Statements : Looping statements parseInt(prompt("Enter the
}
allow you to execute a block of code repeatedly second number:"));
// Use a continue
while a certain condition is true. The two most let num3 =
statement to skip certain
common looping statements in JavaScript are: parseInt(prompt("Enter the
iterations of the loop
(i) while loop : The `while` loop executes a third number:"));
for (let i = 0; i <= largest; i+
block of code while a specified condition is // Use conditional
+) {
true. statements to find the
if (i === num2 || i ===
Example : largest number
num3) {
while (i < 10) { let largest = num1;
console.log("Skipping " +
console.log(i); if (num2 > largest) {
i);
i++; largest = num2;
continue;
} }
}
(ii) for loop : The `for` loop executes a block of if (num3 > largest) {
console.log(i);
code a specified number of times largest = num3;
}
Example : }
</script>
for (let i = 0; i < 10; i++) { // Use a for loop to print all
</body>
console.log(i); numbers between 0 and the
</html>
} largest number
(3) Jump Statements : Jump statements allow console.log("All numbers
you to "jump" out of a loop or switch statement. between 0 and " + largest +
The two most common jump statements in ":");
JavaScript are : for (let i = 0; i <= largest; i+
(i) break statement : The `break` statement +) {
"jumps" out of a loop or switch statement
-: Explain about switch statement :-
output :
Wednesday
Switch Statement :-
In the above example, the `switch` statement checks the
In JavaScript, the `switch` statement is used to
value of the `day` variable and executes the code block
execute a block of code based on the value of a
associated with the matching case. In this case, the
variable or expression. It provides a way to test
value of `day` is 3, so the code block associated with the
multiple conditions using a single control
`case 3` label is executed, which assigns the string
structure.
`"Wednesday"` to the `dayName` variable. The `break`
syntax :
keyword is used to exit the `switch` statement once the
switch (expression) {
matching case has been found. If none of the cases
case value1: statement-1;
match the value of the expression, the `default` code
break;
block is executed.
case value2: statement-2;
break;
default: default-statement;
break;
}
Example of a `switch` statement in action : -: Write about programmer-defined functions or global
let day = 3; function or pre-defined functions in javascript :-
let dayName;
<html> In JavaScript, there are three main types of functions:
<head> programmer-defined functions, pre-defined functions, and
<title>switch test</title> global functions.
</head> * Programmer-defined functions are created by the
<body> programmer to perform specific tasks or calculations. These
<script type="text/javascript"> functions are defined using the `function` keyword followed by
let day = 3; a name and a set of parentheses, which can include any
let dayName; parameters that the function will accept. The body of the
switch (day) { function is enclosed in curly braces and contains the code that
case 1: will be executed when the function is called.
dayName = 'Monday'; Example of a programmer-defined function that adds two
break; numbers together :
case 2: function addNumbers(num1, num2) {
dayName = 'Tuesday'; return num1 + num2;
break; }
case 3: * Pre-defined functions, also known as built-in functions or
dayName = 'Wednesday'; native functions, are functions that are included in JavaScript
break; by default. These functions can be used without the need to
case 4: define them first. Some common pre-defined functions in
dayName = 'Thursday'; JavaScript include `alert()`, `console.log()`, `parseInt()`,
break; `parseFloat()`, and `Math.random()`.
case 5: * Global functions, also known as methods, are functions that
dayName = 'Friday'; are attached to the global object in JavaScript, which is called
break; `window` in web browsers. These functions can be accessed
case 6: from anywhere in the code and are commonly used for
dayName = 'Saturday'; general-purpose tasks such as manipulating the DOM, working
break; with arrays and strings, and performing asynchronous
case 7: operations. Some common global functions in JavaScript
dayName = 'Sunday'; include `setTimeout()`, `setInterval()`,
break; `document.getElementById()`, and `fetch()`.
default:
dayName = 'Invalid day';
}
console.log(dayName);
</script>
</body>
</html>
-: Explain about functions used in javascript (or) }
Explain the program modules in javascript :- // Function Call and Return Statement
function add(a, b) {
A function in JavaScript is a block of code that return a + b;
performs a specific task and can be reused throughout }
a program. There are three main parts to a function in let result = add(2, multiply(3, 6));
JavaScript: function declaration, function definition, and greet("Harsha");
function call. console.log(result);
(1) Function Declaration : </script>
A function declaration is a statement that defines a </body>
named function. It begins with the keyword "function", </html>
followed by the function name, a list of parameters Output :
enclosed in parentheses, and the code block enclosed Hello, Harsha! 20
in curly braces. Function declarations are hoisted in
JavaScript, meaning they can be called before they are Return statement :
declared. Return statement is used to return a value or a
Example : result.This statement is used to specify the value
function greet(name) { that is returned when a function is called.
console.log("Hello, " + name + "!"); Consider the below example that calculates the
} area of rectangle by using function
(2) Function Definition : program :
A function definition is the code within the function <html>
declaration that performs the specific task. It can <head>
contain any number of statements or expressions. The <title>Area of rectangle</title>
function definition is what is executed when the </head>
function is called. <body>
Example : <script type="text/javascript">
function multiply(a, b) { function Area_rectangle(length, width)
return a * b; {
} area = length * width;
(3) Function Call and Return Statement : return area;
A function call is when the function is actually executed. }
It is done by using the function name followed by </script>
parentheses containing any arguments. The return <form name="formarea">
statement is used to return a value from the function. Enter the length and width of your rectangle to
Example : calculate the area :<br>
function add(a, b) { Length:<input type="text" name="txtlength"
return a + b; size="4"/><br>
} Width:<input type="text" name="txtwidth" size="4"/
let result = add(2, 3); ><br>
console.log(result); // Output: 5 <input type="button" value="CalculatedArea"
Program : onclick=''alert(Area_rectangle(document.formarea.
<html> t xtlength.value,
<head> document.formArea.txtWidth.value))''/>
<title>Example</title> </form>
</head> </body>
<body> </html>
<h1>Functions test</h1> output :
<script> Enter the Length and width of your rectangle to
// Function Declaration calculate the area
function greet(name) { Length : 5
console.log("Hello, " + name + "!"); width : 4
}
// Function Definition calculate Area
function multiply(a, b) {
return a * b; answer = 20
-: Explain about Scope rules in javascript :-
-: Discuss in brief about recursion and write a
In JavaScript, scope rules define where a variable recursive program to perform a popular mathematical
can be accessed within the code. There are two calculations :-
types of scopes in JavaScript: global scope and
local scope. Global scope variables can be Recursion is a programming technique in which a
accessed from any part of the code, while local function calls itself repeatedly until a specific condition
scope variables are only accessible within a is met. It is a powerful tool for solving problems that
specific function or code block. can be defined recursively, such as mathematical
Examples of scope rules in JavaScript : series or trees. The process of recursion involves
Example 1 : Global scope breaking down a problem into smaller and smaller
let name = "harsha"; subproblems until the base case is reached.
function greet() { * Recursive functions have two main components: the
console.log("Hello, " + name + "!"); base case and the recursive case. The base case is the
} condition that stops the recursion and returns a value.
greet(); // Output: "Hello, harsha!" The recursive case is the part of the function that calls
* In this example, the variable `name` is defined in itself with smaller input values until the base case is
the global scope, meaning it can be accessed from reached.
anywhere in the code. The `greet()` function is able Example of a recursive function in JavaScript that
to access the `name` variable and use it in the calculates the factorial of a number :
`console.log()` statement. <html>
Example 2 : Local scope <head>
function printNumber() { <title>finding factorial of 5</title>
let num = 10; </head>
console.log(num); <body>
} <script type="text/javascript">
printNumber(); // Output: 10 function factorial(n) {
console.log(num); // Output: Uncaught if (n === 0) {
ReferenceError: num is not defined return 1;
* In this example, the variable `num` is defined } else {
within the `printNumber()` function, meaning it can return n * factorial(n - 1);
only be accessed within that function. When we try }
to access `num` outside of the function, we get a }
reference error because it is not defined in the console.log(factorial(5));
global scope. </script>
Example 3 : Nested scope </body>
let x = 5; </html>
function outerFunction() { Output : 120
let y = 10; * In this example, the base case is when `n` is equal to
function innerFunction() { 0. When `n` is 0, the function returns 1. Otherwise, the
let z = x + y; function calls itself with `n - 1` as the argument and
console.log(z); multiplies the result by `n`.
} * The above function calculates the factorial of a
innerFunction(); // Output: 15 number recursively. Factorial of a number is a popular
} mathematical calculation. The factorial of a number is
outerFunction(); the product of all positive integers less than or equal to
* In this example, there are two functions: the given number. For example, the factorial of 5 is 5 *
`outerFunction()` and `innerFunction()`. `x` is 4 * 3 * 2 * 1 = 120.
defined in the global scope, `y` is defined in the
`outerFunction()` local scope, and `z` is defined in
the `innerFunction()` local scope. `innerFunction()`
is nested within `outerFunction()`, meaning it has
access to both the `x` and `y` variables. When we
call `innerFunction()` from `outerFunction()`, it can
access both `x` and `y` to calculate the value of `z`.
* It is important to understand scope rules in order
to write efficient and bug-free code.
-: what are different types of looping statements output :
or counter-controlled repetitions :- 0
1
There are three main types of looping statements 2
or counter-controlled repetitions in JavaScript: 3
(1) `for` loop : This loop is used when you know 4
the exact number of iterations you want to (3) `do-while` loop : This loop is similar to the while
perform. It consists of three parts: initialization, loop, but the code block is executed at least once,
condition, and increment or decrement. even if the condition is false.
syntax : syntax :
for (initialization; condition; increment/ do {
decrement) { // code block to be executed
// code block to be executed } while (condition);
} program :
program : <html>
<html> <head>
<head> <title>Do-While Loop Example</title>
<title>For Loop Example</title> </head>
</head> <body>
<body> <script>
<script> let i = 0;
for (let i = 0; i < 5; i++) { do {
console.log(i); console.log(i);
} i++;
</script> } while (i < 5);
</body> </script>
</html> </body>
output : </html>
0 * All three types of loops can be used to repeat a
1 block of code multiple times until a certain condition
2 is met. The choice of loop depends on the specific
3 requirements of the program.
4
(2) `while` loop : This loop is used when you
don't know the exact number of iterations you
want to perform, but you know the condition
under which you want to continue looping.
syntax :
while (condition) {
// code block to be executed
}
Program :
<html>
<head>
<title>While Loop Example</title>
</head>
<body>
<script>
let i = 0;
while (i < 5) {
console.log(i);
i++;
}
</script>
</body>
</html>
-: Various Loop Statements with syntax and (3) do-while loop :
Flow Diagram :- The `do-while` loop is similar to the `while` loop, but
the block of code is executed at least once before the
JavaScript has three loop statements: `for`, condition is checked.
`while`, and `do-while`. Each of these loops syntax :
have different syntax and flow. Let's discuss do {
them one by one: // block of code to be executed
(1) for loop : } while (condition);
The `for` loop is used when you know the * Here, the block of code is executed once before the
number of times you want to execute a block `condition` statement is checked. If it is true, the block
of code. of code is executed again. The flow diagram for a `do-
syntax : while` loop looks like this:
for (initialization; condition; increment) { ------|
// block of code to be executed | |
} | |
* Here, the `initialization` statement is | v
executed once at the beginning of the loop. | block of code
The `condition` statement is checked before | |
each iteration of the loop. If it is true, the block | v
of code is executed. The `increment` | |
statement is executed at the end of each |--> |
iteration. The flow diagram for a `for` loop |
looks like this : v
initialization condition
|
|-> v * In summary, `for`, `while`, and `do-while` are three
| condition different loop statements in JavaScript, each with their
| | own syntax and flow. The `for` loop is used when you
| v know the number of times you want to execute a block
| of code, the `while` loop is used when you do not know
| block of code the number of times but know the condition to stop,
| | and the `do-while` loop is similar to the `while` loop but
| v guarantees that the block of code is executed at least
|-> increment once.
|
v
(2) while loop :
The while loop is used when you do not know
the number of times you want to execute a
block of code, but you know the condition
under which we want to stop.
syntax :
while (condition) {
// block of code to be executed
}
* Here, the `condition` statement is checked
before each iteration of the loop. If it is true,
the block of code is executed. The flow
diagram for a `while` loop looks like this:
----|
| v
| condition <-----
| | |
| v |
| block of code <-|
|_____>
-: Define an Array. Explain in brief about declaring
Example :
and allocating arrays :-
const myArray = [];
myArray[0] = 'Hello';
Array :
myArray[1] = 'World';
In JavaScript, an array is a data structure that
* Here's an example of using JavaScript to declare
allows you to store multiple values in a single
and display an array
variable. It is a container that can hold elements of
Program :
different types, such as numbers, strings, objects,
<html>
or even other arrays. Arrays in JavaScript are zero-
<head>
indexed, meaning that the first element is
<title>Array Example</title>
accessed using the index 0, the second element
<script>
with index 1, and so on.
// JavaScript code
Here's we can define an array in
const fruits = ['apple', 'banana', 'orange'];
JavaScript :
function displayArray() {
// Method 1: Using array literal notation
const output = document.getElementById('output');
const myArray = []; // An empty array
output.innerHTML = fruits.join(', ');
// An array with initial values
}
const numbers = [1, 2, 3, 4, 5];
</script>
const fruits = ['apple', 'banana', 'orange'];
</head>
// Method 2: Using the Array constructor
<body>
const myArray = new Array(); // An empty array
<h1>Array Example</h1>
// An array with initial values
<button onclick="displayArray()">Display Array</
const numbers = new Array(1, 2, 3, 4, 5);
button>
const fruits = new Array('apple', 'banana',
<p id="output"></p>
'orange');
</body>
* we can access individual elements of the array
</html>
using square brackets `[]` and the index of the
* In this example, an array `fruits` is declared and
element. For example, `numbers[0]` would give
initialized with some values. The `displayArray()`
you the first element of the `numbers` array, which
function is triggered when the button is clicked, and
is `1`. You can also modify elements or assign
it retrieves the `output` element and sets its content
new values to specific indices in the array using
to the joined string representation of the `fruits`
the same notation.
array.
* In JavaScript, we can declare and allocate arrays
using various methods. Here are a few ways to
declare and allocate arrays in JavaScript :
(1) Array literal notation : This is the most
common and convenient way to declare and
initialize an array. It uses square brackets `[]` to
enclose the array elements.
Syntax :
const arrayName = [element1, element2, ...];
Example :
const numbers = [1, 2, 3, 4, 5];
const fruits = ['apple', 'banana', 'orange'];
(2) Array constructor : we can also use the `Array`
constructor to create an array.
Syntax :
const arrayName = new Array(element1,
element2, ...);
Example :
const numbers = new Array(1, 2, 3, 4, 5);
const fruits = new Array('apple', 'banana',
'orange');
(3) Empty array : You can declare an empty array
and allocate values to its elements later.
Syntax :
const arrayName = [];
-: one-dimensional and multi-dimensional
* To modify or access elements of a multidimensional
Arrays :-
array, you need to specify both the row index and the
column index.
In JavaScript, arrays are a fundamental data
matrix[2][1] = 10;
structure used to store and manipulate
console.log(matrix); // Output: [[1, 2, 3],
collections of values. JavaScript supports
[4, 5, 6], [7, 10, 9]]
both one-dimensional and multidimensional
we can also have arrays with more than two
arrays.
dimensions, such as three-dimensional arrays or
(1) One-Dimensional Arrays :
higher. The concept is the same: you nest arrays within
A one-dimensional array, also known as a
arrays based on the desired dimensions.
simple or linear array, is a collection of
let cube = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]];
elements arranged in a single row. It
console.log(cube[0][1][0]); // Output: 3
represents a list of values of the same type,
such as numbers or strings. In JavaScript, you
* Multidimensional arrays are useful when we need to
can create a one-dimensional array using the
represent data structures like grids, matrices, or
array literal notation or the `Array` constructor.
nested collections.
* Here's an example of creating a one-
* It's important to note that JavaScript does not have
dimensional array using the array literal
built-in multidimensional array support. Instead, it
notation :
relies on the ability to nest arrays to create the illusion
let numbers = [1, 2, 3, 4, 5];
of multidimensionality.
let fruits = ['apple', 'banana', 'orange'];
* we can access individual elements of a one-
dimensional array using zero-based indexing.
Example :
console.log(numbers[0]); // Output: 1
console.log(fruits[1]); // Output: banana
we can also modify elements by assigning
new values to specific indexes :
numbers[2] = 10;
console.log(numbers); // Output: [1, 2, 10, 4,
5]
Arrays in JavaScript are dynamic, meaning you
can add or remove elements dynamically.
Example :
fruits.push('mango');
console.log(fruits); // Output: ['apple',
'banana', 'orange', 'mango']
numbers.pop();
console.log(numbers); // Output: [1, 2, 10, 4]

(2) Multidimensional Arrays :


A multidimensional array is an array that
contains other arrays as its elements, forming
a grid or matrix-like structure. In JavaScript,
you can create multidimensional arrays by
nesting one-dimensional arrays within each
other.
* Here's an example of creating a two-
dimensional array :
let matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
* In this example, `matrix` is a two-dimensional
array with three rows and three columns. You
can access individual elements in a
multidimensional array using multiple indexes.
console.log(matrix[0][0]); // Output: 1
console.log(matrix[1][2]); // Output: 6
-: (1) Write a short notes on reference and
reference parameters :- function modifyArray(array) {
array.push(4);
reference is a pointer that referes to an object. console.log("Inside the function: " + array);
if the reference is passed as a parameter to a }
function. they are as var numbers = [1, 2, 3];
(1) call-by-value or pass-by-value console.log("Before function call: " + numbers);
(2) call-by-reference or pass-by-reference modifyArray(numbers);
(1) Call-by-value : This is a method of console.log("After function call: " + numbers);
parameter passing where the value of a </script>
variable is passed to a function. When a </head>
function is called with call-by-value, a copy of <body>
the value is made, and any changes made to </body>
the parameter inside the function do not affect </html>
the original variable outside the function. output :
JavaScript typically uses call-by-value for Before function call: 1,2,3
primitive types like numbers, strings, and Inside the function: 1,2,3,4
booleans. After function call: 1,2,3,4
program :
<!DOCTYPE html>
-: (2) How can you pass an array as an argument to a
<html>
function? Give an example. :-
<head>
<title>Call-by-Value Example</title>
Arrays are allowed to be passed to functions in Two
<script>
ways namely, call-by-value and call-by-reference. To pass
function incrementValue(value) {
an array from the calling Function, simply the name of
value += 1;
array must be written. No need to include brackets or
console.log("Inside the function: " + value);
length variables.
}
(1) call-by-value or pass-by-value
var num = 5;
console.log("Before function call: " + num);
(2) call-by-reference or pass-by-reference
incrementValue(num);
console.log("After function call: " + num);
</script>
</head>
<body>
</body>
</html>
output :
Before function call: 5
Inside the function: 6
After function call: 5
(2) Call-by-reference : This is a method of
parameter passing where a reference to the
variable is passed to a function. When a
function is called with call-by-reference, any
changes made to the parameter inside the
function will modify the original variable outside
the function. JavaScript uses call-by-reference
for objects and arrays since assigning a
variable to an object or array creates a
reference to the underlying data.
program :
<html>
<head>
<title>Call-by-Reference Example</title>
<script>
-: Define event handler. What is meant by
-: onLoad Event :
registering event handler? Discuss the types of
events :-
onload Event : The onload event occurs when an
element or the entire page has finished loading.
Event :
program :
Responses made by the browser on account of
<html>
user's interactions are often referred to as
<head>
events. For example, playing audio clip as soon
<title>onload Event Example</title>
as the page is loaded, generation of informative
</head>
text as the mouse pointer is moved through a
<body onload="alert('Page is loaded!')">
certain region of the web page, submission of
<h1>Welcome to my webpage</h1>
user entered data to the server upon clicking the
</body>
submit bution etc., forms normally observed
</html>
events.
output :
Event Handler : Once the event is generated,
Welcome to my page
there is often requirement of code to process
an alert will occur after loading page like (page is
these events. Such code is known event handler.
loaded)
In general, event handlers are of two types.
(a) Interactive Event Handlers :
The event handlers which simply relies on the
user's activity for them to be invoked are
interactive event handler
Example : onClick, onBlur, etc.
(b) Non-Interactive Event Handlers :
The event handlers which do not rely on the
user's for them to be invoked are non-interactive
event handlers.
Example : onPageLoad
Registering Event Handler :
Registering event handler can be defined as the
process of assigning an event handler to node
of a Document Object Model (DOM) Initially, the
registration of event handlers can be done in
two ways. They are as follows.
(1) Inline Model :
In this model, the events can be treated as the
attributes of XHTML. elements.
Example : <p onclick = "exampleFunction()">
(2) Traditional Model :
in this model the events are registered beside
the inline model.
Types of events :
The two types of events are used to trigger
scripts,
(1) Window Events : Window events are the
events that occur as soon as something
happens to the window. They occur when u
page loads or windows or when the focus
moves to and from a window or frame.
(2) User Event : User events are the events that
occur when user interacts with page elements
by using mouse or keyboard or other pointing
device.
-: onMousemove Event :-

onMouseMove event occurs when the pointer points on an element.This event is handled by onMouseamove
event handler. The browser will check the mouse position constantly. if any changes in mouse position is
observed. then the onMouseMove event is triggered.
program :
<!DOCTYPE html>
<html>
<head>
<title>onMouseMove Event Example</title>
</head>
<body>
<li>onMouseMove Eventhandler :
Transverse the mouse through this text
<a href=""onMouseMove='alert("mouse traversed")'>Harsha python Programer</a>
</body>
</html>
output :
when we move mouse to the text the alert will apear as "mouse traversed"

-: onMouseOut Event :

onMouseOut event occurs when the cursor leaves the element. The javascript code is called when the cursor
leaves the element.
program :
<!DOCTYPE html>
<html>
<head>
<title>onMouseOut Event Example</title>
</head>
<body>
<li>onMouseOut Event Handler :
Plase the mouse pointer here
<a href=""onMouseOut='alert("mouse out")'>Harsha Technologies</a>and release
</body>
</html>
output :
when we point the mouse pointer on Harsha Technologies and when we move from it the alert will appear as
"mouse out"

-: onMouseOver Event :

onMouseOver event occurs when the mouse pointer is moved over an element. this event is handled by the
onMouseOver Event Handler.
program :
<!DOCTYPE html>
<html>
<head>
<title>onMouseOver Event Example</title>
</head>
<body>
<li>onMouseOver EventHandler :
<a href=""onMouseOver='alert("Mouse over")'>Harsha Programmer</a>
</body>
</html>
output :
when we move the mouse pointer through text an alert will apear as "Mouse over"
-: onFocus Event :- -: onSubmit :-

when a window frame or form element is focused onSubmit is a form based event, whenever user fills in
on, the onFocus event handler calls the javascript the given form and ensures that his entries has to be
function. the specific javascript code or function loaded on a server then he clicks the "submit" button
will be executed on the occurrence of a focus event. which is provided at the end of each form, hence
the element can be focused by clicking on it or by onSubmit event fires whenever the button to which it is
tabbing it. associated is clicked.
Program : program :
<html> <form name="myform"
<body> onSubmit="window.location=window.document.myfor
Enter Your Name:<input type="text" m.URL.value;return false;">
onFocus="func(this)"> <input type="text" name="URL" value="http://">
<p>Focus on input field, the background-color <input type="submit" value="Redirect">
changes</p> </form>
<script> output :
function func(x) on webpage a field and redirect button is found when
{ we enter the url and click on redirect button it take that
x.style.background="blue"; website
} -: onReset :-
</script>
</body> onReset event occurs when a form is reset. This event
</html> is handled by the onReset event handler. when any form
output : _________ reset, all the controls related to it will be set to their
Enter Your Name: |_________| initial values. this event is cancellable, once the event is
Focus on input field, the background-color cancelled the reset operation will not be performed.
changes program :
<form onReset="hkr()">
-: onBlur Event :- Enter name:<input type="text">
<input type="reset">
onBlur event will be invoked as soon as any text, </form>
data or image turns blur(object losses its focus). <script>
Program : function hkr()
<html> {
<body> alert("The form was reset");
Name:<input type="text" id="myinput" }
onFocus="focusFunction()" </script>
onBlur="blurFunction()"> output : when user enters the name in the name field
<script> and clicks on reset the name will be cleared and alert
function focusFunction() pop's up as "The from was reset"
{
document.getElementById("myinput").style.bac
kground="lightblue";
}
function onBlur()
{
document.getElementById("myinput").style.bac
kground="grey";
}
</script>
</body>
</html>
output :
_________
Name: |_________|
the field background-color will change to lightblue
and dark
-: Event Bubbling :-

Event bubbling can be defined as a process in


which the child element may be triggered and
bubbles up to the root/parent element in the
hierarchy. As soon as an event is triggered, it
first goes to its event handler and then to the
event handler of parent/root element. This
process results in the occurrence of event
handling that is not required. This can be
cancelled by cancelBubble property of that (iii) When the user clicks on child element button, the
particular event object. alert box will display text as Clicked on child element
program :
<!DOCTYPE html>
<html>
<head>
<title>Event bubbling Test</title>
</head>
<body>
<h2>Event bubbling in Javascript</h2>
<div id="parent">
<button>
<h2>parent element<h2>
</button>
<button id="child">
<p>Child element</p>
</button>
</div><br>
<script>document.getElementById("child").ad
dEventListener("click",function()
{
alert("clicked child element");
}, false);
document.getElementById("parent").addEvent
Listener("click",function()
{
alert("Clicked parent element");
}, false);
</script>
</body>
</html>
Output :
(i) when the above code is executed, a screen
with 'parent' and 'child' elements are displayed

(ii) When the user clicks on parent


element button, the alert box will display
text as Clicked parent element
-: JAVASCRIPT OBJECTS AND CREATING OF
const harsha = Object.create(personPrototype);
JAVASCRIPT OBJECTS :-
harsha.name = 'harsha';
harsha.age = 21;
Define Javascript objects :-
* In this example, the personPrototype object serves as
JavaScript objects are fundamental data
the prototype for the harsha object created using
structures in JavaScript that allow us to store
Object.create(). The properties name and age are added
and manipulate collections of related data and
to the harsha object.
functions. Objects are composed of key-value
(iv) Class Syntax : JavaScript supports classes, which
pairs, where the key represents the property
are syntactic sugar over constructor functions. Classes
name, and the value represents the associated
provide a more structured and familiar way to define
data or function.
objects.
-: there are so many ways we can create an
Example :
object they are :-
class Person {
(i) Object Literal Notation:
constructor(name, age) {
(ii) Constructor Functions
this.name = name;
(iii) Object.create() Method
this.age = age;
(iv) Class Syntax
}
sayHello() {
(i) Object Literal Notation :
console.log('Hello!');
object literal notation, which involves defining
}
the object properties and values within curly
}
braces {}
const harsha = new Person('harsha', 21);
Example :
* In this example, the Person class defines the name
const person = {
and age properties and the sayHello method. The new
name: 'harsha',
keyword is used to create an instance of the Person
age: 21,
class.
sayHello: function() {
console.log('Hello!');
}
};
* In this example, the person object is created
with properties name and age, and a method
sayHello.
(ii) Constructor Functions : You can define a
constructor function and use the new keyword to
create new instances of the object.
Example :
function Person(name, age) {
this.name = name;
this.age = age;
}
const harsha = new Person('harsha', 21);
* In this example, the Person function serves as
a constructor for creating Person objects. The
this keyword refers to the new instance being
created, and properties name and age are
assigned to it.
(iii) Object.create() Method : The Object.create()
method allows us to create a new object using
an existing object as the prototype.
Example :
const personPrototype = {
sayHello: function() {
console.log('Hello!');
}
};
-: Math object :-
// Example 1: Rounding
output += "Math.round(4.6): " + Math.round(4.6) +
In JavaScript, the `Math` object is a built-in object
"<br>";
that provides a set of mathematical operations
output += "Math.ceil(4.2): " + Math.ceil(4.2) +
and functions. It does not have a constructor, and
"<br>";
all its properties and methods are static, meaning
output += "Math.floor(4.9): " + Math.floor(4.9) +
they are accessed directly from the `Math` object
"<br>";
itself. The `Math` object provides a convenient
// Example 2: Trigonometry
way to perform common mathematical
output += "Math.sin(Math.PI / 2): " +
calculations in JavaScript.
Math.sin(Math.PI / 2) + "<br>";
* commonly used properties and methods of the
output += "Math.cos(Math.PI): " +
`Math` object :
Math.cos(Math.PI) + "<br>";
(1) Mathematical Constants :
output += "Math.tan(0): " + Math.tan(0) + "<br>";
(i) Math.PI : Represents the mathematical
// Example 3: Exponential and Logarithmic
constant π (pi).
Functions
(ii) Math.E : Represents the mathematical
output += "Math.exp(1): " + Math.exp(1) + "<br>";
constant e (Euler's number).
output += "Math.log(10): " + Math.log(10) + "<br>";
(2) Rounding Functions :
output += "Math.pow(2, 3): " + Math.pow(2, 3) +
(i) Math.round(x) : Rounds a number to the
"<br>";
nearest integer.
output += "Math.sqrt(25): " + Math.sqrt(25) + "<br>";
(ii) Math.ceil(x) : Rounds a number up to the
// Example 4: Random Number Functions
nearest integer.
output += "Math.random(): " + Math.random() +
(iii) Math.floor(x) : Rounds a number down to the
"<br>";
nearest integer.
output += "Math.floor(Math.random() * 10): " +
(3) Trigonometric Functions :
Math.floor(Math.random() * 10) + "<br>";
(i) Math.sin(x) : Returns the sine of a given angle
document.getElementById("output").innerHTML =
(in radians).
output;
(ii) Math.cos(x) : Returns the cosine of a given
}
angle (in radians).
</script>
(iii) Math.tan(x) : Returns the tangent of a given
</head>
angle (in radians).
<body>
(iv) Math.atan(x) : Returns the arctangent of a
<button onclick="runExamples()">Run Examples</
number as a numeric value between -π/2 and π/2
button>
radians.
<div id="output"></div>
(4) Exponential and Logarithmic Functions :
</body>
(i) Math.exp(x) : Returns the value of Euler's
</html>
number (e) raised to the power of x.
Output :
(ii) Math.log(x) : Returns the natural logarithm
Math.round(4.6): 5
(base e) of a number.
Math.ceil(4.2): 5
(iii) Math.pow(x, y) : Returns the value of x raised
Math.floor(4.9): 4
to the power of y.
Math.sin(Math.PI / 2): 1
(iv) Math.sqrt(x) : Returns the square root of a
Math.cos(Math.PI): -1
number.
Math.tan(0): 0
(5) Random Number Functions :
Math.exp(1): 2.718281828459045
(i) Math.random() : Returns a random floating-
Math.log(10): 2.302585092994046
point number between 0 (inclusive) and 1
Math.pow(2, 3): 8
(exclusive).
Math.sqrt(25): 5
(ii) Math.floor(Math.random() * n) : Returns a
Math.random(): 0.12345678901234567
random integer between 0 and n-1.
Math.floor(Math.random() * 10): 7
Example Program :
<!DOCTYPE html>
<html>
<head>
<title>Math Object Examples</title>
<script>
function runExamples() {
var output = "";
-: String Object :- let TenthCharacter = message[10];
document.getElementById('characters').innerHTML = 'First
In JavaScript, a string is a sequence of Character: ' + firstCharacter + '<br>' +
characters enclosed in single quotes ('') or 'Tenth Character: ' + TenthCharacter;
double quotes (""). Strings are immutable, // Concatenation
which means they cannot be changed once let firstName = 'Harsha';
created. However, you can perform various let lastName = 'Vardhan';
operations and manipulations on strings let fullName = firstName + ' ' + lastName;
using built-in methods. Let's discuss the document.getElementById('concatenation').innerHTML = 'Full
string object in JavaScript along with some Name: ' + fullName;
examples. // Substring Extraction
* Creating a String : let extractedSubstring = message.substring(10, 17);
To create a string, you can simply assign a document.getElementById('substring').innerHTML =
value to a variable using quotes : 'Substring: ' + extractedSubstring;
let message = 'Computer, Science!'; // String Searching and Replacement
let name = "Harsha Vardhan"; let searchResult = message.indexOf('Science');
(i) String Length : let nonExistentSearchResult = message.indexOf('harsha');
we can determine the length of a string using document.getElementById('search').innerHTML = 'Search
the `length` property Result: ' + searchResult + '<br>' +
(ii) Accessing Characters : 'Non-Existent Search Result: ' + nonExistentSearchResult;
we can access individual characters in a let newMessage = message.replace('Science',
string using square brackets notation, starting 'Programming');
from index 0: document.getElementById('replace').innerHTML = 'Replaced
(iii) Concatenation : Message: ' + newMessage;
You can concatenate strings using the `+` // Converting Case
operator or the `concat()` method let upperCaseMessage = message.toUpperCase();
(iv) Substring Extraction : let lowerCaseMessage = message.toLowerCase();
we can extract a portion of a string using the document.getElementById('case').innerHTML = 'Uppercase: '
`substring()` method + upperCaseMessage + '<br>' +
(v) String Searching and Replacement : 'Lowercase: ' + lowerCaseMessage;
* we can search for a substring within a string // Splitting and Joining
using the `indexOf()` method : let words = message.split(', ');
* we can also replace a substring with let joinedMessage = words.join(', ');
another string using the `replace()` method : document.getElementById('split-join').innerHTML = 'Split: ' +
(vi) Converting Case : words + '<br>' +
we can convert the case of a string using the 'Joined Message: ' + joinedMessage;
`toUpperCase()` and `toLowerCase()` }
methods </script>
(vii) Splitting and Joining : </head>
* we can split a string into an array of <body>
substrings using the `split()` method <h1>String Object Example</h1>
* we can also join an array of strings into a <button onclick="demonstrateStringOperations()">Click to
single string using the `join()` method Execute String Operations</button>
program : <h2>Output:</h2> Output :
<!DOCTYPE html> <p id="length"></p> * String Length: 18
* First Character: C
<html> <p id="characters"></p> * Tenth Character: S
<head> <p id="concatenation"></p> * Full Name: Harsha Vardhan
<title>String Object Example</title> <p id="substring"></p> * Substring: Science
<script> <p id="search"></p> * Search Result: 10
function demonstrateStringOperations() { <p id="replace"></p> * Non-Existent Search Result: -1
* Replaced Message: Computer,
let message = 'Computer, Science!'; <p id="case"></p> Programming!
let name = "Harsha Vardhan"; <p id="split-join"></p> * Uppercase: COMPUTER, SCIENCE!
// String Length </body> * Lowercase: computer, science!
let length = message.length; </html> * Split: Computer, Science!
document.getElementById('length').innerHT Output : * Joined Message: Computer, Science!
ML = 'String Length: ' + length; When we run this program we will see a button labeled "Click
// Accessing Characters to Execute String Operations". Upon clicking the button, the
let firstCharacter = message[0]; JavaScript code will be executed, and the output will be
-: Date Object :-
Example of Getting values and setting values :
Date Object :
<!DOCTYPE html>
The Date object in JavaScript is used for working with
<html>
dates and times. It represents a single moment in time
<head>
and provides various properties and methods to
<title>Date Object Example</title>
manipulate and retrieve information about dates.
</head>
* Properties of the Date object :
<body>
(i) Date.prototype : The prototype property allows you to
<script>
add new properties and methods to all Date objects.
var date = new Date();
(ii) Date.length : The length property returns the number
// Get methods
of arguments expected by the Date constructor, which is
var year = date.getFullYear();
7.
var month = date.getMonth();
(iii) Date.now() : The now() method returns the current
var day = date.getDate();
timestamp as the number of milliseconds since January
var hours = date.getHours();
1, 1970, 00:00:00 UTC.
var minutes = date.getMinutes();
(iv) Date.parse() : The parse() method parses a date
var seconds = date.getSeconds();
string and returns the number of milliseconds since
var milliseconds = date.getMilliseconds();
January 1, 1970, 00:00:00 UTC.
// Set methods
* Methods of the Date object :
date.setFullYear(2023);
(1) Date() : The Date() constructor creates a new Date
date.setMonth(5); // june (0-11)
object with the current date and time.
date.setDate(24);
(2) Date.UTC() : The UTC() method returns the number of
date.setHours(10);
milliseconds in a Date object since January 1, 1970,
date.setMinutes(30);
00:00:00 UTC.
date.setSeconds(45);
(3) Date.getDate() : The getDate() method returns the day
date.setMilliseconds(500);
of the month (from 1 to 31) for the specified date.
document.write("Current date and time: " + date +
(4) Date.getDay() : The getDay() method returns the day
"<br>");
of the week (from 0 to 6) for the specified date, where
document.write("Year: " + year + "<br>");
Sunday is 0 and Saturday is 6.
document.write("Month: " + month + "<br>");
(5) Date.getFullYear() : The getFullYear() method returns
document.write("Day: " + day + "<br>");
the year (4 digits for 4-digit years) of the specified date.
document.write("Hours: " + hours + "<br>");
(6) Date.getHours() : The getHours() method returns the
document.write("Minutes: " + minutes + "<br>");
hour (from 0 to 23) of the specified date.
document.write("Seconds: " + seconds + "<br>");
(7) Date.getMilliseconds() : The getMilliseconds() method
document.write("Milliseconds: " + milliseconds +
returns the milliseconds (from 0 to 999) of the specified
"<br>");
date.
document.write("<br>After modifications:<br>");
(8) Date.getMinutes() : The getMinutes() method returns
document.write("Modified date and time: " + date
the minutes (from 0 to 59) of the specified date.
+ "<br>");
(9) Date.getMonth() : The getMonth() method returns the
</script>
month (from 0 to 11) for the specified date, where
</body>
January is 0 and December is 11.
</html>
(10) Date.getSeconds() : The getSeconds() method
Output :
returns the seconds (from 0 to 59) of the specified date.
Current date and time: Wed june 24 2023 10:30:00
(11) Date.getTime() : The getTime() method returns the
GMT+0530 (India Standard Time)
number of milliseconds since January 1, 1970, 00:00:00
Year: 2023
UTC.
Month: 5
(12) Date.getUTCDate() : The getUTCDate() method
Day: 24
returns the day of the month (from 1 to 31) of the
Hours: 10
specified date, according to universal time.
Minutes: 30
(13) Date.setFullYear() : The setFullYear() method sets
Seconds: 45
the year (4 digits for 4-digit years) of the specified date.
Milliseconds: 500
(14) Date.setMonth() : The setMonth() method sets the
After modifications :
month (from 0 to 11) for the specified date.
Modified date and time: Mon Sep 25 2022
(15) Date.setDate(): The setDate() method sets the day of
15:30:45 GMT+0530 (India Standard Time)
the month (from 1 to 31) for the specified date.
(16) Date.setHours() : The setHours() method sets the
hour (from 0 to 23) for the specified date.
-: Document Object :- -: Cookies :-

Cookies are small pieces of data that are stored on the user's
Document Object : The main objective of computer by a website. They are commonly used to store information
document object is to change the document about the user's preferences, login status, or other relevant data. In
that is opened in a browser. it consists of this example, I'll provide you with a sample Java servlet program called
various methods and properties. Some of them "CookieServlet" that demonstrates how to work with cookies in a web
are, application.
Example :
Methods : import java.io.IOException;
(i) getElementById(id) : import javax.servlet.ServletException;
it is used to return the DOM node by indicating import javax.servlet.http.HttpServlet;
the XHTML elements whose id is equal to the import javax.servlet.http.HttpServletRequest;
given I'd. import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Cookie;
Usage : var x =
document.getElementById("Harsha"); public class CookieServlet extends HttpServlet {
x.style.color = "blue"; protected void doGet(HttpServletRequest request,
(ii) write(str) : HttpServletResponse response) throws ServletException, IOException {
it is used to write the given string to XHTML // Check if cookies exist
Cookie[] cookies = request.getCookies();
document as XHTML code. if (cookies != null) {
Usage : document.write("harsha"); for (Cookie cookie : cookies) {
(iii) writeIn(str) : String name = cookie.getName();
it is used to write the given string to XHTML String value = cookie.getValue();
document as XHTML code by adding a newline response.getWriter().println("Cookie Name: " + name + ", Value: " +
value);
at the end of the string. }
Usage : document.wrieIn("harsha"); }
properties : // Create a new cookie
(iv) Cookie : Cookie newCookie = new Cookie("username", "JohnDoe");
It stores the values of all the cookies as a string newCookie.setMaxAge(60 * 60); // Cookie expires in 1 hour
response.addCookie(newCookie);
in the computer memory for current document. response.getWriter().println("Cookie has been created.");
(v) lastModified : }
it represents the date and time modified for the }
last time. * In this example, the `doGet` method of the `CookieServlet` class is
Program : overridden to handle HTTP GET requests. Here's a breakdown of the
code :
<!DOCTYPE html> (1) The `doGet` method takes two parameters: the
<html> `HttpServletRequest` object, which represents the request made by the
<head> client, and the
<title>Document Object Test</title> `HttpServletResponse` object, which represents the response that will
</head> be sent back to the client.
(2) We use the `request.getCookies()` method to retrieve any existing
<body> cookies from the client's request. If cookies are found, we iterate
<p id="test">COMPUTER SCIENCE DOM</p> through them and print their names and values.
<button onclick="myFunction()">Click me</ (3) Next, we create a new `Cookie` object called `newCookie`. It is
button> initialized with a name ("username") and a value ("JohnDoe"). The
<script> `setMaxAge` method is used to set the maximum age of the cookie in
seconds (1 hour in this case).
function myFunction() (4) The `response.addCookie` method is called to add the new cookie
{ to the response. This ensures that it will be sent to the client in the
var x = document.getElementById("test"); HTTP response headers.
x.style.color="blue" (5) Finally, a message is printed to the response indicating that the
} cookie has been created.
document.writeIn("")
document.writeIn("Document Object")
document.write("Example")
</script>
</body>
</html>
Output :
when user clicks on "Click me" button, the text
colour of the text will be changed to blue
-: Window Object :-
(xi) print() : it is used to print the content of current
window.
The window object is a fundamental part of the
(xii) prompt() : it is used for creating a dialog box
JavaScript programming language and represents
to enter an input by the user.
the global scope of a browser environment. It is
(xiii) stop() : it is used same as clicking the stop
accessible within the browser's JavaScript runtime
button in the browser.
and provides various properties and methods for
program :
manipulating and interacting with the browser
<!DOCTYPE html>
window.
<html>
Properties of Window Object :
<body>
(i) closed : A boolean value is used to indicate as
<title>Window objects</title>
true if a window is closed.
<script type="text/javascript">
(ii) Defaultstatus : it is used to display the default
function msg()
message on the browser's window status bar.
{
(iii) document : it is used to show a document object
alert("This Alert is method");
which is saved in that window.
var a=confirm("This is confirmed method");
(iv) Frames : An array consists of named child
if(a==true){
frames in the current window.
alert("ok");
(v) History : a history object that has the information
}
of visited URL's in the same window.
else{
(vi) location : The location object specifies the URL
alert("cancel");
of the current window.
}
(vii) name : The name is used to specify the name of
var b=prompt("This is prompt method");
the window.
alert("I am"+b);
(viii) status : A status is a temporary message that is
open("https://www.google.com");
set at any time to display in the status bar.
setTimeout(
(xi) statusbar : A statusbar specifies
function(){
whether the statusbar can be visible or not. it can be
alert("Google page is closed")
known by a boolean value (true/false)
},2000);
(x) toolbar : The toolbar specifies whether the
var myWindow = window.open("","","width=200,
toolbar can be visible or not. it can be known by a
height=100");
boolean value (true/false)
myWindow.document.write("<p>A new window!</
(xi) top : Top specifies the reference for the topmost
p>");
window when different windows are opened on the
myWindow.blur();
desktop.
}
Methods of Window Object :
</script>
(i) alert() : it is used for displaying an alert box with
<input type="button" value="Click it"
message and on botton.
onclick="msg()"/>
(ii) back() : it has the same effect as the browser's
</body>
back button.
<html>
(iii) blur() : it is used for removing and focused or
Output :
making it to loose its focus from the current window.
A page will be created with click it button when the
(iv) close() : it is used to close the current window.
button is clicked the prompt will be displayed As
(v) confirm() : it is used to confirm whether the user
"This is Alert method" when the ok button is
want to perform any action.
pressed the another prompt will display "This is
(vi) focus() : it is used to provide focus to a particular
Confirm method" when we click ok again the ok
window and make it as a top
prompt will be displayed And again when we click
(vii) forward() : it is similar to the clicking of
ok next prompt will be displayed as textfield with
browser's forward button.
ok button if name is entered in text field and
(viii) home() : it is used to allow the user to reach
pressed ok that name will be displayed in alert
their browser's designated homepage.
mode only when we click ok again the google page
(xi) moves by(horizontal pixels, vertical pixels) : it is
will be opened in newtab if name is not entered in
used to move the window by a given number of
the field the page throws an error as google page is
pixels with its current coordinates.
closed.
(x) open(URL, name, specs, replace) : it is used for
opening a new browser window. here the parameters
are optional.
-: Give a brief introduction on XML and features of
-: What are the elements and attributes in XML?
it :-
Give Example :-
XML :
In XML, elements and attributes are used to define
XML (eXtensible Markup Language) is a widely used
and describe the structure and content of the data.
markup language designed to structure, store, and
• Elements :
transport data in a human-readable and platform-
Elements are the building blocks of an XML
independent manner. It provides a flexible way to
document and represent the different components
define and describe data elements using tags and
or entities within the data. They are enclosed within
attributes, making it suitable for a variety of
tags and can have child elements, text content, or
applications and industries.
both. Elements can be nested hierarchically to
* Features of XML :
create a tree-like structure.
(1) Structure : XML allows you to define a
• Example of an XML element :
hierarchical structure for your data. You can create
<book>
custom tags to represent different elements and
<title>Harry Potter and the Sorcerer's Stone</title>
arrange them in a tree-like structure. This enables
<author>J.K. Rowling</author>
you to organize and represent complex data
<year>1997</year>
relationships.
</book>
(2) Self-Descriptive : XML documents are self-
• In the above example, `<book>`, `<title>`,
descriptive, meaning they contain both the data and
`<author>`, and `<year>` are elements. `<book>` is
its metadata. You can define the structure and
the root element, and `<title>`, `<author>`, and
meaning of the data using Document Type
`<year>` are child elements of the `<book>` element.
Definitions (DTD) or XML Schemas (XSD), making it
• Attributes : Attributes provide additional
easier for applications to understand and process
information or metadata about an element. They are
the data.
specified within the opening tag of an element and
(3) Platform-Independent : XML is platform-
consist of a name-value pair. Attributes are used to
independent, which means it can be used on any
provide extra details or characteristics of the
operating system or computing platform. This
element.
allows for seamless data exchange between
• Example of an XML element with attributes :
different systems and applications, regardless of
<book category="fiction" ISBN="123-456789012">
their underlying technologies.
<title>Harry Potter and the Sorcerer's Stone</title>
(4) Human-Readable : XML documents are designed
<author>J.K. Rowling</author>
to be human-readable and understandable. The use
<year>1997</year>
of tags and attributes provides a clear structure,
</book>
making it easier for developers and users to interpret
• In the above example, the `<book>` element has
and work with the data.
two attributes: `category` and `ISBN`. The `category`
(5) Extensibility : XML is extensible, allowing you to
attribute has the value "fiction", and the `ISBN`
define custom tags and attributes based on your
attribute has the value "123-456789012".
specific requirements. This flexibility enables you to
• Elements and attributes are fundamental
adapt XML to various domains and use cases,
components of XML that allow for the organization,
making it highly versatile.
description, and representation of data in a
(6) Interoperability : XML plays a crucial role in
structured and meaningful way.
enabling interoperability between different systems.
It serves as a common data format that can be
shared and understood by multiple applications,
facilitating seamless integration and data exchange.
(7) Well-Supported : XML is supported by a wide
range of programming languages, libraries, and
tools. There are numerous APIs available for parsing,
manipulating, and transforming XML data, making it
easier to work with XML in different development
environments.
* XML's key features make it a popular choice for
data representation and exchange in many domains,
such as web services, data storage, configuration
files, and document formats.
-: Explain the rules of XML syntax :- (7) Comments : Comments in XML provide
additional information or explanations and are
Rules of XML syntax : ignored by XML processors. They are enclosed
XML has a specific syntax that must be followed to within `<!--` and `-->` markers.
ensure a well-formed XML document. Here are the key Example :
rules of XML syntax : <!-- This is a comment -->
(1) XML Declaration : An XML document typically starts (8) Entity References : XML allows the use of
with an optional XML declaration, which declares the predefined entities like `&lt;` for `<` and `&gt;` for `>`,
XML version being used. It begins with the `<?xml ?>` as well as custom entity references for special
tag, followed by the version number and encoding (if characters or symbols.
necessary). Example :
Example : <title>This is an example &mdash; a dash.</title>
<?xml version="1.0" encoding="UTF-8"?> * These rules ensure that an XML document is well-
(2) Root Element : Every XML document must have a formed, meaning it adheres to the syntax
single root element that encapsulates all other requirements and can be processed by XML parsers.
elements. The root element is the starting point and
contains all the other elements in a hierarchical
structure. -: Explain the Basic principles in XML :
Example :
<root> The basic principles in XML :
<!-- Other elements go here -->
</root> (1) XML should support many number of
(3) Elements : Elements are the building blocks of XML applications.
documents and represent the different data (2) XML should be directly used over internet.
components. They are enclosed within opening and (3) XML should be easier to write programs.
closing tags. Element names are case-sensitive and can (4) XML should be used with SGML without any
contain letters, numbers, and other valid characters. conflict.
Elements can be nested to create a hierarchical (5) XML documents should be easily and clearly
structure. understandable by humans.
Example : (6) The design of XML documents should be
<book> formal to genrate.
<title>Harry Potter</title> (7) The XML document should be simple and easy
<author>J.K. Rowling</author> to create.
<year>1997</year> (8) The XML document should be clearly and
</book> correctly designed.
(4) Empty Elements : Empty elements, also known as (9) The optional features in XML is kept at
self-closing or void elements, are elements that do not absolute minimum.
have any content. They are represented by a single tag (10) Minimum importance should be given to XML
without a closing tag. documents compactness.
Example :
<image src="example.jpg" />
(5) Attributes : Elements can have attributes, which
provide additional information about the element.
Attributes are specified within the opening tag and
consist of a name-value pair.
Example :
<book category="fiction">
<!-- Element content goes here -->
</book>
(6) Character Data : The content of an element is known
as character data. It can include text, whitespace, and
other characters. However, certain characters like `<`,
`>`, `&`, and `"` have special meanings in XML and need
to be encoded using character entities.
Example :
<description>This is a <b>bold</b> statement.</
description>
-: Discuss the structuring of data in XML (or) Describe the organization of data in the form of XML :-

XML provides a flexible way to structure and organize data within a document. Here are the key aspects of
structuring data in XML :
(1) Hierarchy : XML allows you to create a hierarchical structure by nesting elements within each other. This
hierarchy represents the relationships between different data elements. For example, in an e-commerce
system, you can have a "Product" element that contains child elements like "Name," "Price," and "Description."
(2) Parent-Child Relationships : XML elements can have parent-child relationships. The parent element
encapsulates and contains its child elements. This allows you to represent complex data structures and
relationships. For example, a "Library" element can have child elements like "Books" and "Authors."
(3) Attributes : XML elements can have attributes that provide additional information or metadata about the
element. Attributes are specified within the opening tag of an element. For example, an "Employee" element
can have attributes like "id" and "department."
(4) Repeating Data : XML allows for repeating data by using multiple occurrences of the same element. For
example, within an "AddressBook" element, you can have multiple "Contact" elements representing different
contacts.
(5) Nested Elements : XML allows nesting elements within other elements. This enables the representation of
complex data structures and relationships. For example, within a "Customer" element, you can have nested
"Address" and "Order" elements.
(6) Self-Descriptive : XML documents are self-descriptive as they contain both data and metadata. You can
define the structure, data types, and constraints of the elements and attributes using Document Type
Definitions (DTD) or XML Schemas (XSD). This self-descriptive nature makes it easier for applications to
understand and process the data.
Example of a simple XML document that represents a basic structure for a "Book" data :
<?xml version="1.0" encoding="UTF-8"?>
<Library>
<Book ISBN="123-456-789">
<Title>The Great Gatsby</Title>
<Author>F. Scott Fitzgerald</Author>
<PublicationYear>1925</PublicationYear>
</Book>
<Book ISBN="123-321-456-789">
<Title>To Kill a Mockingbird</Title>
<Author>Harper Lee</Author>
<PublicationYear>1960</PublicationYear>
</Book>
</Library>
output :
F. Scott Fitzgerald 1925 Harper Lee 1960
* In this example, the "Library" element is the root element that encapsulates multiple "Book" elements. Each
"Book" element has attributes like "ISBN" and contains child elements such as "Title," "Author," and
"PublicationYear."
<library xmlns:bk="http://example.com/books">
-: State the significance of namespace :-
<bk:book>
• In XML, a namespace is a mechanism used to
<bk:title>The Great Gatsby</bk:title>
avoid naming conflicts by providing a unique
<bk:author>F. Scott Fitzgerald</bk:author>
identifier for elements and attributes. It allows you
</bk:book>
to differentiate elements and attributes with the
</library>
same name but belonging to different contexts or
• In this example, the namespace prefix "bk" is declared and
vocabularies.
associated with the URI "http://example.com/books" using
• A namespace is declared using a namespace
the `xmlns:bk` attribute in the root element `<library>`. This
prefix followed by a Uniform Resource Identifier
declares that elements prefixed with "bk:" belong to the
(URI) or Uniform Resource Name (URN). The prefix
specified namespace.
is used as a shorthand reference within the XML
• The `<bk:book>` element and its child elements
document to associate elements and attributes
`<bk:title>` and `<bk:author>` are associated with the "bk"
with the corresponding namespace.
namespace. This allows us to differentiate them from
• Example to illustrate the use of namespaces in
elements with the same local names that might exist in
XML :
other namespaces or the default namespace.
`xml
-: Explain XML DTD :- -: Explain different ways to use a DTD in an XML
document :-
Certainly! XML Document Type Definition (DTD) There are different ways to use a Document Type
is a way to define the structure, elements, and Definition (DTD) in an XML document. Let's explore
attributes of an XML document. It provides a set each of them :
of rules and constraints for validating the (1) Internal DTD : In this approach, the DTD is defined
document's content. directly within the XML document itself. The DTD
Example of an XML DTD program : declarations are placed within the `<!DOCTYPE>`
<!DOCTYPE library [ declaration, typically before the root element. The DTD
<!ELEMENT library (book+)> declarations are enclosed within square brackets ([]).
<!ELEMENT book (title, author, Example :
publicationYear)> <?xml version="1.0" encoding="UTF-8"?>
<!ELEMENT title (#PCDATA)> <!DOCTYPE library [
<!ELEMENT author (#PCDATA)> <!ELEMENT library (book+)>
<!ELEMENT publicationYear (#PCDATA)> <!ELEMENT book (title, author)>
]> <!ELEMENT title (#PCDATA)>
<library> <!ELEMENT author (#PCDATA)>
<book> ]>
<title>The Great Gatsby</title> <library>
<author>F. Scott Fitzgerald</author> <book>
<publicationYear>1925</publicationYear> <title>The Great Gatsby</title>
</book> <author>F. Scott Fitzgerald</author>
<book> </book>
<title>To Kill a Mockingbird</title> </library>
<author>Harper Lee</author> • In this example, the DTD declarations are specified
<publicationYear>1960</publicationYear> within the `<!DOCTYPE library [...]` section. The internal
</book> DTD defines the structure and content rules for the XML
</library> document.
output : ]> F. Scott Fitzgerald 1925 Harper Lee Advantages of Internal DTD :
1960 • Simplicity : Internal DTDs provide a straightforward
• In this example, the DTD section is defined approach as they are defined directly within the XML
within the `<!DOCTYPE>` declaration. It specifies document itself. There is no need for additional external
the structure and content rules for the XML files, which can simplify document management and
document. Here's what each DTD line represents: distribution.
• `<!ELEMENT library (book+)>`: Defines that the Disadvantages of Internal DTD :
root element is "library" and it must contain one • Code Duplication : In cases where multiple XML
or more "book" elements. documents need to adhere to the same DTD, internal
• `<!ELEMENT book (title, author, DTDs can lead to code duplication. Each XML
publicationYear)>`: Specifies that the "book" document must repeat the DTD declarations, which can
element should contain "title," "author," and be time-consuming and prone to errors when making
"publicationYear" elements in that order. changes or updates.
• `<!ELEMENT title (#PCDATA)>`: Declares that (2) External DTD :
the "title" element contains parsed character data In this approach, the DTD is defined in a separate
(#PCDATA), which represents text content. external file with a .dtd extension. The XML document
• `<!ELEMENT author (#PCDATA)>`: Declares that references the external DTD file using the `SYSTEM`
the "author" element also contains parsed keyword within the `<!DOCTYPE>` declaration.
character data. Example :
• `<!ELEMENT publicationYear (#PCDATA)>`: XML document (`library.xml`) :
Specifies that the "publicationYear" element <?xml version="1.0" encoding="UTF-8"?>
contains parsed character data. <!DOCTYPE library SYSTEM "library.dtd">
• By including the DTD in the XML document, you <library>
define the structure and constraints for the <book>
elements. The XML content should adhere to the <title>The Great Gatsby</title>
defined rules specified in the DTD. In this case, <author>F. Scott Fitzgerald</author>
the DTD ensures that each "book" element </book>
includes a "title," "author," and "publicationYear" </library>
element.
External DTD file (`library.dtd`) : -: Ajax :-
<!ELEMENT library (book+)> * Ajax (Asynchronous JavaScript and XML) is a technique
<!ELEMENT book (title, author)> used in web development to create dynamic and interactive
<!ELEMENT title (#PCDATA)> web applications. It allows for the asynchronous exchange
<!ELEMENT author (#PCDATA)> of data between a web browser and a web server without
* In this example, the XML document requiring a full page reload.
references the external DTD file `library.dtd` * Traditionally, when a user interacts with a web page, such
using the `SYSTEM` keyword. The DTD as submitting a form or clicking a link, the entire page would
declarations are placed in the separate DTD reload to fetch new content from the server. However, with
file, which can be reused across multiple XML Ajax, only specific portions of the page can be updated,
documents. providing a more seamless and responsive user experience.
• Advantages Of External DTD : * Ajax achieves this by using a combination of technologies,
• Reusability : External DTDs can be defined primarily JavaScript and XML (although JSON is commonly
once and reused across multiple XML used instead of XML nowadays). JavaScript is responsible
documents. This promotes consistency, for making asynchronous requests to the server and
reduces code duplication, and simplifies manipulating the page content dynamically. XML or JSON is
maintenance as changes can be made in a used to format the data being sent between the client and
single DTD file. server.
Disadvantages of External DTD : * The key aspect of Ajax is its asynchronous nature,
• Dependency on External Files : meaning that the web page can continue to be used and
External DTDs require the XML document to interacted with while the data is being fetched from the
reference and access the external DTD file. If server in the background. This enables developers to create
the external DTD file is missing, inaccessible, more interactive and responsive applications.
or not up-to-date, it can result in validation * Ajax is widely used in modern web development and has
errors or incorrect interpretation of the XML been instrumental in the development of various web
document. technologies and frameworks. It has facilitated the creation
(3) Combining Internal and External DTDs : of dynamic interfaces, real-time updates, and interactive
It is also possible to combine both internal features, enhancing the overall user experience on the web.
and external DTDs in an XML document. In -: DOM :-
this approach, the DTD declarations can be DOM stands for Document Object Model. It is a programming
split between the internal DTD and external interface for HTML and XML documents, representing the
DTD files. The internal DTD can define some structure and content of a webpage. The DOM provides a way
rules, while the external DTD can define to access, manipulate, and update elements on a webpage
additional rules. dynamically.
Example : * In simple terms, when a web page is loaded, the browser
XML document (`library.xml`) : creates a structured representation of the page, known as the
<?xml version="1.0" encoding="UTF-8"?> DOM tree. Each element in the HTML document, such as
<!DOCTYPE library [ headings, paragraphs, images, and buttons, becomes a node in
<!ELEMENT book (title, author)> the tree.
<!ELEMENT title (#PCDATA)> Example to illustrate how the DOM works :
]> <!DOCTYPE html>
<library> <html>
<book> <head>
<title>The Great Gatsby</title> <title>DOM Example</title>
<author>F. Scott Fitzgerald</author> </head>
</book> <body>
</library> <h1>Welcome to the DOM example</h1>
External DTD file (`library.dtd`) : <p id="demo">This is a paragraph.</p>
<!ELEMENT library (book+)> <button onclick="changeText()">Click me</button>
<!ELEMENT author (#PCDATA)> <script>
• In this example, the XML document function changeText() {
includes an internal DTD that defines the var paragraph = document.getElementById("demo");
"book" element and the "title" element. The paragraph.innerHTML = "Text changed!";
external DTD file `library.dtd` defines the }
"library" element and the "author" element. </script>
</body>
</html>
-: XML Schema and Creation :-

An XML schema, also known as XML Schema Definition (XSD), is a description of the structure, content,
and data types allowed in an XML document. It defines the rules and constraints that govern the elements,
attributes, and relationships within an XML document. XML schemas provide a way to validate the
structure and integrity of XML data, ensuring that it conforms to a specific set of rules.
* To create an XML schema, you typically define it using XML Schema Definition Language (XSD), which is
an XML-based language itself.
Example of how an XML schema can be created :

<?xml version="1.0" encoding="UTF-8"?>


<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="bookstore">
<xs:complexType>
<xs:sequence>
<xs:element name="book" maxOccurs="unbounded">
<xs:complexType>
<xs:sequence>
<xs:element name="title" type="xs:string"/>
<xs:element name="author" type="xs:string"/>
<xs:element name="price" type="xs:decimal"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
* In this example, the XML schema describes a simple structure for a bookstore. It contains a root element
named "bookstore" with a complex type. Inside the "bookstore" element, there is a sequence of "book"
elements. Each "book" element has a complex type with a sequence of child elements: "title," "author," and
"price," each having their own data types specified using XML Schema built-in types (e.g., "xs:string" for a
string, "xs:decimal" for a decimal number).
* This XML schema defines the structure and data types expected in an XML document conforming to this
schema. You can use various XML schema validators or XML processing tools to validate XML documents
against this schema to ensure they adhere to the defined rules and constraints.
-: What is XSL (XSLT) How it can be used to present XML ? :-

XSL stands for Extensible Stylesheet Language, which is a language used for transforming and presenting
XML (Extensible Markup Language) documents. It is a standard defined by the World Wide Web Consortium
(W3C) and consists of two main components: XSLT (XSL Transformations) and XSL-FO (XSL Formatting
Objects).
* XSLT is used for transforming XML documents into other formats, such as HTML, PDF, or plain text. It
allows you to extract data from XML documents, apply formatting and styling, and generate a new output
document. XSLT uses XPath to navigate through the XML structure and define transformation rules.
* XSL-FO, on the other hand, is used for defining the layout and formatting of XML documents. It describes
how the content should be displayed, specifying elements such as page layout, headers, footers, margins,
and fonts. XSL-FO files can be transformed into various output formats using XSLT processors.
Example to illustrate the usage of XSL to present XML :
XML input :
<bookstore>
<book>
<title>Harry Potter and the Philosopher's Stone</title>
<author>J.K. Rowling</author>
<year>1997</year>
</book>
<book>
<title>The Hobbit</title>
<author>J.R.R. Tolkien</author>
<year>1937</year>
</book>
</bookstore>

XSLT stylesheet :
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<h2>Bookstore</h2>
<table border="1">
<tr>
<th>Title</th>
<th>Author</th>
<th>Year</th>
</tr>
<xsl:for-each select="bookstore/book">
<tr>
<td><xsl:value-of select="title"/></td>
<td><xsl:value-of select="author"/></td>
<td><xsl:value-of select="year"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
* In this example, the XSLT stylesheet defines a template that matches the root element ("/") of the XML
document. It generates an HTML document with a table displaying the book information. The `<xsl:for-each>`
loop iterates over each `<book>` element, extracting the values of the `<title>`, `<author>`, and `<year>`
elements using `<xsl:value-of>`. The resulting output would be an HTML table presenting the XML data in a
formatted manner.

You might also like