0% found this document useful (0 votes)
13 views57 pages

Webd Qa

Uploaded by

kabirkaim2002
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)
13 views57 pages

Webd Qa

Uploaded by

kabirkaim2002
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/ 57

Unit 1:

1 Mark Answers:

1. What is the World Wide Web (WWW)?


The World Wide Web (WWW) is a system of interlinked hypertext documents and
multimedia content accessed via the internet using web browsers.
2. Define a web page.
A web page is a document or resource on the World Wide Web, typically written in
HTML, and accessed using a web browser.
3. What is the purpose of a home page?
A home page is the main page of a website that serves as the starting point for navigation
and provides an overview of the site's content.
4. Differentiate between a static and a dynamic website.
o Static website: Displays fixed content, and does not change unless manually
updated.
o Dynamic website: Displays content that changes dynamically based on user
interaction or server-side processing.
5. What is the role of a web browser?
A web browser is software used to retrieve, render, and display web pages and content
from the World Wide Web.
6. What is a client in client-server computing?
A client is a device or software application that requests resources or services from a
server in a client-server architecture.
7. Name any two client-side scripting languages.
o JavaScript
o VBScript
8. What is the function of a web server?
A web server stores, processes, and delivers web pages and resources to clients via the
internet using HTTP/HTTPS.
9. Define client-side scripting.
Client-side scripting refers to code executed in the web browser on the user’s device to
enhance interactivity, such as form validation or dynamic content updates.
10. What is a website?
A website is a collection of interlinked web pages and resources hosted on a server,
accessible through a unique URL.

3 Mark Answers:

1. Difference between a Home Page and a Web Page:


o A home page is the main entry point or starting page of a website, typically
containing links to other sections of the site. It often serves as a summary or a
navigation hub.
o A web page is any individual page of a website that contains content like text,
images, or other media. The home page is just one type of web page.
2. Static Website vs. Dynamic Website:
o A static website consists of fixed content and doesn't change unless manually
updated by the website owner. Example: A personal blog.
o A dynamic website displays content that changes based on user interactions,
server data, or other inputs. Example: Facebook or an e-commerce website.
3. Concept of Client-Server Computing:
o In client-server computing, the client is a device (such as a computer or
smartphone) that requests services or resources, while the server provides those
services or resources. The client and server communicate over a network.
4. Main Components of a Web Browser:
o A web browser consists of:
▪ User Interface (UI): The graphical part where users interact with the
browser.
▪ Rendering Engine: Displays content on the screen.
▪ Networking: Manages connections to the web.
▪ JavaScript Engine: Executes JavaScript code.
▪ Data Storage: Stores cookies and cache for faster browsing.
5. Client-Side Scripting vs. Server-Side Scripting:
o Client-side scripting is executed on the user's browser (e.g., JavaScript),
allowing real-time interaction without server communication.
o Server-side scripting is executed on the web server (e.g., PHP, Python), and the
server processes the request, returning the result to the client.
6. Key Differences between a Web Client and a Web Server:
o A web client is a device (like a browser) that requests resources from the server.
o A web server is a system that stores and delivers content to clients over the web
when requested.
7. Importance of the World Wide Web:
o The World Wide Web (WWW) is a global network of interconnected websites
that provide access to information, entertainment, communication, and services,
revolutionizing how people access and share data.
8. How Scripting Languages Enhance Website Functionality:
o Scripting languages (like JavaScript) allow websites to be interactive by
handling user input, updating content dynamically, validating forms, creating
animations, and making websites responsive to users.
9. Web Site and Its Types:
o A website is a collection of web pages, accessible via the internet, that are
grouped under a common domain name.
o Types of websites:
▪ Static Website: Fixed content, doesn't change.
▪ Dynamic Website: Content changes based on user interaction.
▪ E-commerce Website: For online shopping.
▪ Blog or Portfolio Website: For sharing personal content.
10. Role of a Server in Dynamic Websites:

• In dynamic websites, the server processes the request from the client, accesses the
database or other resources, and generates dynamic content (e.g., displaying personalized
information) before sending it back to the client.

5 Mark Answers:

1. Discuss the architecture of client-server computing with a diagram.

Client-server computing architecture consists of two primary entities: the client and the server.

• Client: This is the device or software application that requests services or resources. It
could be a web browser, mobile app, or desktop application.
• Server: This is the machine or application that provides services or resources to the
client, like hosting websites, handling data, or processing requests.

Diagram:

Client Server
(Browser) (Web Server)
| |
Request (HTTP) Response (HTML, CSS, JS)
| |
Web Browser Web Server

In this architecture, clients send requests to the server, and the server processes and returns the
appropriate responses.

2. Compare static and dynamic websites in detail, including advantages and


disadvantages of each.

• Static Websites: These websites have fixed content. The web pages are simple HTML
files served to the client without modification.
o Advantages:
▪ Faster loading times.
▪ Simpler to develop.
▪ Less resource-intensive.
o Disadvantages:
▪ Limited interactivity.
▪ Difficult to update; requires manual changes to each page.
• Dynamic Websites: These websites generate content dynamically, often using a backend
programming language like PHP or Python, pulling data from a database.
o Advantages:
▪ Greater interactivity and personalization.
▪ Easier to update content; changes can be made in the backend without
altering the frontend.
o Disadvantages:
▪ Slower loading times due to server-side processing.
▪ More complex to develop and maintain.

3. Explain how client-side and server-side scripting work together to deliver a


dynamic web experience.

• Client-side scripting (e.g., JavaScript): This script runs in the user's browser and is
responsible for tasks like form validation, DOM manipulation, and interactive UI
elements.
• Server-side scripting (e.g., PHP, Node.js): This script runs on the server, processing data
and generating dynamic content that is sent to the client's browser.

Interaction: When a user interacts with a dynamic webpage, client-side scripts capture user
actions (like button clicks), and may send data to the server (e.g., via AJAX). The server then
processes the data, queries a database if necessary, and sends back a response, which is then
handled by the client-side script to update the page without needing a full reload.

4. Describe the components of the World Wide Web and their functions.

• Web Browser: Displays web content (e.g., Chrome, Firefox). It retrieves and presents
data to the user.
• Web Server: Hosts websites and responds to client requests (e.g., Apache, Nginx).
• Web Page: The document displayed by the browser, usually written in HTML.
• URL (Uniform Resource Locator): The address that specifies the location of a resource
on the web.
• Hyperlinks: Allow navigation between different web pages.
• HTTP/HTTPS: Protocols that define how requests and responses are structured on the
web.

5. How does a web browser communicate with a web server? Explain the
process.

1. The user enters a URL in the web browser.


2. The browser looks up the IP address of the web server using DNS (Domain Name
System).
3. The browser sends an HTTP request to the server for the requested resource (web page).
4. The web server processes the request and sends an HTTP response with the requested
content (HTML, images, etc.).
5. The browser renders the content and displays the web page to the user.

6. Write a detailed note on the differences between a web page, home page, and
website.

• Web Page: A single document on the web, usually consisting of HTML, CSS, and media
files. It is typically part of a larger website.
• Home Page: The main or introductory page of a website. It is often the first page users
see when visiting a site.
• Website: A collection of related web pages and resources, organized under a common
domain, providing a specific service or content.

7. What is the role of client-side scripting languages like JavaScript in modern


web development?

JavaScript is a client-side scripting language used to create interactive and dynamic web pages. It
enables:

• Dynamic content updates without reloading the page.


• Form validation and error handling before data is sent to the server.
• Animation, user interface manipulation, and responsive design.
• Fetching data from servers via AJAX for a seamless user experience.

8. How do web servers handle requests from web clients? Explain with an
example.

When a web server receives a request from a client, it processes the request and responds
accordingly. For example:

1. A user requests a webpage (e.g., example.com/index.html).


2. The server locates the HTML file on its storage and sends it to the client's browser.
3. The browser then renders the page for the user to see.

If the request involves server-side processing (e.g., querying a database), the server might run a
script (like PHP), fetch data from the database, and send the resulting dynamic content back to
the client.
9. Explain the importance of scripting languages in creating interactive and
responsive websites.

Scripting languages (like JavaScript, PHP, Python) enable interactivity on websites by:

• Allowing real-time updates and modifications of the webpage.


• Facilitating user interaction (forms, buttons, mouse movements).
• Supporting dynamic content loading (AJAX, API calls).
• Enabling animations and transitions that make websites visually appealing and engaging.

10. Illustrate the working of a dynamic website, highlighting the interaction


between the client, server, and database.

1. Client Request: The user requests a dynamic page (e.g., example.com/profile).


2. Server-side Script Execution: The web server runs a script (e.g., PHP) that interacts
with a database (e.g., MySQL) to fetch personalized data (e.g., user profile).
3. Server Response: The server processes the data, combines it with HTML templates, and
sends a dynamic webpage back to the client.
4. Client-side Rendering: The browser receives the page, renders it, and may use client-
side scripts (JavaScript) for further interactivity or updates without refreshing the page.

Unit 2:

1 Mark Answers:

1. What does HTML stand for?


HTML stands for HyperText Markup Language.
2. Write the syntax for adding a comment in HTML.
<!-- This is a comment -->
3. What is the purpose of the <a> tag in HTML?
The <a> tag is used to create hyperlinks that link to another page, file, or location.
4. Name two types of lists in HTML.
o Ordered list (<ol>)
o Unordered list (<ul>)
5. Which HTML tag is used to insert an image?
The <img> tag is used to insert an image.
6. What is a meta tag in HTML?
A meta tag provides metadata about an HTML document, such as keywords,
description, author, and viewport settings.
7. Define character entities in HTML.
Character entities are special characters represented in HTML by a unique code, like
&amp; for & or &lt; for <.
8. What is the difference between <frameset> and <frame> tags?
o <frameset> defines a layout for frames in the browser window.
o <frame> specifies the content for each frame within the <frameset>.
9. Which attribute is used to set the background color in HTML?
The bgcolor attribute is used to set the background color.
10. What is the full form of XHTML?
XHTML stands for Extensible HyperText Markup Language.

3 Mark Answers:

1. HTML Comments Example:


o HTML comments are used to add notes or remarks in the code that are not
displayed in the browser. They help in documentation and debugging.
o Example:

<!-- This is a comment in HTML -->


<p>This is visible text</p>

2. Difference between Ordered and Unordered Lists in HTML:


o Ordered List (<ol>): A list where the items are numbered.

<ol>
<li>First item</li>
<li>Second item</li>
</ol>

o Unordered List (<ul>): A list where the items are bullet points.

<ul>
<li>First item</li>
<li>Second item</li>
</ul>

3. How Hyperlinks are Created in HTML:


o Hyperlinks are created using the <a> tag with the href attribute to specify the
destination URL.
o Example:

<a href="https://www.example.com">Click here</a>

4. Structure of an HTML Form Example:


o HTML forms are used to collect user input. The <form> tag contains various input
elements like text fields, checkboxes, and buttons.
o Example:

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


<label for="name">Name:</label>
<input type="text" id="name" name="name">
<input type="submit" value="Submit">
</form>

5. Meta Tags in HTML and Their Importance:


o Meta tags provide metadata about the HTML document, such as character
encoding, author information, and viewport settings.
o Example:

<meta charset="UTF-8">
<meta name="description" content="A website about cats">

o Importance:
▪ They improve SEO, control document behavior, and specify character
sets.
6. Use of the <table> Tag with Example:
o The <table> tag is used to create a table. It can contain <tr> for rows, <th> for
headers, and <td> for data cells.
o Example:

<table border="1">
<tr>
<th>Header 1</th>
<th>Header 2</th>
</tr>
<tr>
<td>Data 1</td>
<td>Data 2</td>
</tr>
</table>

7. Character Entities in HTML:


o Character entities are used to represent special characters that cannot be directly
written in HTML, such as <, >, and &.
o Example:

&lt; <!-- Represents < -->


&gt; <!-- Represents > -->
&amp; <!-- Represents & -->

8. Role of Frames and Framesets in HTML:


o Frames allow multiple HTML pages to be displayed within the same window. A
frameset defines how the window is divided.
o Example:

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


<frame src="page1.html">
<frame src="page2.html">
</frameset>

o Note: <frameset> and <frame> are deprecated in HTML5, and it's recommended
to use <iframe> instead.
9. Adding Images to an HTML Document:
o Images are added using the <img> tag with the src (source) attribute to specify
the image location and alt (alternative text) for accessibility.
o Example:

<img src="image.jpg" alt="A description of the image">

10. Comparison of XHTML and HTML:


o XHTML is a stricter version of HTML that follows XML rules. It requires all
tags to be properly nested and closed, and attribute names must be in lowercase.
o HTML is more lenient and allows for self-closing tags, unquoted attributes, and
case-insensitive tag names.
o Example of XHTML:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>XHTML Page</title>
</head>
<body>
<h1>Welcome</h1>
</body>
</html>

5 Mark Questions

1. Write an HTML document to demonstrate the use of formatting tags and


fonts.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Formatting Tags and Fonts</title>
</head>
<body>
<h1>HTML Formatting Example</h1>
<p>This is a <b>bold</b> text, <i>italic</i> text, and <u>underlined</u>
text.</p>
<p style="font-family: Arial, sans-serif; font-size: 18px;">This is text
with a custom font family and size.</p>
<p style="font-family: 'Times New Roman', serif; color: blue;">This is a
paragraph with Times New Roman font and blue color.</p>
</body>
</html>

2. Explain the steps to create a table in HTML, including attributes for rows,
columns, and borders.

To create a table in HTML:

1. Use the <table> tag to define the table.


2. Define each row with the <tr> tag.
3. Define the header cells within the row using the <th> tag.
4. Define the data cells within the row using the <td> tag.
5. Add the border attribute to the <table> tag to make borders visible.

Example:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Table Example</title>
</head>
<body>
<table border="1">
<tr>
<th>Header 1</th>
<th>Header 2</th>
</tr>
<tr>
<td>Row 1, Column 1</td>
<td>Row 1, Column 2</td>
</tr>
<tr>
<td>Row 2, Column 1</td>
<td>Row 2, Column 2</td>
</tr>
</table>
</body>
</html>

3. Discuss the various input types supported in HTML forms with examples.

HTML forms support various <input> types for gathering different kinds of data:

• text: Used for single-line text input.


• password: Used for password fields, obscures input.
• email: For email addresses, with built-in validation.
• number: For numeric input.
• radio: For single choice options.
• checkbox: For multiple choice options.
• submit: A button to submit the form.

Example:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form Inputs</title>
</head>
<body>
<form>
<label for="name">Name:</label>
<input type="text" id="name" name="name"><br><br>

<label for="password">Password:</label>
<input type="password" id="password" name="password"><br><br>

<label for="email">Email:</label>
<input type="email" id="email" name="email"><br><br>

<label for="age">Age:</label>
<input type="number" id="age" name="age"><br><br>

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


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

4. Write an HTML code to create a navigation bar using hyperlinks.


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Navigation Bar</title>
<style>
nav {
background-color: #333;
overflow: hidden;
}
nav a {
float: left;
display: block;
color: white;
text-align: center;
padding: 14px 20px;
text-decoration: none;
}
nav a:hover {
background-color: #ddd;
color: black;
}
</style>
</head>
<body>
<nav>
<a href="#home">Home</a>
<a href="#services">Services</a>
<a href="#about">About</a>
<a href="#contact">Contact</a>
</nav>
</body>
</html>

5. Explain the structure and purpose of meta tags with examples of common
attributes like name and content.

Meta tags provide metadata about an HTML document. They are placed in the <head> section of
the document and help browsers, search engines, and other services understand the content.

Common attributes:

• name: Specifies the name of the meta information (e.g., "description", "keywords").
• content: Provides the value for the specified meta name.

Example:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="description" content="This is a description of the webpage.">
<meta name="keywords" content="HTML, meta tags, web development">
<meta name="author" content="John Doe">
<meta http-equiv="refresh" content="30">
<title>Meta Tags Example</title>
</head>
<body>
<h1>Using Meta Tags</h1>
</body>
</html>

6. How can you create a web page using frames and framesets? Provide an
example.

Frames and framesets allow you to display multiple HTML documents within one web page.
• Use <frameset> instead of <body> to define the structure.
• Use <frame> to define each individual frame.

Example:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Frameset Example</title>
</head>
<body>
<frameset cols="25%, 75%">
<frame src="left.html" name="leftFrame">
<frame src="right.html" name="rightFrame">
</frameset>
</body>
</html>

Note: Frames are deprecated in HTML5 in favor of more modern layout techniques.

7. Discuss the key features of the latest version of HTML (HTML5).

Key features of HTML5 include:

• Semantics: New semantic elements like <article>, <section>, <header>, <footer>,


<nav>, and <aside>.
• Multimedia Support: Native support for audio (<audio>) and video (<video>)
elements.
• Form Elements: New form input types like date, email, and range.
• Canvas: The <canvas> element allows for dynamic graphics and animations.
• Offline Storage: Web Storage API for storing data offline using localStorage and
sessionStorage.
• APIs: New APIs for Geolocation, Web Workers, and WebSockets.

8. Write an HTML document demonstrating the use of images, hyperlinks, and


lists on a single page.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Images, Links, and Lists</title>
</head>
<body>
<h1>HTML Elements Example</h1>

<h2>Image</h2>
<img src="example.jpg" alt="Example Image" width="300">

<h2>Links</h2>
<a href="https://www.example.com" target="_blank">Visit Example
Website</a>

<h2>List</h2>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
</body>
</html>

9. Explain how character entities are used in HTML. Provide examples for at
least five entities.

Character entities are used in HTML to represent special characters that would otherwise be
interpreted as HTML code.

Examples:

• &lt; for < (less than sign)


• &gt; for > (greater than sign)
• &amp; for & (ampersand)
• &quot; for " (double quotation mark)
• &copy; for © (copyright symbol)

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Character Entities</title>
</head>
<body>
<p>Use &lt; for less than and &gt; for greater than.</p>
<p>Display &amp; for the ampersand symbol.</p>
<p>&quot;Quotes&quot; in HTML.</p>
<p>&copy; 2025 Example Corp.</p>
</body>
</html>

10. Compare HTML and XHTML in terms of syntax rules, features, and usage.
• HTML:
o Less strict syntax.
o Tags do not need to be closed in some cases (e.g., <li>, <br>).
o Attribute values are not always required to be quoted.
• XHTML:
o More strict syntax.
o Tags must be properly closed.
o All attributes must have quoted values.
o It must be served with the MIME type application/xhtml+xml.

Usage: HTML is more commonly used in modern web development, while XHTML is used in
applications requiring stricter standards or backward compatibility.

Unit 3:

1 Mark Answers:

1. What does CSS stand for?


CSS stands for Cascading Style Sheets.

2. Write the syntax for including an external CSS file in an HTML document.
<link rel="stylesheet" href="styles.css">

3. What is the purpose of the background-color property in CSS?


The background-color property is used to set the background color of an element.

4. Name any two types of CSS.

○ Inline CSS
○ External CSS
5. Which property is used to set the font size in CSS?
The font-size property is used to set the font size of text.

6. What is the function of the padding property in CSS?


The padding property adds space between the content of an element and its border.

7. Write the syntax for setting a border in CSS.


border: 1px solid black;

8. What is the difference between id and class in CSS?


○ id is used to select a unique element (e.g., #elementId), and it can only be
applied to one element.
○ class is used to select multiple elements (e.g., .className), and it can be
applied to multiple elements.
9. Which CSS property is used to align text to the center?
The text-align property is used to align text. To center it, use text-align: center;.

10. How do you apply inline CSS to an HTML element?


Inline CSS is applied using the style attribute within an HTML element.
Example: <p style="color: red;">This is a red text.</p>

3 Mark Questions:

1. Different Types of CSS (Inline, Internal, and External) with Examples:


o Inline CSS: CSS is applied directly within an HTML element using the style
attribute.

<p style="color: red;">This is a red paragraph.</p>

o Internal CSS: CSS is written inside the <style> tag within the <head> section of
the HTML document.

<style>
p {
color: blue;
}
</style>
<p>This is a blue paragraph.</p>

o External CSS: CSS is stored in a separate .css file and linked to the HTML file
using the <link> tag.

<link rel="stylesheet" href="styles.css">


<p>This is styled by an external CSS file.</p>

2. CSS for Setting Background Images:


o You can set background images using the background-image property in CSS.
o Example:

body {
background-image: url('background.jpg');
background-size: cover; /* Ensures the image covers the entire
background */
}

3. The Box Model in CSS:


o The box model describes the rectangular boxes generated for elements in the
document layout. It consists of the following components:
▪ Content: The actual content of the element, like text or images.
▪ Padding: The space between the content and the border.
▪ Border: A border surrounding the padding (optional).
▪ Margin: The space outside the border, separating elements from each
other.
4. CSS to Style Text with Specific Font, Size, and Color:
o Example:

p {
font-family: 'Arial', sans-serif;
font-size: 16px;
color: #333333;
}

5. Difference Between Margin and Padding with Example:


o Margin: The space outside the element's border, creating distance between it and
other elements.
o Padding: The space inside the element's border, around the content.
o Example:

div {
margin: 20px; /* space outside the element */
padding: 10px; /* space inside the element */
}

6. Styling a Table Using CSS:


o Example:

table {
width: 100%;
border-collapse: collapse; /* Makes borders collapse into a
single line */
}
th, td {
border: 1px solid black;
padding: 10px;
text-align: center;
}
tr:nth-child(even) {
background-color: #f2f2f2; /* Zebra striping effect */
}

7. Purpose and Usage of the Position Property in CSS:


o The position property controls the positioning of an element on the page.
▪ static (default): The element follows the normal document flow.
▪ relative: The element is positioned relative to its normal position.
▪ absolute: The element is positioned relative to the nearest positioned
ancestor.
▪ fixed: The element is positioned relative to the browser window and stays
in place when scrolling.
▪ sticky: The element is treated as relative until it reaches a certain scroll
position, then it becomes fixed.
8. CSS to Style an Unordered List with Custom Bullet Points and Color:
o Example:

ul {
list-style-type: none; /* Removes default bullets */
}
ul li {
background: url('custom-bullet.png') no-repeat left center;
padding-left: 20px;
color: #444;
}

9. Creating Rounded Borders Using CSS:


o Example using the border-radius property:

div {
width: 200px;
height: 100px;
background-color: #4CAF50;
border-radius: 15px; /* Rounded corners */
}

10. Importance of Float and Clear Properties in CSS:


o Float: The float property is used to place an element on the left or right side of
its container, allowing text or inline elements to wrap around it.

img {
float: left;
margin-right: 10px;
}

o Clear: The clear property is used to prevent elements from floating beside a
floated element. It forces the element to move below the floated elements.

div {
clear: both;
}

5 Mark Questions:

1. Write a CSS code to style a web page with background images, colors, and
borders for different sections.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Styled Page</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
}

header {
background-image: url('header-bg.jpg');
background-size: cover;
color: white;
padding: 20px;
text-align: center;
}

section {
background-color: #f4f4f4;
padding: 20px;
margin: 10px;
border: 2px solid #ccc;
}

footer {
background-color: #333;
color: white;
text-align: center;
padding: 10px;
margin-top: 20px;
}
</style>
</head>
<body>
<header>
<h1>Welcome to My Web Page</h1>
</header>

<section>
<h2>Section 1</h2>
<p>This is the first section with a background color and border.</p>
</section>

<section>
<h2>Section 2</h2>
<p>This is the second section with a background color and border.</p>
</section>

<footer>
<p>&copy; 2025 My Website</p>
</footer>
</body>
</html>
2. Explain the CSS box model in detail with a diagram and an example.

The CSS box model defines how elements are structured on the page and consists of the
following parts:

1. Content: The actual content of the box (e.g., text, images).


2. Padding: The space between the content and the border.
3. Border: Surrounds the padding (if any) and content.
4. Margin: The space outside the border, creating space between elements.

Diagram:

lua
Copy code
+-----------------------------+
| Margin |
| +-----------------------+ |
| | Border | |
| | +-----------------+ | |
| | | Padding | | |
| | | +-----------+ | | |
| | | | Content | | | |
| | | +-----------+ | | |
| | +-----------------+ | |
| +-----------------------+ |
+-----------------------------+

Example:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Box Model Example</title>
<style>
.box {
width: 200px;
padding: 20px;
border: 5px solid black;
margin: 30px;
}
</style>
</head>
<body>
<div class="box">
This is a box with padding, border, and margin.
</div>
</body>
</html>
3. How can CSS be used to style text and fonts? Write a CSS code to demonstrate
various text and font properties.

CSS can style text using properties like font-family, font-size, font-weight, text-align,
line-height, and color.

Example:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Text and Font Styling</title>
<style>
h1 {
font-family: 'Arial', sans-serif;
font-size: 36px;
font-weight: bold;
text-align: center;
color: #2c3e50;
}

p {
font-family: 'Times New Roman', serif;
font-size: 18px;
line-height: 1.6;
color: #34495e;
}
</style>
</head>
<body>
<h1>Styled Heading</h1>
<p>This is a paragraph styled with different font properties such as
family, size, weight, and color.</p>
</body>
</html>

4. Discuss the difference between relative, absolute, fixed, and sticky positioning
in CSS with examples.

• Relative Positioning: The element is positioned relative to its normal position.


• Absolute Positioning: The element is positioned relative to its closest positioned
ancestor (other than static).
• Fixed Positioning: The element is positioned relative to the viewport and stays fixed
even when scrolling.
• Sticky Positioning: The element is positioned relative to its nearest scrolling ancestor,
and sticks to the top of the viewport when scrolling.

Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Positioning Example</title>
<style>
.relative {
position: relative;
top: 20px;
}

.absolute {
position: absolute;
top: 20px;
left: 50px;
}

.fixed {
position: fixed;
bottom: 10px;
right: 10px;
}

.sticky {
position: sticky;
top: 0;
background-color: #f1f1f1;
}
</style>
</head>
<body>
<div class="relative">This is a relatively positioned div.</div>
<div class="absolute">This is an absolutely positioned div.</div>
<div class="fixed">This is a fixed positioned div.</div>
<div class="sticky">This is a sticky positioned div.</div>
</body>
</html>

5. Write a CSS code to design a table with alternating row colors, borders, and
padding.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Styled Table</title>
<style>
table {
width: 100%;
border-collapse: collapse;
}
th, td {
padding: 10px;
text-align: left;
border: 1px solid #ddd;
}

tr:nth-child(even) {
background-color: #f2f2f2;
}

tr:nth-child(odd) {
background-color: #fff;
}
</style>
</head>
<body>
<table>
<tr>
<th>Header 1</th>
<th>Header 2</th>
</tr>
<tr>
<td>Row 1, Column 1</td>
<td>Row 1, Column 2</td>
</tr>
<tr>
<td>Row 2, Column 1</td>
<td>Row 2, Column 2</td>
</tr>
<tr>
<td>Row 3, Column 1</td>
<td>Row 3, Column 2</td>
</tr>
</table>
</body>
</html>

6. Explain how margins and paddings work in CSS with an example of nested
elements.

• Padding: The space between the content of an element and its border.
• Margin: The space outside an element's border, creating space between elements.

Example:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Margins and Padding</title>
<style>
.outer {
margin: 30px;
background-color: lightblue;
padding: 20px;
}

.inner {
margin: 15px;
background-color: lightgreen;
padding: 10px;
}
</style>
</head>
<body>
<div class="outer">
Outer Box
<div class="inner">Inner Box</div>
</div>
</body>
</html>

7. Write a CSS code to style an image gallery with hover effects using borders
and shadows.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Image Gallery</title>
<style>
.gallery {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 10px;
}

.gallery img {
width: 100%;
border: 2px solid #ccc;
transition: transform 0.3s, box-shadow 0.3s;
}

.gallery img:hover {
transform: scale(1.1);
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);
}
</style>
</head>
<body>
<div class="gallery">
<img src="image1.jpg" alt="Image 1">
<img src="image2.jpg" alt="Image 2">
<img src="image3.jpg" alt="Image 3">
</div>
</body>
</html>

8. How can CSS be used to style lists? Write a code to demonstrate styling
ordered and unordered lists differently.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Styled Lists</title>
<style>
ul {
list-style-type: square;
margin-left: 20px;
color: green;
}

ol {
list-style-type: decimal;
margin-left: 20px;
color: blue;
}
</style>
</head>
<body>
<h2>Unordered List</h2>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>

<h2>Ordered List</h2>
<ol>
<li>First</li>
<li>Second</li>
<li>Third</li>
</ol>
</body>
</html>

9. Discuss how the z-index property works in CSS. Provide an example involving
overlapping elements.

The z-index property controls the stacking order of elements. Higher values are displayed on
top of lower values.

Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>z-index Example</title>
<style>
.box1 {
position: absolute;
top: 50px;
left: 50px;
width: 200px;
height: 200px;
background-color: red;
z-index: 1;
}

.box2 {
position: absolute;
top: 100px;
left: 100px;
width: 200px;
height: 200px;
background-color: blue;
z-index: 2;
}
</style>
</head>
<body>
<div class="box1"></div>
<div class="box2"></div>
</body>
</html>

10. Write a complete CSS stylesheet to style a webpage with headings,


paragraphs, images, and navigation menus.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Complete Style</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
}

header {
background-color: #333;
color: white;
padding: 15px;
text-align: center;
}

nav {
background-color: #444;
overflow: hidden;
}

nav a {
float: left;
display: block;
color: white;
padding: 14px 16px;
text-align: center;
text-decoration: none;
}

nav a:hover {
background-color: #ddd;
color: black;
}

main {
padding: 20px;
}

h1, h2 {
color: #333;
}

p {
font-size: 16px;
line-height: 1.6;
}

img {
width: 100%;
max-width: 600px;
display: block;
margin: 0 auto;
}
</style>
</head>
<body>
<header>
<h1>My Website</h1>
</header>

<nav>
<a href="#home">Home</a>
<a href="#about">About</a>
<a href="#services">Services</a>
<a href="#contact">Contact</a>
</nav>

<main>
<h2>Welcome to My Website</h2>
<p>This is a paragraph of text on my website. Below is an image.</p>
<img src="image.jpg" alt="Sample Image">
</main>
</body>
</html>

Unit 4:

1 Mark Answers:

1. What is JavaScript?
JavaScript is a programming language used to create interactive effects and dynamic
content on web pages.
2. Name two data types supported in JavaScript.
o String
o Number
3. What is the purpose of the alert() function in JavaScript?
The alert() function is used to display a popup message to the user.
4. Which operator is used for strict equality in JavaScript?
The === operator is used for strict equality, which checks both value and type.
5. Write the syntax for a for loop in JavaScript.

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


// code to be executed
}

6. What is the typeof operator used for in JavaScript?


The typeof operator is used to determine the type of a variable or expression.
7. What is an event in JavaScript?
An event is an action or occurrence (such as a mouse click, keypress, or page load) that
can be detected by JavaScript to trigger a function.
8. Name one method to create a user-defined function in JavaScript.
A user-defined function can be created using the function keyword:

function myFunction() {
// code to be executed
}

9. What is the full form of DOM in JavaScript?


DOM stands for Document Object Model.
10. What is the console.log() function used for?
The console.log() function is used to output messages or variables to the browser’s
console for debugging purposes.
3 Mark Questions:

1. Basic Syntax of a JavaScript Function:


o A JavaScript function is defined using the function keyword, followed by the
function name, parentheses (which can contain parameters), and curly braces for
the function body.
o Example:

function greet(name) {
console.log("Hello, " + name + "!");
}
greet("Alice"); // Output: Hello, Alice!

2. Difference Between var, let, and const in JavaScript:


o var: Defines a variable that is function-scoped or globally scoped (if declared
outside a function). It can be redeclared and updated.

var x = 10;
x = 20; // Allowed

o let:Defines a block-scoped variable. It can be updated but not redeclared in the


same scope.

let y = 30;
y = 40; // Allowed

o const: Defines a block-scoped constant that cannot be reassigned. Once assigned


a value, it cannot be changed.

const z = 50;
z = 60; // Error: Assignment to constant variable.

3. Handling a Button Click Event Using JavaScript:


o A button click event can be handled by using the addEventListener method or
the onclick attribute.
o Example:

<button id="myButton">Click Me</button>


<script>
document.getElementById("myButton").addEventListener("click",
function() {
alert("Button was clicked!");
});
</script>

4. Difference Between == and === Operators in JavaScript:


o == (Equality Operator): Compares values for equality, performing type
conversion if necessary.

5 == '5'; // true

o === (Strict Equality Operator): Compares both the value and the type, without
type conversion.

5 === '5'; // false

5. Purpose of the prompt() Dialog Box in JavaScript:


o The prompt() method displays a dialog box that prompts the user for input. It
returns the input value or null if the user cancels.
o Example:

var userName = prompt("What is your name?");


console.log("Hello, " + userName); // If the user enters "Alice",
the output will be: "Hello, Alice"

6. JavaScript Program to Check if a Number is Even or Odd:

function checkEvenOdd(num) {
if (num % 2 === 0) {
console.log(num + " is even.");
} else {
console.log(num + " is odd.");
}
}
checkEvenOdd(4); // Output: 4 is even.
checkEvenOdd(7); // Output: 7 is odd.

7. Creating Objects in JavaScript:


o Objects in JavaScript can be created using the object literal syntax or the new
Object() syntax.
o Example:

var person = {
name: "John",
age: 30,
greet: function() {
console.log("Hello, " + this.name);
}
};
person.greet(); // Output: Hello, John

8. Browser Object Model (BOM) and Two BOM Objects:


o The Browser Object Model (BOM) provides a way to interact with the web
browser. It allows JavaScript to manipulate the browser window, document, and
more.
o Two objects of the BOM:
1. window: Represents the browser window and provides methods like
alert(), confirm(), and setTimeout().
2. navigator: Provides information about the browser, such as the user
agent and browser version.
9. Role of the if-else Statement in JavaScript:
o The if-else statement is used for conditional branching. It checks if a condition
is true or false, and executes different blocks of code based on the result.
o Example:

var age = 18;


if (age >= 18) {
console.log("You are an adult.");
} else {
console.log("You are a minor.");
}

10. JavaScript Form Validation Example for Email:


o JavaScript can be used to validate the email input field in a form before
submission.
o Example:

<form id="myForm">
<label for="email">Email:</label>
<input type="text" id="email" name="email">
<input type="submit" value="Submit">
</form>
<script>
document.getElementById("myForm").onsubmit = function(event) {
var email = document.getElementById("email").value;
var regex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-
Z]{2,6}$/;
if (!regex.test(email)) {
alert("Please enter a valid email.");
event.preventDefault(); // Prevent form submission
}
};
</script>

5 Mark Questions:

1. Write a JavaScript program that demonstrates the use of control statements


(if, for, and while).
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Control Statements Example</title>
</head>
<body>
<script>
// if statement
let age = 20;
if (age >= 18) {
console.log("You are an adult.");
} else {
console.log("You are a minor.");
}

// for loop
console.log("For loop output:");
for (let i = 1; i <= 5; i++) {
console.log(i);
}

// while loop
console.log("While loop output:");
let count = 1;
while (count <= 3) {
console.log(count);
count++;
}
</script>
</body>
</html>

2. Explain the Document Object Model (DOM) in detail with examples of


accessing and manipulating elements.

The Document Object Model (DOM) is a programming interface for HTML and XML
documents. It represents the structure of the document as a tree of objects where each object
corresponds to a part of the page (such as elements, attributes, and text).

Accessing elements:

let element = document.getElementById("myElement");

Manipulating elements:

let heading = document.getElementById("header");


heading.innerText = "New Heading Text"; // Changes the text of an element
heading.style.color = "blue"; // Changes the text color

Example:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>DOM Example</title>
</head>
<body>
<h1 id="header">Original Heading</h1>
<button onclick="changeText()">Change Heading Text</button>

<script>
function changeText() {
document.getElementById("header").innerText = "Updated Heading";
document.getElementById("header").style.color = "green";
}
</script>
</body>
</html>

3. Discuss the different types of dialog boxes in JavaScript (alert, prompt,


confirm) with examples.

• Alert: Displays a simple message in a popup box.

alert("This is an alert message!");

• Prompt: Displays a dialog box that asks the user for input.

let userName = prompt("What is your name?");


console.log("User's name is: " + userName);

• Confirm: Displays a dialog box with OK and Cancel buttons and returns true or false.

let isConfirmed = confirm("Do you want to proceed?");


if (isConfirmed) {
console.log("User chose to proceed.");
} else {
console.log("User chose to cancel.");
}

4. Write a JavaScript program to create and call a user-defined function that


calculates the factorial of a number.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Factorial Program</title>
</head>
<body>
<script>
function factorial(num) {
let result = 1;
for (let i = 1; i <= num; i++) {
result *= i;
}
return result;
}

let num = 5;
console.log(`The factorial of ${num} is ${factorial(num)}`);
</script>
</body>
</html>

5. How are events handled in JavaScript? Write a program to handle a


mouseover and click event.

In JavaScript, events can be handled using event listeners, which are attached to HTML
elements. These listeners trigger a function when an event occurs, such as mouseover or click.

Example:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Event Handling Example</title>
</head>
<body>
<button id="myButton">Click Me</button>
<div id="hoverDiv" style="width: 200px; height: 100px; background-color:
lightblue; margin-top: 20px;">
Hover over me
</div>

<script>
// Click event
document.getElementById("myButton").addEventListener("click",
function() {
alert("Button clicked!");
});

// Mouseover event
document.getElementById("hoverDiv").addEventListener("mouseover",
function() {
this.style.backgroundColor = "lightgreen";
});

// Mouseout event
document.getElementById("hoverDiv").addEventListener("mouseout",
function() {
this.style.backgroundColor = "lightblue";
});
</script>
</body>
</html>

6. Explain how objects are created and manipulated in JavaScript, including


properties and methods. Provide examples.

In JavaScript, objects are created using curly braces {}. An object can have properties (key-value
pairs) and methods (functions attached to the object).

Example:

let person = {
firstName: "John",
lastName: "Doe",
age: 30,
greet: function() {
console.log("Hello, " + this.firstName + " " + this.lastName);
}
};

// Accessing properties
console.log(person.firstName); // Output: John

// Calling a method
person.greet(); // Output: Hello, John Doe

7. Discuss the difference between built-in and user-defined functions in


JavaScript. Write examples of each.

• Built-in Functions: These are functions provided by JavaScript, like alert(),


prompt(), parseInt(), etc.

let num = "10";


let parsedNum = parseInt(num); // Built-in function
console.log(parsedNum); // Output: 10

• User-defined Functions: These are functions created by the user to perform specific
tasks.

function multiply(a, b) {
return a * b;
}

let result = multiply(2, 3); // User-defined function


console.log(result); // Output: 6

8. Write a JavaScript code that validates a form with fields for name, email, and
phone number.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form Validation</title>
</head>
<body>
<form id="myForm" onsubmit="return validateForm()">
<label for="name">Name:</label><br>
<input type="text" id="name" name="name"><br><br>

<label for="email">Email:</label><br>
<input type="email" id="email" name="email"><br><br>

<label for="phone">Phone:</label><br>
<input type="text" id="phone" name="phone"><br><br>

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


</form>

<script>
function validateForm() {
let name = document.getElementById("name").value;
let email = document.getElementById("email").value;
let phone = document.getElementById("phone").value;

if (name == "" || email == "" || phone == "") {


alert("All fields must be filled out!");
return false;
}

let phonePattern = /^[0-9]{10}$/;


if (!phonePattern.test(phone)) {
alert("Invalid phone number!");
return false;
}

return true;
}
</script>
</body>
</html>

9. Explain how the try-catch block is used in JavaScript to handle errors.


Provide a program as an example.

The try-catch block is used to handle errors in JavaScript. Code inside the try block is
executed, and if an error occurs, control is passed to the catch block.

Example:

try {
let num = 10;
let result = num / 0; // This will not throw an error but return Infinity
console.log(result);
let undefinedVar = undefinedVar + 1; // This will throw an error
} catch (error) {
console.log("Error caught: " + error.message);
}

10. Write a JavaScript program to dynamically update the content of an HTML


element using the DOM.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>DOM Update Example</title>
</head>
<body>
<p id="demo">This is the original text.</p>
<button onclick="changeContent()">Change Content</button>

<script>
function changeContent() {
document.getElementById("demo").innerText = "This is the updated
text!";
}
</script>
</body>
</html>

Unit 5:

1 Mark Answers:

1. What does XML stand for?


XML stands for Extensible Markup Language.
2. Name one key feature of XML.
One key feature of XML is that it is extensible, meaning you can define your own tags to
structure data.
3. What are XML tags?
XML tags are user-defined elements that define the structure of data within an XML
document. They are enclosed in angle brackets, e.g., <tagname>.
4. State one difference between XML and HTML.
o XML is used to store and transport data, and is extensible, meaning you can
define your own tags.
o HTML is used to display data on a webpage and has predefined tags for specific
purposes (e.g., <p>, <h1>).
5. What is a well-formed XML document?
A well-formed XML document is one that follows the basic syntax rules of XML,
including proper nesting of tags, and every tag being properly closed.
6. Define an XML Parser.
An XML Parser is a software component that reads and processes XML data to convert
it into a format that can be used by an application.
7. What is the purpose of DTD in XML?
A DTD (Document Type Definition) defines the structure and rules for an XML
document, specifying the allowed elements and their relationships.
8. Write an example of a valid XML naming convention.
Example of a valid XML naming convention:
<person_name>John Doe</person_name>
o Names should start with a letter or underscore and can contain letters, digits,
hyphens, and underscores.
9. What is the basic structure of an XML document?
The basic structure of an XML document includes:
o XML Declaration (optional)
o Root element
o Child elements
Example:

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


<book>
<title>XML for Beginners</title>
<author>John Doe</author>
</book>

10. How does CSS integrate with XML?


CSS can be used to style XML documents by referencing the XML file in a separate
CSS file or within a <style> tag. The styling is applied to XML elements using the
class or id attributes.
Example:

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


<book>
<title>XML for Beginners</title>
<author>John Doe</author>
</book>

3 Mark Questions:

1. Three Features of XML:


o Extensibility: XML allows users to define their own tags, making it flexible and
adaptable for various applications.
o Self-descriptive: XML documents describe their structure and data through tags,
which makes them human-readable.
o Platform-independent: XML is platform-independent and can be used across
different systems, making it suitable for data exchange.
2. Naming Rules for XML Elements and Attributes:
o Elements:
▪ Must start with a letter or underscore (_).
▪ Can contain letters, digits, hyphens (-), underscores (_), and periods (.).
▪ Cannot contain spaces.
▪ Example: <name>John</name>, <user_id>12345</user_id>
o Attributes:
▪ Must be enclosed in quotes.
▪ Can contain letters, digits, hyphens, and underscores.
▪ Example: <person age="30" gender="male">John</person>
3. Difference Between Well-formed and Valid XML Documents:
o Well-formed XML: An XML document is well-formed if it follows the basic
XML syntax rules, such as proper nesting, tag closure, and case sensitivity.
▪ Example: <note><to>Tove</to><from>John</from></note>
o Valid XML: A valid XML document adheres to both the basic syntax rules (well-
formed) and conforms to a Document Type Definition (DTD) or XML Schema
that defines its structure.
▪ Example: The document
<note><to>Tove</to><from>John</from></note> is valid if it follows
a predefined DTD.
4. Differences Between XML and HTML:
o Purpose:
▪ XML is used to store and transport data, whereas HTML is used to display
data.
o Tag Structure:
▪ XML allows users to define their own tags, while HTML has predefined
tags like <div>, <p>, etc.
o Data Handling:
▪ XML is data-oriented and doesn’t define how data should be displayed,
while HTML is presentation-oriented and defines the structure of web
pages.
5. Role of XML in Data Exchange:
o XML is widely used for data exchange between different systems, applications,
and platforms. It provides a standardized format to store and transmit structured
data, ensuring that data can be read and understood across different platforms.
o Example: SOAP (Simple Object Access Protocol) uses XML to exchange
messages between web services.
6. What is an XML Parser? Brief Explanation of Its Types:
o An XML parser is a software component that reads an XML document, checks if
it is well-formed, and converts it into a readable format for processing.
o Types:
▪ DOM Parser (Document Object Model): Parses the entire XML
document into a tree structure in memory, allowing for easy manipulation
of elements.
▪ SAX Parser (Simple API for XML): Parses XML documents
sequentially and does not load the entire document into memory, making it
more memory-efficient.
7. Example of an XML Document and Its Building Blocks:
o Example:

<book>
<title>XML for Beginners</title>
<author>John Doe</author>
<year>2023</year>
</book>

o Building Blocks:
▪ Element: <book>, <title>, <author>, <year>
▪ Text content: XML for Beginners, John Doe, 2023
▪ Attributes (optional): <book id="1"> (optional, not used in this
example)
▪ Prolog (optional): <?xml version="1.0"?> (optional, for version
declaration)
8. Using DTD to Define the Structure of an XML Document:
o DTD (Document Type Definition) defines the structure, allowed elements, and
attributes of an XML document.
o Example:

<!DOCTYPE book [
<!ELEMENT book (title, author, year)>
<!ELEMENT title (#PCDATA)>
<!ELEMENT author (#PCDATA)>
<!ELEMENT year (#PCDATA)>
]>
<book>
<title>XML for Beginners</title>
<author>John Doe</author>
<year>2023</year>
</book>

9. Styling XML Using CSS:


o You can style an XML document with CSS by associating a stylesheet with the
XML file.
o Example:

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


<book>
<title>XML for Beginners</title>
<author>John Doe</author>
<year>2023</year>
</book>
In the style.css file:

book {
color: blue;
}
title {
font-weight: bold;
}

10. Key Uses of XML in Web Development:


o Data Exchange: XML is commonly used to exchange data between web
applications and databases, as well as between different web services.
o Configuration Files: Many applications use XML for configuration files, storing
settings in a structured format.
o RSS Feeds: RSS (Really Simple Syndication) feeds use XML to syndicate
content across different websites and platforms.

5 Mark Questions:

1. Write a complete XML document to represent details of a library (e.g., books,


authors, publication year).
<?xml version="1.0" encoding="UTF-8"?>
<library>
<book>
<title>Introduction to Programming</title>
<author>John Doe</author>
<publicationYear>2021</publicationYear>
<isbn>978-1234567890</isbn>
</book>
<book>
<title>Web Development Essentials</title>
<author>Jane Smith</author>
<publicationYear>2020</publicationYear>
<isbn>978-0987654321</isbn>
</book>
<book>
<title>Data Structures and Algorithms</title>
<author>David Lee</author>
<publicationYear>2019</publicationYear>
<isbn>978-1122334455</isbn>
</book>
</library>

2. Explain the features and benefits of XML in modern web applications.

Features of XML:
• Human-readable and machine-readable: XML is text-based, making it both readable
by humans and easily processed by machines.
• Extensible: XML allows the definition of custom tags, making it adaptable to various
data types.
• Platform-independent: XML is platform-agnostic, meaning it can be used across
different systems and applications.
• Self-descriptive: XML elements describe their own data, providing context and meaning.

Benefits:

• Data interchange: XML is widely used for transferring data between different systems,
especially when the data source and destination are built with different technologies.
• Data storage: XML can be used to store data in a structured, hierarchical format.
• Standardized format: XML is standardized and widely adopted, ensuring compatibility
and interoperability across various applications and platforms.

3. Discuss the key differences between HTML and XML, focusing on syntax,
usage, and functionality.

Feature HTML XML


Markup language for displaying Markup language for data storage and
Purpose
data in web browsers. exchange.
Allows flexibility; tags are Strict syntax; tags must be properly closed
Syntax
predefined. and nested.
Tag
Tags are not case-sensitive. Tags are case-sensitive.
Structure
Predefined HTML uses predefined tags (e.g., XML does not have predefined tags. Users
Tags <h1>, <p>, <table>). define tags based on data.
Focuses on how content should be
Display Focuses on storing and transporting data.
displayed.
No formal structure validation; not Data must conform to a schema (DTD,
Validation
required. XML Schema, etc.).

4. What is DTD in XML? Write an example showing how DTD is used to define
the structure of an XML document.

DTD (Document Type Definition) defines the structure and rules for an XML document. It
specifies what elements are allowed, their order, and their attributes.

Example:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE library [
<!ELEMENT library (book+)>
<!ELEMENT book (title, author, publicationYear, isbn)>
<!ELEMENT title (#PCDATA)>
<!ELEMENT author (#PCDATA)>
<!ELEMENT publicationYear (#PCDATA)>
<!ELEMENT isbn (#PCDATA)>
]>
<library>
<book>
<title>Introduction to Programming</title>
<author>John Doe</author>
<publicationYear>2021</publicationYear>
<isbn>978-1234567890</isbn>
</book>
<book>
<title>Web Development Essentials</title>
<author>Jane Smith</author>
<publicationYear>2020</publicationYear>
<isbn>978-0987654321</isbn>
</book>
</library>

5. Explain the concept of an XML Parser in detail. Compare DOM Parser and
SAX Parser with examples.

XML Parser: An XML parser reads and interprets XML data and provides an API to access the
document's structure and content.

• DOM (Document Object Model) Parser:


o Loads the entire XML document into memory and creates a tree structure.
o Allows easy access and manipulation of elements.
o Memory-intensive for large documents.
o Example:

var parser = new DOMParser();


var xmlDoc = parser.parseFromString(xmlString, "text/xml");
var title =
xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue;
console.log(title);

• SAX (Simple API for XML) Parser:


o Reads the XML document sequentially (event-based parsing).
o Faster and uses less memory, especially for large documents.
o Does not allow modification of the document structure.
o Example: SAX-based parsing is typically done in other programming languages
(e.g., Python, Java), and does not directly support manipulation like DOM.
6. Write an XML document for a product catalog and demonstrate how it can be
styled using CSS.

XML Document for Product Catalog:

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


<catalog>
<product>
<name>Smartphone</name>
<price>499.99</price>
<category>Electronics</category>
</product>
<product>
<name>Laptop</name>
<price>899.99</price>
<category>Electronics</category>
</product>
<product>
<name>Table</name>
<price>199.99</price>
<category>Furniture</category>
</product>
</catalog>

CSS for Styling XML:

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


<catalog>
<product>
<name>Smartphone</name>
<price>499.99</price>
<category>Electronics</category>
</product>
<!-- More products... -->
</catalog>

CSS File (styles.css):

catalog {
font-family: Arial, sans-serif;
}

product {
border: 1px solid #ddd;
padding: 10px;
margin-bottom: 10px;
}

name {
font-weight: bold;
font-size: 1.2em;
}

price {
color: green;
}

category {
color: blue;
}

7. How does XML ensure data validation using DTD? Write a DTD to validate
an XML document for student data.

DTD for Student Data Validation:

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


<!DOCTYPE students [
<!ELEMENT students (student+)>
<!ELEMENT student (name, age, grade)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT age (#PCDATA)>
<!ELEMENT grade (#PCDATA)>
]>
<students>
<student>
<name>John Doe</name>
<age>20</age>
<grade>A</grade>
</student>
<student>
<name>Jane Smith</name>
<age>22</age>
<grade>B</grade>
</student>
</students>

8. Discuss the advantages and challenges of using XML in data storage and
exchange.

Advantages of XML:

• Interoperability: XML allows different systems to exchange data in a standard format.


• Self-descriptive: Data is tagged with meaningful names, making it easy to understand.
• Extensibility: XML can define custom tags to represent any data structure.

Challenges of XML:

• Verbosity: XML documents can be large and contain a lot of overhead.


• Complexity: Parsing and processing XML documents require specialized tools and can
be computationally expensive.
• Overhead: The large number of tags can increase file size, impacting storage and
transmission.

9. Write an XML document and integrate it with HTML using JavaScript to


display its content dynamically.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>XML Integration</title>
</head>
<body>
<h1>Product List</h1>
<div id="productList"></div>

<script>
var xmlString = `
<catalog>
<product>
<name>Smartphone</name>
<price>499.99</price>
</product>
<product>
<name>Laptop</name>
<price>899.99</price>
</product>
</catalog>`;

var parser = new DOMParser();


var xmlDoc = parser.parseFromString(xmlString, "text/xml");
var products = xmlDoc.getElementsByTagName("product");
var productListDiv = document.getElementById("productList");

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


var name =
products[i].getElementsByTagName("name")[0].childNodes[0].nodeValue;
var price =
products[i].getElementsByTagName("price")[0].childNodes[0].nodeValue;
productListDiv.innerHTML += `<p>${name}: $${price}</p>`;
}
</script>
</body>
</html>

10. Compare and contrast the use of XML and JSON for data interchange.

Feature XML JSON


Format Text-based, uses custom tags. Text-based, uses key-value pairs.
Feature XML JSON
More verbose and harder to read
Readability Lightweight and easy to read.
for humans.
Data Structure Hierarchical (tree-like structure). Lightweight, simple, key-value pairs.
Support for Data Supports mixed content (text, Limited to text, numbers, arrays, and
Types attributes, and nested elements). booleans.
Parsing Requires a parser, can be slower. Easier to parse and faster.
Used for complex data structures Commonly used for lightweight data
Usage
and document-based data. exchange, APIs, and web services.

Unit 6:

1 Mark Answers:

1. What does PHP stand for?


PHP stands for Hypertext Preprocessor.
2. Write the syntax for starting and ending a PHP script.

<?php
// PHP code here
?>

3. Name two decision-making statements in PHP.


o if statement
o switch statement
4. How do you declare an array in PHP?
An array is declared using the array() function or using square brackets [].
Example:

$arr = array(1, 2, 3); // using array()


$arr = [1, 2, 3]; // using []

5. What is the purpose of the isset() function in PHP?


The isset() function checks whether a variable is set and is not null.
6. Name one method to create a session in PHP.
To start a session in PHP, you can use:

session_start();
7. What does $_POST in PHP represent?
$_POST is a superglobal array used to collect form data after submitting a form with the
POST method.
8. Write the syntax to connect to a MySQL database in PHP.
Example using mysqli:

$conn = mysqli_connect("localhost", "username", "password",


"database_name");

9. What is the purpose of the echo statement in PHP?


The echo statement is used to output one or more strings to the screen.

3 Mark Questions:

1. Difference Between echo and print in PHP:


o echo: It is a language construct used to output one or more strings. It does not
return a value and can output multiple parameters.

echo "Hello, World!"; // Outputs: Hello, World!


echo "Hello", " ", "World!"; // Outputs: Hello World!

o print: It is also a language construct used to output a single string. Unlike echo,
print returns a value (1), which makes it useful in expressions.

print "Hello, World!"; // Outputs: Hello, World!

2. Handling Form Data Using $_GET and $_POST:


o $_GET: It is used to collect form data after submitting an HTML form with the
method GET. Data is passed in the URL.

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


<input type="text" name="username">
<input type="submit" value="Submit">
</form>

// process.php
echo $_GET['username']; // Outputs the value of the username
field

o $_POST: It is used to collect form data after submitting an HTML form with the
method POST. Data is sent in the HTTP request body, which is more secure for
sensitive data.

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


<input type="text" name="username">
<input type="submit" value="Submit">
</form>
php
Copy code
// process.php
echo $_POST['username']; // Outputs the value of the username
field

3. PHP Program Demonstrating the Use of a For Loop:

<?php
for ($i = 1; $i <= 5; $i++) {
echo "Number: " . $i . "<br>";
}
?>

o This will output:

javascript
Copy code
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5

4. Defining Arrays in PHP and Example of an Associative Array:


o Indexed Array: An array with numeric indices.

$colors = array("Red", "Green", "Blue");


echo $colors[0]; // Outputs: Red

o Associative Array: An array where each element is identified by a key instead of


a numeric index.

$person = array("name" => "John", "age" => 25);


echo $person["name"]; // Outputs: John

5. Role of Cookies in PHP:


o Cookies are used to store data on the client-side (in the browser). They can store
user preferences or session data across requests.
o Example:

// Setting a cookie
setcookie("username", "Alice", time() + 3600, "/"); // Cookie
expires in 1 hour

// Accessing the cookie


if(isset($_COOKIE["username"])) {
echo "Welcome " . $_COOKIE["username"]; // Outputs: Welcome
Alice
}
6. Sessions in PHP:
o Sessions are used to store user data on the server. A session is started using
session_start() and can store user information like login status, preferences,
etc.
o Example:

session_start(); // Starts the session


$_SESSION["username"] = "Alice"; // Store session variable

echo "Hello, " . $_SESSION["username"]; // Outputs: Hello, Alice

7. PHP Detecting Browser Information Using $_SERVER:


o PHP provides the $_SERVER superglobal to access information about the server
and the client's browser.
o Example:

echo $_SERVER['HTTP_USER_AGENT']; // Outputs the user's browser


information, e.g., "Mozilla/5.0..."

8. Difference Between include and require in PHP:


o include: Includes and evaluates a specified file. If the file is not found, it
generates a warning, but the script continues executing.

include 'header.php';

o require: Similar to include, but if the file is not found, it results in a fatal error
and stops the script execution.

require 'header.php';

9. String Manipulation in PHP (Examples Using strlen and strpos):


o strlen: Returns the length of a string.

$str = "Hello, World!";


echo strlen($str); // Outputs: 13

o strpos: Finds the position of the first occurrence of a substring in a string.

$str = "Hello, World!";


echo strpos($str, "World"); // Outputs: 7

10. Creating a File and Writing Data to It in PHP:


o PHP allows you to create and write data to a file using functions like fopen,
fwrite, and fclose.
o Example:

$file = fopen("example.txt", "w"); // Opens the file for writing


fwrite($file, "Hello, this is a test!"); // Writes data to the
file
fclose($file); // Closes the file

5 Mark Questions:

1. Write a PHP script to process a form and display the submitted data (e.g.,
name, email, and age).
<!DOCTYPE html>
<html>
<head>
<title>Form Submission</title>
</head>
<body>

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


Name: <input type="text" name="name"><br><br>
Email: <input type="email" name="email"><br><br>
Age: <input type="number" name="age"><br><br>
<input type="submit" value="Submit">
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST['name'];
$email = $_POST['email'];
$age = $_POST['age'];

echo "<h2>Submitted Data:</h2>";


echo "Name: " . $name . "<br>";
echo "Email: " . $email . "<br>";
echo "Age: " . $age . "<br>";
}
?>

</body>
</html>

2. Explain decision-making in PHP with examples of if-else, switch, and ternary


operators.

• If-Else Statement:

$age = 18;
if ($age >= 18) {
echo "You are an adult.";
} else {
echo "You are a minor.";
}
• Switch Statement:

$day = 3;
switch ($day) {
case 1:
echo "Monday";
break;
case 2:
echo "Tuesday";
break;
case 3:
echo "Wednesday";
break;
default:
echo "Invalid day";
}

• Ternary Operator:

$age = 20;
echo ($age >= 18) ? "You are an adult." : "You are a minor.";

3. Write a PHP script that demonstrates the use of functions, including a user-
defined function and a built-in function.
<?php
// User-defined function
function greet($name) {
return "Hello, " . $name;
}

echo greet("Alice"); // Output: Hello, Alice

// Built-in function
$date = date("Y-m-d H:i:s");
echo "<br>Current Date and Time: " . $date;
?>

4. Discuss cookies and sessions in PHP, highlighting their differences with


examples for each.

• Cookies:
o A cookie is stored on the user's browser and can be accessed across sessions.
o Example:

setcookie("username", "JohnDoe", time() + 3600); // 1 hour


expiration
if (isset($_COOKIE["username"])) {
echo "Welcome " . $_COOKIE["username"];
}
• Sessions:
o A session stores data on the server and can be used across different pages during a
single user session.
o Example:

session_start();
$_SESSION['username'] = "JohnDoe";
echo "Hello, " . $_SESSION['username'];

Differences:

• Cookies are stored in the user's browser, while sessions are stored on the server.
• Cookies persist even after the browser is closed (until expiration), while sessions expire
when the browser is closed or the session is destroyed.
• Cookies have size limitations (typically 4KB), while sessions can store larger amounts of
data.

5. Write a PHP program to connect to a MySQL database and perform CRUD


operations (Insert, Update, Delete, and Retrieve).
<?php
// Database connection
$conn = new mysqli("localhost", "username", "password", "database");

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// Insert Data
if (isset($_POST['insert'])) {
$name = $_POST['name'];
$email = $_POST['email'];
$sql = "INSERT INTO users (name, email) VALUES ('$name', '$email')";
$conn->query($sql);
}

// Update Data
if (isset($_POST['update'])) {
$id = $_POST['id'];
$newEmail = $_POST['newEmail'];
$sql = "UPDATE users SET email='$newEmail' WHERE id='$id'";
$conn->query($sql);
}

// Delete Data
if (isset($_POST['delete'])) {
$id = $_POST['id'];
$sql = "DELETE FROM users WHERE id='$id'";
$conn->query($sql);
}

// Retrieve Data
$sql = "SELECT * FROM users";
$result = $conn->query($sql);
while ($row = $result->fetch_assoc()) {
echo "ID: " . $row['id'] . " - Name: " . $row['name'] . " - Email: " .
$row['email'] . "<br>";
}

$conn->close();
?>

6. Explain the use of loops in PHP with examples of while, do-while, and foreach
loops.

• While Loop:

$i = 1;
while ($i <= 5) {
echo $i . "<br>";
$i++;
}

• Do-While Loop:

$i = 1;
do {
echo $i . "<br>";
$i++;
} while ($i <= 5);

• Foreach Loop (used with arrays):

$arr = array(1, 2, 3, 4, 5);


foreach ($arr as $value) {
echo $value . "<br>";
}

7. How does PHP integrate with HTML? Write a sample PHP-HTML script for
a simple calculator.
<!DOCTYPE html>
<html>
<head>
<title>Simple Calculator</title>
</head>
<body>

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


First Number: <input type="number" name="num1"><br><br>
Second Number: <input type="number" name="num2"><br><br>
<input type="submit" name="submit" value="Calculate">
</form>

<?php
if (isset($_POST['submit'])) {
$num1 = $_POST['num1'];
$num2 = $_POST['num2'];
$sum = $num1 + $num2;
echo "Sum: " . $sum;
}
?>

</body>
</html>

8. Write a PHP program to handle file uploads and display the uploaded file
details.
<!DOCTYPE html>
<html>
<head>
<title>File Upload</title>
</head>
<body>

<form action="" method="post" enctype="multipart/form-data">


Select file: <input type="file" name="fileToUpload"
id="fileToUpload"><br><br>
<input type="submit" value="Upload File" name="submit">
</form>

<?php
if (isset($_POST['submit'])) {
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"],
$target_file)) {
echo "The file ". basename($_FILES["fileToUpload"]["name"]). " has
been uploaded.";
echo "<br>File Details:<br>";
echo "File Name: " . $_FILES["fileToUpload"]["name"] . "<br>";
echo "File Size: " . $_FILES["fileToUpload"]["size"] . " bytes<br>";
echo "File Type: " . $_FILES["fileToUpload"]["type"] . "<br>";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>

</body>
</html>
9. Explain the process of database connectivity in PHP using MySQL, including
error handling.
<?php
// Database connection
$conn = new mysqli("localhost", "username", "password", "database");

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";

// Perform a query
$sql = "SELECT id, name, email FROM users";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"]. " - Name: " . $row["name"]. " - Email: " .
$row["email"]. "<br>";
}
} else {
echo "0 results";
}

$conn->close();
?>

10. Write a complete PHP-MySQL application to display data from a database


table in a formatted HTML table.
<?php
// Database connection
$conn = new mysqli("localhost", "username", "password", "database");

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// Fetch data from the database


$sql = "SELECT id, name, email FROM users";
$result = $conn->query($sql);

// Display data in a table


echo "<table border='1'>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
</tr>";
while ($row = $result->fetch_assoc()) {
echo "<tr>
<td>" . $row["id"] . "</td>
<td>" . $row["name"] . "</td>
<td>" . $row["email"] . "</td>
</tr>";
}

echo "</table>";

$conn->close();
?>

You might also like