Valid HTML5 Code and Structure Guide
Valid HTML5 Code and Structure Guide
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 :
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]
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 :-
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 `<` for `<` and `>` 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 — 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 :
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.