0% found this document useful (0 votes)
26 views84 pages

JC Web

The document covers fundamental concepts of HTML and CSS, including the structure of an HTML document, types of lists in HTML, and various CSS styles and selectors. It explains the box model in CSS, detailing the content, padding, border, and margin areas. Additionally, it introduces JavaScript control statements and loops, providing examples for better understanding.

Uploaded by

pavan raj
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)
26 views84 pages

JC Web

The document covers fundamental concepts of HTML and CSS, including the structure of an HTML document, types of lists in HTML, and various CSS styles and selectors. It explains the box model in CSS, detailing the content, padding, border, and margin areas. Additionally, it introduces JavaScript control statements and loops, providing examples for better understanding.

Uploaded by

pavan raj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 84

Briefly explain the HTTP request and response in AJAX with suitable examples

Structure of HTML

Types of lists in HTML

Different style sheets available in CSS with example

Different positioning of HTML elements in CSS

Unit -1
1).Structure of HTML

Structure of an HTML Document


An HTML document is essentially a series of nested elements that work together to form a complete
webpage. The document follows a standard structure to ensure consistency and compatibility across
different browsers.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content=
"width=device-width, initial-scale=1.0" />
<title>Structure of HTML Document</title>
</head>
<body>
<!-- Main content of website -->
<h1>GeeksforGeeks</h1>
<p>A computer science portal for geeks</p>
</body>
</html>
1. <!DOCTYPE html>: Declaring the Document Type
The <!DOCTYPE html> declaration is used to specify the version of HTML. In this case, it indicates
that the document is written in HTML5, which is the latest version of HTML.
2. <html>: The Root Element
The <html> element is the root element of the HTML document. Everything inside this element is
considered part of the HTML document.
3. <head>:Metadata of the Document
The <head> section contains metadata about the document that isn't displayed on the webpage. This
section includes important elements like:
• <meta charset="UTF-8">: Specifies the character encoding for the document (UTF-8
supports most characters from all languages).
• <meta name="viewport" content="width=device-width, initial-scale=1.0">: Controls
the layout on mobile devices by setting the viewport width and scaling.
4. <body>:Visible Content of the Webpage
The <body> tag contains the actual content of the webpage that will be visible to users, such as text,
images, and links.
Tags and Elements for Structuring an HTML Document
HTML tags are structural components enclosed in angle brackets. They are typically opened and
closed with a forward slash (e.g., <h1></h1>). Some tags are self-closing, while others support
attributes like width, height, and controls for defining properties or storing metadata.
There are generally two types of tags in HTML
1. Paired Tags: These tags come in pairs i.e. they have both opening(< >) and closing(</ >)
tags.
2. Empty Tags: These tags are self-closing and do not require a closing tag.”
Below is an example of a <b> tag in HTML, which tells the browser to bold the text inside it.

Understanding these key tags will allow you to organize content effectively and create more readable
and accessible webpages.
• Headings (<h1> to <h6>): Headings are important for structuring the content within
the <body> section. They define the hierarchy of information, where <h1> is the highest-
level heading.
• Paragraphs (<p>): The <p> tag is used for creating paragraphs, which help to group text
into readable sections. This tag automatically adds some spacing between paragraphs to
improve readability.
• Images (<img>): The <img> tag is used to add images to a webpage. It requires the src
attribute to specify the image path and the alt attribute for accessibility.
• Links (<a>):Links are created with the <a> tag. The href attribute defines the destination
URL, and the text within the <a> tag serves as the clickable link text.
• Lists (<ul>, <ol>, <li>): Lists allow you to organize items in bullet
points (<ul>) or numbered order (<ol>). Each item within a list is wrapped in <li> tags.
• Divisions (<div>): The <div> tag is a container used to group other elements together,
often for layout. It does not add any style or structure on its own but is useful for applying
CSS styles to sections of content.

2).Explain the Lists in HTML

HTML offers web authors three ways for specifying lists of information. All lists must contain one or
more list elements.

1. Ordered List or Numbered List (ol)

2. Unordered List or Bulleted List (ul)

3. Description List or Definition List (dl)

1. Ordered List or Numbered List <ol>

In the ordered HTML lists, all the list items are marked with numbers by default. It is known as
numbered list also. The ordered list starts with <ol> tag and the list items start with <li> tag.
<html>

<head>

<title>HTML Ordered List</title>

</head>

<body>

<ol>

<li>DBMS</li>

<li>SOFTWARE ENGINEERING</li>

<li>JAVA</li>

<li>WEB TECHNOLOGY</li>

</ol>

</body>

</html>

2. Unordered List or Bulleted List <ul>

In HTML Unordered list, all the list items are marked with bullets. It is also known as bulleted list
also. The Unordered list starts with <ul> tag and list items start with the <li> tag.
<html>

<head>

<title>HTML Unordered List</title>

</head> <body>

<ul>

<li>DBMS</li>

<li>SOFTWARE ENGINEERING</li>

<li>JAVA</li>

<li>WEB TECHNOLOGY</li>

</ul>

</body>

</html>

3. Description Lists <dl>

HTML also supports description lists.

A description list is a list of terms, with a description of each term.

The <dl> tag defines the description list, the <dt> tag defines the term (name), and the <dd> tag describes
each term:

Definition List makes use of following three tags.

1). <dl> - Defines the start of the list

2). <dt> - A term

3). <dd> - Term definition

4). </dl> - Defines the end of the list


<html>

<head>

<title>HTML Definition
List</title>

</head>

<body>
<dl>

<dt><b>HTML</b></dt>

<dd>This stands for Hyper Text


Markup

Language</dd>
<dt><b>HTTP</b></dt>

<dd>This stands for Hyper Text


Transfer

Protocol</dd>

</dl>

</body>

</html>

3).Levels of CSS OR TYPES OF CSS

1.Inline CSS

Inline CSS is generally used to style a specific HTML element only. We can write inline CSS simply

by adding the style attribute to each HTML element.

For Example:
<h1 style="background-color:yellow;"> This is a heading </h1>

<p style="color:red"> This is some pragraph </p>

This CSS type is not really recommended, as each HTML tag needs to be styled individually.

Managing a website may be difficult if we use only inline CSS.

Advantages

• You can easily and quickly write inline CSS to an HTML page.
• It is useful for testing or previewing the changes, and performing quick fixes to your website.
• You don’t need to create or link a separate document as required in the external CSS.

Disadvantages

• Generally, Inline CSS needs to write in each HTML tag individually. So managing a website
may be difficult if we use only inline CSS.
• Adding CSS property to every HTML tag is time-consuming.
• Styling multiple elements can affect your page’s size and download time.

Example

<!DOCTYPE html>

<html>

<body>

<h1 style="color:red">Simple Box Design </h1>

<div style="height:200px;width:300px;background-color:yellow"> </div>

</body>

</html>

2.Internal CSS

Internal CSS is also known as embedded CSS. It is generally used to style a single page. We can

write internal CSS inside a <style> tag within the HTML pages.
For Example:

<style>

h1{

background-color : yellow;

color : red;

</style>

<h1> This is a heading </h1>

This CSS type is an effective method of styling a single page. However, using this style for multiple

pages is time-consuming as you need to put CSS style on every page of your website.

Advantages

• You can use ID and class selectors to write the internal CSS.
• Since you’ll only add the code within the same HTML file, you don’t need to create or upload
multiple files.

Disadvantages

• Since you’ll only add the code within the same HTML file, styling multiple pages will become

time-consuming.

• Adding the code to the HTML document can increase the page’s size and loading time.

Example

<!DOCTYPE html>

<html>

<head>

<style>

/* Using tag name as a selector here */

h1{
background-color:orange;

/* Using class as a selector here */

.box{

height:200px;

width:300px;

background-color:yellow;

/* Using ID as a selector here */

#circle{

height:200px;

width:200px;

background-color:red;

border-radius:50%;

</style>

</head>

<body>

<h1>Simple example of internal CSS</h1>

<div class="box"></div>

<div id="circle"></div>

</body>

</html>
External CSS

With an external CSS, you can change the look of an entire website by changing just one file. We

can write external CSS in a separate .css file. Each HTML page must include a reference to

the external CSS file inside the <link> tag, inside the <head> tag.

For Example:

creating a my-style.css file with any text editor( eg:- Notepad++)

/* Using tag name as a selector here */

h1{

background-color:orange;

/* Using class as a selector here */

.box{

height:200px;

width:300px;

background-color:yellow;

/* Using ID as a selector here */

#circle{

height:200px;

width:200px;

background-color:red;

border-radius:50%;

Now include the my-style.css external file in your HTML page using <link> tag:
<link rel="stylesheet" type="text/css" href="my-style.css" />

The complete HTML page will look like this:

<!DOCTYPE html>

<html>

<head>

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

</head>

<body>

<h1>Simple example of external CSS</h1>

<div class="box"></div>

<div id="circle"></div>

</body>

</html>

Advantages

• Since the CSS code is in a separate file, your HTML files will have a cleaner structure and be
smaller in size.
• You can use the same .css file for multiple pages when you want the same look for each page.

Disadvantages

• Your pages may not be rendered correctly until the external CSS is loaded.
• Uploading multiple external CSS files can increase the download time of a website.

4). Explain the Types of selectors

CSS (Cascading Style Sheets) selectors are patterns used to select and style HTML elements. They

allow you to target specific elements on a web page and apply styles to them. Here are some

common CSS selectors:


1. Universal Selector:

*: Selects all elements on the page.

2. Type Selector:

element: Selects all instances of the specified HTML element.

3. Class Selector:

.class: Selects all elements with a specific class attribute.

4. ID Selector:

#id: Selects a single element with a specific id attribute.

5. Child Selector:

parent > child: Selects all direct children of the specified parent.

6. Adjacent Sibling Selector:

element + adjacent: Selects the adjacent sibling of the specified element.

7. General Sibling Selector:

element ~ sibling: Selects all siblings that share the same parent as the specified

element.

8. Attribute Selector:

[attribute]: Selects all elements with the specified attribute.

[attribute=value]: Selects elements with a specific attribute value.

[attribute~=value]: Selects elements with an attribute value containing a specified

word.

9. Pseudo-classes:

: hover: Selects and styles an element when the mouse hovers over it.

: focus: Selects and styles an element when it is in focus.

: first-child: Selects the first child of a parent.


: nth-child(n): Selects the nth child of a parent.

: nth-child(odd), :nth-child(even): Selects odd or even children of a parent.

10. Pseudo-elements:

:: before: Inserts content before the specified element.

:: after: Inserts content after the specified element.

:: first-line: Selects the first line of text in an element.

:: first-letter: Selects the first letter of text in an element.

Example:

/* Selects all paragraphs */

p{

color: blue;

/* Selects elements with class 'highlight' */

.highlight {

background-color: yellow;

/* Selects the element with id 'header' */

#header {

font-size: 24px;

}
/* Selects the first child of each 'div' */

div > :first-child {

font-weight: bold;

/* Selects odd rows in a table */

tr:nth-child(odd) {

background-color: #f2f2f2;

5). Discuss the concept of BOX model in CSS with neat diagram

When laying out a document, the browser's rendering engine represents each element as a rectangular box

according to the standard CSS basic box model. CSS determines the size, position, and properties (color,

background, border size, etc.) of these boxes.

Every box is composed of four parts (or areas), defined by their respective edges: the content edge, padding

edge, border edge, and margin edge.


Content area

The content area, bounded by the content edge, contains the "real" content of the element, such as text, an

image, or a video player. Its dimensions are the content width (or content-box width) and the content

height (or content-box height). It often has a background color or background image.

If the box-sizing property is set to content-box (default) and if the element is a block element, the content
area's

size can be explicitly defined with the width, min-width, max-width, height, min-height, and max-

height properties.

Padding area

The padding area, bounded by the padding edge, extends the content area to include the element's padding.
Its

dimensions are the padding-box width and the padding-box height.

The thickness of the padding is determined by the padding-top, padding-right, padding-bottom, padding-left,

and shorthand padding properties.

Border area

The border area, bounded by the border edge, extends the padding area to include the element's borders. Its

dimensions are the border-box width and the border-box height.

The thickness of the borders are determined by the border-width and shorthand border properties. If the box-

sizing property is set to border-box, the border area's size can be explicitly defined with the width, min-

width, max-width, height, min-height, and max-height properties. When there is a background (background-

color or background-image) set on a box, it extends to the outer edge of the border (i.e. extends underneath
the border in z-ordering). This default behavior can be altered with the background-clip CSS property.
Margin area

The margin area, bounded by the margin edge, extends the border area to include an empty area used to
separate

the element from its neighbors. Its dimensions are the margin box width and the margin box height.

The size of the margin area is determined by the margin-top, margin-right, margin-bottom, margin-left, and

shorthand margin properties. When margin collapsing occurs, the margin area is not clearly defined since

margins are shared between boxes.

Finally, note that for non-replaced inline elements, the amount of space taken up (the contribution to the
height

of the line) is determined by the line-height property, even though the borders and padding are still displayed

around the content.

5).Javascript control statements, loops, arrays, elements, access, event access

Controls Statement

There are three forms of if statement in JavaScript.

1. If Statement

2. If else statement

3. if else if statement

JavaScript If statement

It evaluates the content only if expression is true. The signature of JavaScript if statement is given

below.

if(expression){

//content to be evaluate

}
Let’s see the simple example of if statement in javascript.

<script>

var a=20;

if(a>10){

document.write("value of a is greater than 10");

</script>

Output of the above example

value of a is greater than 10

JavaScript If...else Statement

It evaluates the content whether condition is true of false. The syntax of JavaScript if-else statement

is given below.een

if(expression){

//content to be evaluated if condition is true

else{

//content to be evaluated if condition is false

Let’s see the example of if-else statement in JavaScript to find out the even or odd number.

<script>

var a=20;

if(a%2==0){
document.write("a is even number");

else{

document.write("a is odd number");

</script>

Output of the above example

a is even number

JavaScript If...else if statement

It evaluates the content only if expression is true from several expressions. The signature of

JavaScript if else if statement is given below.

if(expression1){

//content to be evaluated if expression1 is true

else if(expression2){

//content to be evaluated if expression2 is true

else if(expression3){

//content to be evaluated if expression3 is true

else{

//content to be evaluated if no expression is true

}
Let’s see the simple example of if else if statement in javascript.

<script>

var a=20;

if(a==10){

document.write("a is equal to 10");

else if(a==15){

document.write("a is equal to 15");

else if(a==20){

document.write("a is equal to 20");

else{

document.write("a is not equal to 10, 15 or 20");

</script>

Output of the above example

a is equal to 20

JavaScript Switch

The JavaScript switch statement is used to execute one code from multiple expressions.

It is just like else if statement that we have learned in previous page. But it is convenient

than if..else..if because it can be used with numbers, characters etc.

The signature of JavaScript switch statement is given below.


switch(expression){

case value1:

code to be executed;

break;

case value2:

code to be executed;

break;

......

default:

code to be executed if above values are not matched;

Let’s see the simple example of switch statement in javascript.

<script>

var grade='B';

var result;

switch(grade){

case 'A':

result="A Grade";

break;

case 'B':

result="B Grade";

break;

case 'C':
result="C Grade";

break;

default:

result="No Grade";

document.write(result);

</script>

Output of the above example

B Grade

JavaScript Loops

The JavaScript loops are used to iterate the piece of code using for, while, do while or for-

in loops. It makes the code compact. It is mostly used in array.

There are four types of loops in JavaScript.

1. for loop

2. while loop

3. do-while loop

1) JavaScript For loop

The JavaScript for loop iterates the elements for the fixed number of times. It should be

used if number of iteration is known. The syntax of for loop is given below.

for (initialization; condition; increment)

code to be executed
}

Let’s see the simple example of for loop in javascript.

<script>

for (i=1; i<=5; i++)

document.write(i + "<br/>")

</script>

Output:

2) JavaScript while loop

The JavaScript while loop iterates the elements for the infinite number of times. It should

be used if number of iteration is not known. The syntax of while loop is given below.

while (condition)

code to be executed

Let’s see the simple example of while loop in javascript.


<script>

var i=11;

while (i<=15)

document.write(i + "<br/>");

i++;

</script>

Output:

11

12

13

14

15

3) JavaScript do while loop

The JavaScript do while loop iterates the elements for the infinite number of times like

while loop. But, code is executed at least once whether condition is true or false. The syntax

of do while loop is given below.

do{

code to be executed

}while (condition);

Let’s see the simple example of do while loop in javascript.

<script>
var i=21;

do{

document.write(i + "<br/>");

i++;

}while (i<=25);

</script>

Output:

21

22

23

24

25

ARRAY

JavaScript array is an object that represents a collection of similar type of elements.

There are 3 ways to construct array in JavaScript

1. By array literal

2. By creating instance of Array directly (using new keyword)

3. By using an Array constructor (using new keyword)

1) JavaScript array literal

The syntax of creating array using array literal is given below:

var arrayname=[value1,value2.....valueN];

As you can see, values are contained inside [ ] and separated by , (comma).

Let's see the simple example of creating and using array in JavaScript.

<script>
var emp=["Sonoo","Vimal","Ratan"];

for (i=0;i<emp.length;i++){

document.write(emp[i] + "<br/>");

</script>

The .length property returns the length of an array.

Output of the above example

Sonoo

Vimal

Ratan

2) JavaScript Array directly (new keyword)

The syntax of creating array directly is given below:

var arrayname=new Array();

Here, new keyword is used to create instance of array.

Let's see the example of creating array directly.

<script>

var i;

var emp = new Array();

emp[0] = "Arun";

emp[1] = "Varun";

emp[2] = "John";

for (i=0;i<emp.length;i++){

document.write(emp[i] + "<br>");

}
</script>

Output of the above example

Arun

Varun

John

3) JavaScript array constructor (new keyword)

Here, you need to create instance of array by passing arguments in constructor so that we

don't have to provide value explicitly.

The example of creating object by array constructor is given below.

<script>

var emp=new Array("Jai","Vijay","Smith");

for (i=0;i<emp.length;i++){

document.write(emp[i] + "<br>");

</script>

Output of the above example

Jai

Vijay

Smith.

Element Access in JavaScript

These objects identify elements in a document, associating common methods and

their respective properties with other elements. These are referred to as specific

classes which define functionality within the hierarchy.


• By ID
• By Tag Name
• By Class Name
• By CSS Selectors
• By HTML Object Collections

Get Element by ID

By using the getElementById() method, an element object results in an element where

the ID property matches the desired string. Moreover, you should note that IDs should

be unique once specified in order to access the required elements. This method is

very simple and easy to find the HTML element in the DOM, as you will be able to

understand from the example below:

<!DOCTYPE html>

<html>

<body>

<h2>HTML DOM Element</h2>

We will be finding HTML Elements using Id

<p></p>

<p id=”demo”></p>

<script>

const element = document.getElementById(“sample”);

document.getElementById(“demo”).innerHTML =

“We are using text from sample paragraph: ” + element.innerHTML;

</script>

</body>

</html>
From the example above, if an element is found, an object element will return in

myElement. In case there is no element, myElement will return null.

Get Element by Tag Name

Using the getElementByTagName() method provides us an HTML collection (live) of

elements with their respective tag names. So, when trying to get element by name in

JavaScript, do note the following:

• All the hierarchical orders specified will be searched except the main element.
• The live list of HTML collections keeps updating the DOM tree automatically.
• DOM can change between the calls so we just use this method once to avoid repetition.
• The arguments are lower-cased automatically when working with HTML elements.
• By using Element.getElementByTagName(), automatic lower-case can be prevented.

Often, Element.getElementByTagName is confused

with Document.getElementByTagName(). However, one subtle difference is the

search of the hierarchy of a specified element.

– Syntax of Tag Name

We should work with the following syntax when implementing this method:

elements = element.getElementsByTagName(tagName)

– Example 1 Using the Tag Name Method

We will be using two examples for the Tag Name. Let’s look at the first one:

<!DOCTYPE html>

<html>

<body>
<h2>HTML DOM Element</h2>

<p>We are finding HTML Elements using Tag Name.</p>

<p></p>

<p id=”demo”></p>

<script>

const element = document.getElementsByTagName(“p”);

document.getElementById(“demo”).innerHTML = ‘The text in first paragraph (index 0) is:

‘ + element[0].innerHTML;

</script>

</body>

</html>

Looking at the example shown above, we have used a Tag Name. Now, let’s see

how the same example works if we add the getElementById() method.

– Adding GetElementById() Method in the Example

From the second example, we will see interaction with ID and then with the Tag

Name:

<!DOCTYPE html>

<html>

<body>

<h2>HTML DOM Element</h2>

<div id=”main”>
<p>We are finding HTML Elements by Tag Name using ID</p>

<p></p>

</div>

<p id=”demo”></p>

<script>

const x = document.getElementById(“SampleID”);

const y = x.getElementsByTagName(“p”);

document.getElementById(“demo”).innerHTML =

‘The first paragraph (index 0) inside “SampleID” is: ‘ + y[0].innerHTML;

</script>

</body>

</html>

Class Name

Using the getElementByClassName would return us an object similar to an array.

This object will have hierarchical elements with the respective class names. Note the

following to get element by name in JavaScript:

• This method will search the complete document, even the root node.
• Only the descendent elements of the specified class names will return once
getElementByClassName() is called.
• Just like Tag Name, this is a live HTML collection as well; hence, any change will be updated
automatically in the array. Thus, extra care is needed to avoid repetition.

– Syntax of Class Name

We can use any of the two syntaxes for this method:


Syntax 1= var elements = document.getElementsByClassName(names);

Syntax 2= var elements = rootElement.getElementsByClassName(names);

– Example Using the Class Name Method

<!DOCTYPE html>

<html>

<body>

<h2>JavaScript HTML DOM Element</h2>

<p>We are finding HTML Elements using Class Name.</p>

<p class=”intro”>Sample text!</p>

<p class=”intro”></p>

<p id=”demo”></p>

<script>

const x = document.getElementsByClassName(“intro”);

document.getElementById(“demo”).innerHTML =

‘The first paragraph (index 0) with class=”intro” is: ‘ + x[0].innerHTML;

</script>

</body>

</html>

The example above would return all the elements of the “intro” class.

CSS Selectors

For CSS selectors, we will use the querySelector() method. This process brings us a
matching specified CSS selector from the document. Before implementing it yourself,

do note the following guidelines:

• To return other matches, we have to use the querySelectorAll() method because the querySelector()
method brings us only the first element.
• We have to be careful with using ID in our document because this methodwill return any element
that matches, even an ID.

– Parameters of QuerySelector

When working with CSS selectors, we must remember the following parameters:

A string is required in CSS selectors as it specifies the selectors while

matching the elements. These selectors use the JavaScript find element

according to the id, class name, type, and attributes.

If we are working with more selectors, a comma can be inserted to separate

the selectors in an organized manner. Still, the first element found would be

the result.

The string used with the selectors should be compatible with the CSS

selector. If not, a SyntaxError would be obvious.

Characters not related to the CSS syntax can be escaped by a backslash.

For a literal string, we must escape for the JavaScript string and then for

querySelector() as well.

Make sure the ID is not used more than once as the selector can return that

as the first element.

– Syntax of CSS Selector

element = document.querySelector(selectors);
– CSS Selector Examples

We will be seeing some examples using different practices to understand the CSS

selectors role with elements. Moreover, in the example below, we should get the

first element with the class:

<!DOCTYPE html>

<html>

<body>

<h2 class=”example”>A heading with class=”sample example”</h2>

<p class=”example”>A paragraph with class=”sample 2 example”.</p>

<p>We can add a background color to the first element with class.</p>

<button onclick=”myFunction()”>Click Here</button>

<script>

function myFunction() {

document.querySelector(“.example”).style.backgroundColor = “desired color”;

</script>

</body>

</html>

– Example: Getting a <P> Element

From this example, we will get the first <p> element:

<!DOCTYPE html>

<html>

<body>
<p>This is a p element.</p>

<p>This is also a p element.</p>

<p>We can add a background color to the first p element.</p>

<button onclick=”myFunction()”>Click Here</button>

<script>

function myFunction() {

document.querySelector(“p”).style.backgroundColor = “desired color”;

</script>

</body>

</html>

– Example: Getting a <P> Element With Class

Now, we will see an example where the first <p> element interacts with a class.

Let’s take a look:

<!DOCTYPE html>

<html>

<body>

<h2 class=”sample 1′′>A heading with class=”sample1′′</h2>

<p class=”sample 2′′>A paragraph with class=”sample2′′.</p>

<p>We can add a background color to the first p element with class.</p>

<button onclick=”myFunction()”>Click Here</button>

<script>

function myFunction() {
document.querySelector(“p.example”).style.backgroundColor = “desired color”;

</script>

</body>

</html>

– Example: Getting <A> Element

Let’s see how a target attribute within an <a> element works in the example as

follows:

<!DOCTYPE html>

<html>

<head>

<style>

a[target] {

background-color: desired color;

</style>

</head>

<body>

<p>The CSS selector a[target] ensures the desired color becomes the background of all

the targets.</p>

<a href=”http://samplewebsitelink.com”>samplewesbite.com</a>

<a href=”http://samplewebsitelink.com” target=”_blank”>samplewebsite.com</a>

<a href=”http://samplewebsite.org” target=”_top”>samplewebsite.org</a>


<p>The first link having a target attribute will get a border of desired color.</p>

<button onclick=”myFunction()”>Click Here</button>

<script>

function myFunction() {

document.querySelector(“a[target]”).style.border = “12px desired color”;

</script>

</body>

</html>

– Example: Multiple Selectors

We mentioned multiple selectors earlier, so now it’s time that we see a first-hand

example to further understand their application:

<!DOCTYPE html>

<html>

<body>

<h3>A h3 element</h3>

<h2>A h2 element</h2>

<script>

document.querySelector(“h2, h3”).style.backgroundColor = “desired color”;

</script>

</body>

</html>
In this code block, we took two elements (h3 and h2). The code adds the desired

background color to the first element specified. We must remember that whatever

element is placed first will get the background color. From the example above, we

have the h3 element that will get the background color.

HTML Object Collection

The last method to JavaScript find element uses forms collection to display the

element values. Let’s refer the following example:

<!DOCTYPE html>

<html>

<body>

<h2>JavaScript HTML DOM Element</h2>

<p>We are finding HTML Elements Using forms </b ></b>.</p>

<form id=”frm1′′ action=”/action_page.php”>

First name: <input type=”text” name=”fname” value=”Mr. Sample”><br>

Last name: <input type=”text” name=”lname” value=”Samples”><br><br>

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

</form>

<p>These are the values of each element in the form:</p>

<p id=”demo”></p>

<script>

const x = document.forms[“frm1”];

let text = “”;

for (let i = 0; i < x.length ;i++) {

text += x.elements[i].value + “<br>”;


}

document.getElementById(“demo”).innerHTML = text;

</script>

</body>

</html>

Unit – 2
1).Briefly explain the concept of XML document. Declaration and vocabularies with
suitable examples.

An XML document is a basic unit of XML information composed of elements and other

markup in an orderly package. An XML document can contains wide variety of data. For

example, database of numbers, numbers representing molecular structure or a mathematical

equation.

Syntax

Following syntax shows XML declaration –

Each parameter consists of a parameter name, an equals sign (=), and parameter value inside

a quote.

<?xml

version = "version_number"

encoding = "encoding_declaration"

standalone = "standalone_status"

?>
Rules

An XML declaration should abide with the following rules −

If the XML declaration is present in the XML, it must be placed as the first line in the

XML document.

If the XML declaration is included, it must contain version number attribute.

The Parameter names and values are case-sensitive.

The names are always in lower case.

The order of placing the parameters is important. The correct order is: version,

encoding and standalone.

Either single or double quotes may be used.

The XML declaration has no closing tag i.e. </?xml>

Versioning XML vocabularies

Versioning XML vocabularies is crucial to manage changes in the structure and semantics of

XML documents over time. Proper versioning helps ensure interoperability between systems

that exchange XML data, especially when updates or modifications are made to the XML

schema. Here are some common practices for versioning XML vocabularies:

1. Namespace Versioning:

Use XML namespaces to distinguish between different versions of the same

vocabulary. This involves assigning a unique namespace URI to each version.

For example, if you have a vocabulary called "MyVocabulary," version 1.0

might have a namespace URI like http://example.com/myvocabulary/v1, and

version 2.0 might have http://example.com/myvocabulary/v2.


2. Document Versioning:

Include a version attribute or element within the XML document to indicate its

version.

For example:

<MyVocabulary version="2.0">

<!-- XML content here -->

</MyVocabulary>

3. Backward Compatibility:

Ensure backward compatibility whenever possible. Newer versions of the XML

schema should be designed to accommodate the elements and attributes from

the previous versions to avoid breaking existing implementations.

4. Versioning in Schema Definition:

Clearly define version information within the XML schema itself. This can be

done through annotations or comments.

Use tools like XML Schema Definition (XSD) or Document Type Definition

(DTD) to formally define the structure and constraints of your XML documents.

5. Documentation:

Provide comprehensive documentation about changes between different

versions, including updates to elements, attributes, and their semantics.

Communicate changes to users and developers to ensure a smooth transition to

newer versions.

6. Deprecation:

When elements or attributes are no longer supported, mark them as deprecated

and provide information on alternative elements or attributes to use.


7. Validation and Parsing:

Develop XML parsers that can handle multiple versions of the XML schema.

Ensure that these parsers can adapt to changes without causing errors in older

documents.

8. Version Negotiation:

Implement a mechanism for systems to negotiate and agree on the version of the

XML schema they will use during data exchange.

9. Semantic Versioning:

Consider using semantic versioning (Major.Minor.Patch) for your XML

vocabularies. This convention helps convey the nature of changes (major, minor,

or patch) and is widely adopted in software versioning.

10.Testing:

Thoroughly test the XML schema and its compatibility with different versions.

This includes testing with real-world data and ensuring that the versioning

mechanisms are working as expected.

XML declaration

The XML declaration is a statement placed at the beginning of an XML document to provide

essential information about the document itself. It is an optional component, but when used,

it must appear before any other content in the document.

The XML declaration has the following general structure:

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


The components within the XML declaration:

1. <?xml: The XML declaration begins with this processing instruction.

2. version="1.0": Specifies the version of the XML specification to which the document

adheres. The version number is essential for parsers to interpret the document correctly.

The most commonly used version is "1.0."

3. encoding="UTF-8": Indicates the character encoding used in the XML document. It

specifies the mapping between characters and byte sequences. "UTF-8" is a widely

used encoding that supports a broad range of characters from different languages. Other

possible values include "UTF-16" and others.

4. standalone="yes" or standalone="no": This attribute indicates whether the XML

document is standalone or not. A standalone document is one that does not rely on

external entities for its complete interpretation. The value can be "yes" or "no."

-> If standalone="yes", it means the document is standalone.

-> If standalone="no", it means the document may rely on external entities.

The XML declaration is not required, but including it is good practice, especially when

specifying the character encoding. If the declaration is absent, XML parsers assume default

values (version 1.0 and UTF-8 encoding).

Example of an XML document with the XML declaration:

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

<root>

<element1>Value 1</element1>

<element2>Value 2</element2>

</root>
XML and its types

XSLT ,XPATH AND AJAX

XML vocabularies, declaration, namespace

2). Namespace Javascript

A namespace is a programming concept that gives identifiers (names of types, functions,

variables, etc.) scope to avoid name conflicts. For instance, a program may need to use the

same variable name in many contexts. In such a case, namespaces will separate these contexts

so that the same identifier may be utilized in many namespaces.

A namespace is not by default available in JavaScript. Constructing a global object that contains

all functions and variables, the JavaScript Namespace feature may be repeated. Because

numerous libraries and components are utilized in contemporary online applications, namespace

should be used to prevent misunderstanding in the code.

Namespace with Object Literal Notation

In this approach, we will use the Object Literal Notation.

In the Object Literal Notation, JavaScript namespaces can only be specified once, and

only within that namespace may function be written.

With a colon between each pair of keys and values, this may be compared to an object

with a collection of key-value pairs, where keys can also stand in for new namespaces.

The benefit of object literals is that they help properly organize code and arguments while

not contaminating the global namespace.

They are quite helpful if you want to design structures that can be extended to enable

deep layering and are easily readable.

Contrary to simple global variables, object literals frequently additionally consider checks

for the presence of a variable with the same name, considerably lowering the likelihood
of a collision.

Syntax

Initializing an empty Namespace is the first step −

Var <namespace> = { };

The namespace's variables can then be accessed by using −

<namespace>.<identifier>

Approach

We create an object named "student" and then declared two

functions getStudentName() and getStudentAddress() inside those.

Inside the getStudentName() function we have a variable that is initialized to the name

of the student and returns that.

Inside the getStudentAddress() function we have a variable that is initialized to the

address of the student and returns that.

Outside the object, we call these functions, and similarly each value is printed.

In this way, studentName and studentAddress are namespaced under

student: student.getStudentName() and student.getstudentAddress().

Example

</head>

<body>

<h2> Namespace with Object Literal Notation </h2>

<script>

var student = {

getStudentName: function() {

var studentName = "Vivek Kumar lives in ";


return studentName;

},

getstudentAddress: function() {

var studentAddress = "Kota, India";

return studentAddress;

};

document.write(student.getStudentName());

document.write(student.getstudentAddress());

</script>

</body>

</html>

Output:

Vivek Kumar lives in Kota, India

AJAX
AJAX is a technique for accessing web servers from a web page.

AJAX stands for Asynchronous JavaScript And XML.

AJAX = Asynchronous JavaScript And XML.

AJAX is not a programming language.

AJAX just uses a combination of:

A browser built-in XMLHttpRequest object (to request data from a web server)

JavaScript and HTML DOM (to display or use the data)

AJAX allows web pages to be updated asynchronously by exchanging data with a web
server behind the scenes. This means that it is possible to update parts of a web page,

without reloading the whole page.

1. An event occurs in a web page (the page is loaded, a button is clicked)

2. An XMLHttpRequest object is created by JavaScript

3. The XMLHttpRequest object sends a request to a web server

4. The server processes the request

5. The server sends a response back to the web page

6. The response is read by JavaScript

7. Proper action (like page update) is performed by JavaScript

AJAX Example & Explained

<!DOCTYPE html>

<html>

<body>

<div id="demo">

<h2>Let AJAX change this text</h2>

<button type="button" onclick="loadDoc()">Change Content</button>

</div>

</body>

</html>

The HTML page contains a <div> section and a <button>.

The <div> section is used to display information from a server.

The <button> calls a function (if it is clicked).

The function requests data from a web server and displays it


Selecting XML Data :XPATH

An XPath expression generally defines a pattern in order to select a set of nodes. These patterns are

used by XSLT to perform transformations or by XPointer for addressing purpose.

XPath specification specifies seven types of nodes which can be the output of execution of the

XPath expression.

Root

Element

Text

Attribute

Comment

Processing Instruction

Namespace

XPath uses a path expression to select node or a list of nodes from an XML document.

Following is the list of useful paths and expression to select any node/ list of nodes from an XML

document.

Expression & Description

1 node-name

Select all nodes with the given name "nodename"

2/

Selection starts from the root node

3 //

Selection starts from the current node that match the selection

4.
Selects the current node

5 ..

Selects the parent of the current node

6@

Selects attributes

7 Student

Example − Selects all nodes with the name "student"

8 class/student

Example − Selects all student elements that are children of class

9 //student

Selects all student elements no matter where they are in the document

Example

In this example, we've created a sample XML document, students.xml and its stylesheet

document students.xsl which uses the XPath expressions under select attribute of various XSL

tags to get the values of roll no, firstname, lastname, nickname and marks of each student node.

students.xml

<?xml version = "1.0"?>

<?xml-stylesheet type = "text/xsl" href = "students.xsl"?>

<class>

<student rollno = "393">

<firstname>Dinkar</firstname>

<lastname>Kad</lastname>

<nickname>Dinkar</nickname>
<marks>85</marks>

</student>

<student rollno = "493">

<firstname>Vaneet</firstname>

<lastname>Gupta</lastname>

<nickname>Vinni</nickname>

<marks>95</marks>

</student>

<student rollno = "593">

<firstname>Jasvir</firstname>

<lastname>Singh</lastname>

<nickname>Jazz</nickname>

<marks>90</marks>

</student>

</class>

students.xsl

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

<xsl:stylesheet version = "1.0"

xmlns:xsl = "http://www.w3.org/1999/XSL/Transform">

<xsl:template match = "/">

<html>

<body>

<h2>Students</h2>
<table border = "1">

<tr bgcolor = "#9acd32">

<th>Roll No</th>

<th>First Name</th>

<th>Last Name</th>

<th>Nick Name</th>

<th>Marks</th>

</tr>

<xsl:for-each select = "class/student">

<tr>

<td> <xsl:value-of select = "@rollno"/></td>

<td><xsl:value-of select = "firstname"/></td>

<td><xsl:value-of select = "lastname"/></td>

<td><xsl:value-of select = "nickname"/></td>

<td><xsl:value-of select = "marks"/></td>

</tr>

</xsl:for-each>

</table>

</body>

</html>

</xsl:template>

</xsl:stylesheet>
Displaying XML Using XSLT

XSLT stands for Extensible Stylesheet Language Transformation.

XSLT is used to transform XML document from one form to another form.

XSLT uses Xpath to perform matching of nodes to perform these transformation .

The result of applying XSLT to XML document could be an another XML document,

HTML, text or any another document from technology perspective.

The XSL code is written within the XML document with the extension of (.xsl).

In other words, an XSLT document is a different kind of XML document.

XML Namespace: XML Namespaces are the unique names .

XML Namespace is a mechanism by which element or attribute is assigned to a group.

XML Namespace is used to avoid the name conflicts in the XML document.

XML Namespace is recommended by W3C.

XML Namespace Declaration:

It is declared using reserved attribute such as the attribute is xmlns or it can begin

with xmlns:

Syntax:

<element xmlns:name = "URL">

Where

Namespace starts with the xmlns.

The word name is the namespace prefix.

the URL is the namespace identifier.

Example:
Consider the following xml document named Table.xml :-

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

<?xml-stylesheet type="text/css" href="rule.css"?>

<tables>

<table>

<tr>

<td>Apple</td>

<td>Banana</td>

</tr>

</table>

<table>

<height>100</height>

<width>150</width>

</table>

</tables>

AJAX - The XMLHttpRequest Object

All modern browsers support the XMLHttpRequest object.

The XMLHttpRequest object can be used to exchange data with a web server behind the

scenes. This means that it is possible to update parts of a web page, without reloading

the whole page.

Create an XMLHttpRequest Object


All modern browsers (Chrome, Firefox, IE, Edge, Safari, Opera) have a built -

in XMLHttpRequest object.

Syntax for creating an XMLHttpRequest object:

variable = new XMLHttpRequest();

Define a Callback Function

A callback function is a function passed as a parameter to another function.

In this case, the callback function should contain the code to execute when the response

is ready.

xhttp.onload = function() {

// What to do when the response is ready

Send a Request

To send a request to a server, you can use the open() and send() methods of

the XMLHttpRequest object:

xhttp.open("GET", "ajax_info.txt");

xhttp.send();

Example

// Create an XMLHttpRequest object

const xhttp = new XMLHttpRequest();

// Define a callback function

xhttp.onload = function() {

// Here you can use the Data

}
// Send a request

xhttp.open("GET", "ajax_info.txt");

xhttp.send();

XMLHttpRequest Object Methods

Method Description

new XMLHttpRequest() Creates a new XMLHttpRequest object

abort Cancels the current request

getAllResponseHeaders() Returns header information

getResponseHeader() Returns specific header information

open(method, url, async, user, Specifies the request

psw) method: the request type GET or POST

url: the file location

async: true (asynchronous) or false


(synchronous)

user: optional user name

psw: optional password


send() Sends the request to the server

Used for GET requests

send(string) Sends the request to the server.

Used for POST requests

setRequestHeader() Adds a label/value pair to the header to be sent

XMLHttpRequest Object Properties

Property Description

Onload Defines a function to be called when the request is received (loaded)

Onreadystatechange Defines a function to be called when the readyState property changes

readyState Holds the status of the XMLHttpRequest.

0: request not initialized

1: server connection established

2: request received

3: processing request

4: request finished and response is ready

responseText Returns the response data as a string


responseXML Returns the response data as XML data

Status Returns the status-number of a request

200: "OK"

403: "Forbidden"

404: "Not Found"

For a complete list go to the Http Messages Reference

statusText Returns the status-text (e.g. "OK" or "Not Found")

AJAX - Server Response

Server Response Properties

Property Description

responseText get the response data as a string

responseXML get the response data as XML data

The responseText Property

The responseText property returns the server response as a JavaScript string, and you

can use it accordingly:

document.getElementById("demo").innerHTML = xhttp.responseText;
The responseXML Property

The XMLHttpRequest object has an in-built XML parser.

The responseXML property returns the server response as an XML DOM object.

Using this property you can parse the response as an XML DOM object:

Request the file cd_catalog.xml and parse the response:

Example:

const xmlDoc = xhttp.responseXML;

const x = xmlDoc.getElementsByTagName("ARTIST");

let txt = "";

for (let i = 0; i < x.length; i++) {

txt += x[i].childNodes[0].nodeValue + "<br>";

document.getElementById("demo").innerHTML = txt;

xhttp.open("GET", "cd_catalog.xml");

xhttp.send();

Server Response Methods

Method Description

getResponseHeader() Returns specific header information from the server resource

getAllResponseHeaders() Returns all the header information from the server resource
The getAllResponseHeaders() Method

The getAllResponseHeaders() method returns all header information from the server

response.

const xhttp = new XMLHttpRequest();

xhttp.onload = function() {

document.getElementById("demo").innerHTML =

this.getAllResponseHeaders();

xhttp.open("GET", "ajax_info.txt");

xhttp.send();

The getResponseHeader() Method

The getResponseHeader() method returns specific header information from the server

response.

const xhttp = new XMLHttpRequest();

xhttp.onload = function() {

document.getElementById("demo").innerHTML =

this.getResponseHeader("Last-Modified");

xhttp.open("GET", "ajax_info.txt");

xhttp.send();
UNIT -3
1).Explain the types of selectors in JQuery with an example

jQuery selectors are used to select the HTML element(s) and allows you to manipulate

the HTML element(s) in a way we want. It selects the HTML elements on a variable

parameter such as their name, classes, id, types, attributes, attribute values, etc. All

selectors in jQuery are selected using a special sign i.e. dollar sign and parentheses:

1. jQuery * Selector

The jQuery * selector selects all the elements in the document, including HTML,

body, and head. If the * selector is used together with another element then it selects

all child elements within the element used.

Syntax:

$("*")

Parameters:

*: This parameter is used to select all elements.

2. jQuery #id Selector

The #id selector specifies an id for an element to be selected. It should not begin

with a number and the id attribute must be unique within a document which means it

can be used only one time.

Syntax:

$("#id")

Parameter:

id: An element’s specific id.

3. jQuery Multiple ID selectors

Given an HTML document and the task is to select the elements with different ID’s
at the same time using JQuery.

Approach:

Select the ID’s of different element and then use each() method to apply the CSS

property on all selected ID’s element.

Then use css() method to set the background color to pink to all selected

elements.

Display the text which indicates the multiple ID selectors.

4. jQuery .class Selector

The jQuery .class selector specifies the class for an element to be selected. It should

not begin with a number. It gives styling to several HTML elements.

Syntax:

$(".class")

Parameter:

class: This parameter is required to specify the class of the elements to be

selected.

5.jQuery multiple classes Selector

The jQuery multiple class selector is used to select multiple classes of an HTML

document.

Syntax:

$(".class1, .class2, .class3, ...")

Parameter:

class: This parameter is required to specify the class of the elements to be

selected.
6.jQuery element Selector

jQuery element selector is used to select and modify HTML elements based on the

element name.

Syntax:

$("element_name")

7.jQuery multiple elements Selector

The jQuery multiple elements Selector is used to select multiple elements of an

HTML document.

Syntax:

$("element1, element2, element3, ...")

Parameter:

element: This parameter is required to specify the elements to be selected.

8.jQuery :first Selector

The jQuery :first Selector is used to select the first element of the specified type.

Syntax:

$(":first")

9.jQuery :last Selector

The jQuery :last Selector is used to select the last element of the specified type.

Syntax:

$(":last")

10.jQuery :even Selector

The jQuery:even selector used to select an even number index from the elements.

The number of the index starts from 0. The working is the same as odd selectors but
for even numbers.

Syntax

$(":even")

11.jQuery :odd Selector

The jQuery :odd selector is used to select an odd number index from the elements.

The number of indexes starts from 0. The working is the same as :even selectors but

for odd numbers.

Syntax:

$(":odd")

12.jQuery :first-child Selector

jQuery :first-child Selector is used to select every element that is the first child of

its parent element.

Syntax:

$("selector:first-child")

It selects and returns the first child element of its parent element.

13.jQuery :first-of-type Selector

The jQuery :first-of-type Selector is used to select all elements that are the first

child, of a particular type, of their parent.

Syntax:

$(":first-of-type")

14.jQuery :last-child Selector

It is a jQuery Selector used to select every element that is the last child of its parent.

Syntax:

$(":last-child")
2 ).Briefly explain the AngularJS directives and expressions with suitable examples

Angularjs expressions:

AngularJS expressions can be written inside double braces: {{ expression }}.

AngularJS expressions can also be written inside a directive: ng-bind="expression".

AngularJS will resolve the expression, and return the result exactly where the

expression is written.

AngularJS expressions are much like JavaScript expressions: They can contain

literals, operators, and variables.

Example {{ 5 + 5 }} or {{ firstName + " " + lastName }}

Example

<!DOCTYPE html>

<html>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.

js"></script>

<body>

<div ng-app="">

<p>My first expression: {{ 5 + 5 }}</p>

</div>

</body>

</html>

AngularJS change the value of CSS properties.

<div ng-app="" ng-init="myCol='lightblue'">


<input style="background-color:{{myCol}}" ng-model="myCol">

</div>

AngularJS numbers

<div ng-app="" ng-init="quantity=1;cost=5">

<p>Total in dollar: {{ quantity * cost }}</p>

</div>

AngularJS numbers using ng-bind:

<div ng-app="" ng-init="quantity=1;cost=5">

<p>Total in dollar: <span ng-bind="quantity * cost"></span></p>

</div>

AngularJS strings

<div ng-app="" ng-init="firstName='John';lastName='Doe'">

<p>The name is {{ firstName + " " + lastName }}</p>

</div>

AngularJS strings using ng-bind:

<div ng-app="" ng-init="firstName='John';lastName='Doe'">

<p>The name is <span ng-bind="firstName + ' ' + lastName"></span></p>

</div>

AngularJS objects

<div ng-app="" ng-init="person={firstName:'John',lastName:'Doe'}">

<p>The name is {{ person.lastName }}</p>

</div>

AngularJS objects using ng-bind:

<div ng-app="" ng-init="person={firstName:'John',lastName:'Doe'}">


<p>The name is <span ng-bind="person.lastName"></span></p>

</div>

AngularJS arrays

<div ng-app="" ng-init="points=[1,15,19,2,40]">

<p>The third result is {{ points[2] }}</p>

</div>

AngularJS arrays using ng-bind:

<div ng-app="" ng-init="points=[1,15,19,2,40]">

<p>The third result is <span ng-bind="points[2]"></span></p>

</div>

AngularJS Directives:

AngularJS facilitates you to extend HTML with new attributes. These attributes are

called directives.

There is a set of built-in directive in AngularJS which offers functionality to your

applications. You can also define your own directives.

Directives are special attributes starting with ng- prefix. Following are the most common

directives:

AngularJS Directives

AngularJS directives are extended HTML attributes with the prefix ng-.

The ng-app directive initializes an AngularJS application.

The ng-init directive initializes application data.

The ng-model directive binds the value of HTML controls (input, select, textarea) to

application data.
The ng-repeat: This directive repeats html elements for each item in a collection.

ng-app directive

ng-app directive defines the root element. It starts an AngularJS Application and

automatically initializes or bootstraps the application when web page containing

AngularJS Application is loaded. It is also used to load various AngularJS modules in

AngularJS Application.

<div ng-app="" ng-init="firstName='John'">

<p>Name: <input type="text" ng-model="firstName"></p>

<p>You wrote: {{ firstName }}</p>

</div>

ng-init directive

ng-init directive initializes an AngularJS Application data. It defines the initial values for

an AngularJS application.

In following example, we'll initialize an array of countries. We're using JSON syntax to

define array of countries.

<div ng-app = "" ng-init = "countries = [

{locale:'en-IND',name:'India'},

{locale:'en-PAK',name:'Pakistan'},

{locale:'en-AUS',name:'Australia'}]">

</div>

ng-model directive:

ng-model directive defines the model/variable to be used in AngularJS Application.

The ng-model directive can also:


Provide type validation for application data (number, email, required).

Provide status for application data (invalid, dirty, touched, error).

Provide CSS classes for HTML elements.

Bind HTML elements to HTML forms.

In following example, we've defined a model named "name".

<div ng-app = "">

<p>Enter your Name: <input type = "text" ng-model = "name"></p>

</div>

ng-repeat directive

ng-repeat directive repeats html elements for each item in a collection. In following

example, we've iterated over array of countries.

<div ng-app="" ng-init="names=[

{name:'Jani',country:'Norway'},

{name:'Hege',country:'Sweden'},

{name:'Kai',country:'Denmark'}]">

<ul>

<li ng-repeat="x in names">

{{ x.name + ', ' + x.country }}

</li>

</ul>

</div>
3).Explain the different types of events available in JQuery with suitable examples

jQuery Event methods:

Event refers to the actions performed by the site visitor during their interactivity with

the website (or webpage).

There can be various types of events such as

1. User clicks on the button.

2. User moves mouse pointer over an image.

3. User pressed any key from keyboard, etc.

Some of the events methods are given

Method Name Description

click()

The click() method contains an function for event handling which gets invoked when the user clicks on the
particular HTML element.

Syntax:

$(selector).click(function);

dblclick()

The dblclick() method contains an function for event handling which gets invoked when the user double
clicks on the particular HTML element.

Syntax:
$(selector).dblclick(args);
mouseenter()

The mouseenter() method contains an function for event handling which gets invoked when mouse pointer
enters the particular HTML element.

Syntax:
$(selector).mouseenter(function)

mouseleave()

The mouseleave() method contains an function for event handling which gets invoked when mouse pointer
is removed from the particular HTML element which was selected earlier.

Syntax:
$(selector).mouseleave(function)

mousedown()

The mousedown() method contains an function for event handling which gets invoked when mouse left,
right or middle button is pressed while the mouse pointer is over the HTML element.

Syntax:
$(selector).mousedown(function)

mouseup()

The mouseup() method contains an function for event handling which gets invoked when mouse left, right
or middle button is released while the mouse pointer is over the HTML element. hover() The hover() method
contains an function for event handling which gets invoked when mouse pointer enter and leaves the HTML

element. It is a combination of mouseenter() and mouseleave() methods.


Syntax:
$(selector).mouseup(parameter)

Explain the concept of bootstrap grid system with different types of classes

Bootstrap Grid System

Bootstrap's grid system allows up to 12 columns across the page.

Bootstrap's grid system is responsive, and the columns will re-arrange depending on the

screen size: On a big screen it might look better with the content organized in three

columns, but on a small screen it would be better if the content items were stacked on top

of each other.

If you do not want to use all 12 column individually, you can group the columns together

to create wider columns:

Grid Classes

The Bootstrap grid system has four classes:

xs (for phones - screens less than 768px wide)

sm (for tablets - screens equal to or greater than 768px wide)

md (for small laptops - screens equal to or greater than 992px wide)

lg (for laptops and desktops - screens equal to or greater than 1200px wide)

The classes above can be combined to create more dynamic and flexible layouts.

Tip: Each class scales up, so if you wish to set the same widths for xs and sm, you only

need to specify xs.

Grid System Rules

Some Bootstrap grid system rules:


Rows must be placed within a .container (fixed-width) or .container-fluid (full-

width) for proper alignment and padding

Use rows to create horizontal groups of columns

Content should be placed within columns, and only columns may be immediate

children of rows

Predefined classes like .row and .col-sm-4 are available for quickly making grid

layouts

Columns create gutters (gaps between column content) via padding. That padding

is offset in rows for the first and last column via negative margin on .rows

Grid columns are created by specifying the number of 12 available columns you

wish to span. For example, three equal columns would use three .col-sm-4

Column widths are in percentage, so they are always fluid and sized relative to

their parent element

Basic Structure of a Bootstrap Grid

The following is a basic structure of a Bootstrap grid:

<div class="container">

<div class="row">

<div class="col-*-*"></div>

<div class="col-*-*"></div>

</div>

<div class="row">

<div class="col-*-*"></div>

<div class="col-*-*"></div>

<div class="col-*-*"></div>
</div>

<div class="row">

...

</div>

</div>

So, to create the layout you want, create a container (<div class="container">). Next,

create a row (<div class="row">). Then, add the desired number of columns (tags with

appropriate .col-*-* classes). Note that numbers in .col-*-* should always add up to

12 for each row.

Grid Options

The following table summarizes how the Bootstrap grid system works across multiple

devices:

Bootstrap Grid Example: Stacked-to-horizontal

We will create a basic grid system that starts out stacked on extra small devices, before

becoming horizontal on larger devices.

The following example shows a simple "stacked-to-horizontal" two-column layout,

meaning it will result in a 50%/50% split on all screens, except for extra small screens,

which it will automatically stack (100%):

Example: Stacked-to-horizontal

<div class="container">

<h1>Hello World!</h1>

<div class="row">

<div class="col-sm-6" style="background-color:yellow;">


<p>Lorem ipsum...</p>

</div>

<div class="col-sm-6" style="background-color:pink;">

<p>Sed ut perspiciatis...</p>

</div>

</div>

</div>

Bootstrap Grid - Small Devices

Assume we have a simple layout with two columns. We want the columns to be split

25%/75% for small devices.

Tip: Small devices are defined as having a screen width from 768 pixels to 991 pixels.

For small devices we will use the .col-sm-* classes.

We will add the following classes to our two columns:

The following example will result in a 25%/75% split on small (and medium and large)

devices. On extra small devices, it will automatically stack (100%):

Bootstrap Grid - Medium Devices

But on medium devices the design may be better as a 50%/50% split.

Tip: Medium devices are defined as having a screen width from 992 pixels to 1199

pixels.

For medium devices we will use the .col-md-* classes.

Now we will add the column widths for medium devices:


Bootstrap Grid - Large Devices

But on large devices the design may be better as a 33%/66% split.

Tip: Large devices are defined as having a screen width from 1200 pixels and above.

For large devices we will use the .col-lg-* classes.

So now we will add the column widths for large devices

Demonstrate and explain DOM in Client side scripting

UNIT – 4

1).Explain the different types of form validation used in PHP

PHP Form Handling

We can create and use forms in PHP. To get form data, we need to use PHP superglobals $_GET and

$_POST.

The form request may be get or post. To retrieve data from get request, we need to use $_GET, for post

request $_POST.

PHP Get Form

Get request is the default form request. The data passed through get request is visible on the URL

browser so it is not secured. You can send limited amount of data through get request.

Let's see a simple example to receive data from get request in PHP.

File: form1.html

<form action="welcome.php" method="get">

Name: <input type="text" name="name"/>

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

</form>
File: welcome.php

<?php

$name=$_GET["name"];//receiving name field value in $name variable

echo "Welcome, $name";

?>

PHP Post Form

Post request is widely used to submit form that have large amount of data such as file upload, image

upload, login form, registration form etc.

The data passed through post request is not visible on the URL browser so it is secured. You can send

large amount of data through post request.

Let's see a simple example to receive data from post request in PHP.

File: form1.html

<form action="login.php" method="post">

<table>

<tr><td>Name:</td><td> <input type="text" name="name"/></td></tr>

tr><td>Password:</td><td> <input type="password" name="password"/></td></tr>

<tr><td colspan="2"><input type="submit" value="login"/> </td></tr>

</table>

</form>

File: login.php

<?php

$name=$_POST["name"];//receiving name field value in $name variable

$password=$_POST["password"];//receiving password field value in $password variable

echo "Welcome: $name, your password is: $password";


?>

Output:

2).Discuss the usage of include and require statement in PHP

The ‘include’ (or require) statement copies all of the text, code, and mark-up from the

defined file into the include statement's target file. When you want to use the

same PHP, HTML, or text on different pages of a website, including files comes in

handy.

Include in PHP helps one build various functions and elements that can be reused

through several pages. Scripting the same feature through several pages takes time

and effort. This can be avoided if we adopt and use the file inclusion principle, which

allows us to combine several files, such as text or codes, into a single program,

saving time and effort.

PHP Include helps to include files in various programs and saves the effort of writing

code multiple times. If we want to change a code, rather than editing it in all of the

files, we can simply edit the source file, and all of the codes will be updated

automatically. There are two features that assist us in incorporating files in PHP.

1. include

2. require

Include Statement

The ‘include’ or ‘require’ statement can be used to insert the content of one PHP file into

another PHP file (before the server executes it). Except in the case of failure, the ‘include’

and ‘require statements’ are identical:


Include in PHP will only generate an alert (E_WARNING), and the script will proceed.

Require will produce a fatal error (E_COMPILE_ERROR) and interrupt the script.

If the include statement appears, execution should continue and show users the output even

if the include file is missing. Otherwise, always use the required declaration to include the

main file in the flow of execution while coding Framework, CMS, or a complex PHP

program. This will help prevent the application's protection and reputation from being

jeopardized if one key file is corrupted.

The include() function copies all of the text from a given file into the file that uses the

include function. It produces an alert if there is a problem loading a file; however, the script

will still run.

Advantages of Include () in PHP

Code Reusability: We may reuse HTML code or PHP scripts in several PHP scripts with

the aid of the ‘include’ and ‘require’ build.

Easy to Edit: If you want to alter anything on a website, you can modify the source file

used with all of the web pages rather than editing each file individually.

PHP Include

Include is a keyword to include one PHP file into another PHP file. While including

the content of the included file will be displayed in the main file. The below

example code will demonstrate the concept of PHP include.

Syntax:

include 'file_name';
or

require 'file_name';

Code:

Page1.php

<?php

echo "<p>welcome to my webpage</p>";

?>

Main.php

<html>

<body>

<h1>Welcome to my home page!</h1>

<p>Some text.</p>

<p>Some more text.</p>

<?php include 'Page1.php';?>

</body>

</html>

PHP Require

The PHP require function is similar to the include function, which is used to include

files. The only difference is that if the file is not found, it prevents the script from

running, while include does not.

The require() function copies all of the text from a given file into the file that uses the
include function. The require() function produces a fatal error and stops the script's

execution if there is a problem loading a file. So, apart from how they treat error

conditions, require() and include() are identical. Since scripts do not execute if files

are missing or misnamed, the require() function is recommended over include().

Syntax:

require 'file_name';

Or

require ('file_name');

Code:

Menu1.html:

<html>

<body>

<ahref="http://www.google.com">Google</a> |

<ahref="http://www.yahoo.com">Yahoo</a> |

<ahref="http://www.maps.com">Maps</a> |

<ahref="http://www.tutorial.com">Tutorial</a>

</body>

</html>

Main.html:

<html>

<body>
<h1>welcome</h1>

<?php require("menu1.html"); ?>

</body>

</html>

Explain the concept of how to create and use forms in PHP

Breifly Explain the $_get and $_Post superglobal arrays in PHP


$_GET and $_POST in PHP
In PHP, superglobals are built-in global arrays that provide access to certain data types, such as form
inputs, session data, and URL parameters. Among the most commonly used superglobals in web
development are $_GET and $_POST. These superglobals are used to collect data from HTML forms and
URLs.
In this article, we will explore what $_GET and $_POST are, how they work, and their use cases in PHP
programming.
What is $_GET ?
The $_GET superglobal is used to collect form data sent via the GET method. This method appends data
to the URL as query parameters, which are visible to users in the browser’s address bar. Some of the
features of the $_GET are:
• Retrieves data sent to the server as part of the URL query string.
• Useful for retrieving data that is visible to the user, such as search queries or parameters in a
URL.
• Data sent via $_GET is visible in the URL, making it less secure for sensitive information.
• Accessed using associative array notation, e.g., $_GET['parameter'].
Syntax:
<?php
echo $_GET['username']; // Outputs the value of the 'username' parameter from the URL
?>
Now, let us understand with the help of the example:
<html>
<body>
<form action="index.php" method="get">
<label>username:</label><br>
<input type="text" name="username"><br>
<input type="submit" value="Log in"><br>
</form>
</body>
</html>
<?php
echo "{$_GET["username"]} <br>" ;
?>
Output

$_GET Superglobals

In this example:
• A form asks the user for a username and submits it via the GET method to index.php.
• The form submits the data to the same page (index.php), allowing the same script to process
the data.
• The form includes a text input field for the username.
• The submit button sends the form data when clicked.
• After submission, PHP retrieves and displays the entered username using $_GET['username'].
• Since the form uses the GET method, the form data (like the username) is appended to the URL
as query parameters (e.g., index.php?username=anjali), making the username visible in the
browser’s URL bar.
What is $_POST?
The $_POST superglobal is used to collect form data sent via the POST method. Unlike GET, the POST
method sends data in the body of the HTTP request, so the data is not visible in the URL. Some of the
features of the $_POST are:
• Retrieves data sent to the server in the body of an HTTP request, typically from HTML forms
submitted using the POST method.
• Suitable for handling sensitive or large amounts of data as it's not visible in the URL.
• More secure than $_GET for handling sensitive information like passwords.
• Accessed using associative array notation, e.g., $_POST['field_name'].
Syntax:
<?php
echo $_POST['username']; // Outputs the value of the 'username' parameter submitted via POST
?>
Now, let us understand with the help of the example:
<html>
<body>
<form action="index.php" method="post">
<label>username:</label><br>
<input type="text" name="username"><br>
<input type="submit" value="Log in"><br>
</form>
</body>
</html>
<?php
echo "{$_POST["username"]} <br>" ;
?>
Output
$_POST Superglobals

In this example:
• A form asks the user for a username and submits it via the POST method to index.php.
• The form submits the data to the same page (index.php), ensuring the data is processed on the
same script.
• The form includes a text input field for the username.
• The submit button sends the form data when clicked.
• After submission, PHP retrieves and displays the entered username using $_POST['username'].
• Since the form uses the POST method, the form data is sent in the HTTP request body, not in
the URL, so the username is not visible in the URL bar.
When to Use $_GET and $_POST
Use $_GET:
• For data like search terms or filter criteria that don't need security.
• Best for short data (due to URL length limits).
• Useful when you need to share or bookmark URLs with parameters (e.g., search queries).
• Typically used for retrieving data without modifying the server (e.g., reading data from a
database).
Use $_POST:
• Sensitive information (e.g., passwords, payment details) since it is not visible in the URL.
• Suitable for forms with larger data, such as file uploads.
• Use for submitting forms that change server-side data (e.g., registration forms).
• Prevents data from being cached or stored in browser history.
$_GET vs $_POST
Both $_GET and $_POST are superglobals in PHP used to collect form data, but they differ in how and
where the data is transmitted.
$_GET $_POST

Data is visible in the URL Data is hidden in the HTTP request body

Limited by URL length Can handle large data sizes

Not secure (data is visible) More secure, but still requires sanitization

List and explain types of PHP Error reporting

UNIT -5
1.Explain the Basic workflow prepared statement of mysql and its advantages

2.Explain the basic operation in Database in PHP using in mysql

3.Explain the difference between the MEAN STACK AND FULL STACK development

You might also like