0% found this document useful (0 votes)
12 views

Fundamentals of Web Programming

The document explains the difference between the Internet and the World Wide Web (WWW), highlighting that the Internet is the global network of computers while the WWW is a collection of websites accessed via browsers. It covers various communication methods available on the Internet, including email, instant messaging, social media, and video calls, along with the Domain Name System (DNS) which translates domain names into IP addresses. Additionally, it outlines the steps for connecting to the Internet, types of IP addresses, and the importance of DNS in facilitating web access.

Uploaded by

rohanpreets861
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Fundamentals of Web Programming

The document explains the difference between the Internet and the World Wide Web (WWW), highlighting that the Internet is the global network of computers while the WWW is a collection of websites accessed via browsers. It covers various communication methods available on the Internet, including email, instant messaging, social media, and video calls, along with the Domain Name System (DNS) which translates domain names into IP addresses. Additionally, it outlines the steps for connecting to the Internet, types of IP addresses, and the importance of DNS in facilitating web access.

Uploaded by

rohanpreets861
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 117

Fundamentals of Web Programming ECAP214

Chapter 1: Internet Basic


Difference Between WWW and Internet

Many people think WWW (World Wide Web) and Internet are the same, but they are different. Let’s
break it down in a simple way!

1️ What is the Internet?

The Internet is like a huge network of computers all over the world, connected to share
information.
It is the physical infrastructure – cables, satellites, routers, and servers – that connect devices
like computers, phones, and tablets.
The Internet allows you to send emails, play online games, use social media, and browse websites.

Think of the Internet as the roads and highways that connect different cities!

2️ What is WWW (World Wide Web)?

The WWW (World Wide Web) is a part of the Internet.


It is a collection of websites and web pages that you can access using a web browser (like Chrome,
Firefox, or Edge).
Websites are stored on servers, and you can visit them using URLs (e.g., www.google.com).

Think of the WWW as the cars, houses, and buildings on the roads of the Internet!

Key Differences Between Internet & WWW

Feature Internet World Wide Web

A system of websites and web


Definition A global network of computers
pages

Function Connects computers & devices Stores and displays web content

Includes Email, social media, online gaming, file sharing Websites, web pages, hyperlinks

Browsing and accessing


Uses Communication & data transfer
information

Example Sending an email Reading a news article online

1
Conclusion

The Internet is the big network, and the WWW is just one part of it (like a service that runs on
the Internet).
You can use the Internet without the WWW (e.g., sending an email or using WhatsApp).
But you need the Internet to access the WWW.

So next time someone says "I’m on the Internet," you’ll know if they mean using the web or
something else!

How to Communicate on the Internet?

The internet allows people to communicate in different ways. Whether you want to chat with friends,
send emails, or share information, there are many options. Let’s explore them in detail.

1️. Email (Electronic Mail)

What is it?
Email is like a digital letter. You can send messages, documents, and pictures to others.

How to use it?

• Create an email account (e.g., Gmail, Yahoo, Outlook).

• Write a message and enter the recipient's email address.

• Click "Send" to deliver the email.

Best for:

• Formal communication (work, school).

• Sending documents or reports.

2️. Instant Messaging (Chat Apps)

What is it?
Instant messaging allows real-time text communication.

Examples:

• WhatsApp

• Messenger

• Telegram

• Signal

How to use it?

• Install a chat app.

2
• Add contacts.

• Type a message and send it instantly.

Best for:

• Quick communication with friends and family.

• Sharing photos, videos, or voice messages.

3. Social Media (Facebook, Twitter, Instagram, etc.)

What is it?
Social media platforms help people connect, share updates, and interact.

How to use it?

• Create an account.

• Post text, images, or videos.

• Like, comment, and share posts.

Best for:

• Staying connected with friends and communities.

• Sharing personal or public information.

4. Video Calls (Zoom, Google Meet, Skype, etc.)

What is it?
Video calling allows face-to-face communication over the internet.

How to use it?

• Open a video calling app.

• Start a meeting and invite others.

• Use a microphone and camera for talking and seeing each other.

Best for:

• Virtual meetings (work, school).

• Talking with family or friends far away.

5. Forums and Discussion Boards

What is it?
Online forums allow people to discuss topics and ask questions.

3
Examples:

• Reddit

• Quora

• Stack Overflow

How to use it?

• Sign up for a forum.

• Post a question or reply to others.

Best for:

• Learning new things.

• Getting help or advice.

6. Blogs and Websites

What is it?
People can share information, ideas, or experiences through blogs.

How to use it?

• Read blogs to learn.

• Write your own blog and share thoughts.

Best for:

• Sharing knowledge or experiences.

• Learning about different topics.

7. Online Gaming Chats (Discord, In-game Chats, etc.)

What is it?
Gamers use chats to communicate while playing games.

How to use it?

• Join a gaming server (e.g., Discord).

• Use text or voice chat to talk while gaming.

Best for:

• Team coordination in games.

• Making friends with other gamers.

4
8. Online Customer Support (Live Chat, Chatbots)

What is it?
Many companies offer online support through live chat or chatbots.

How to use it?

• Visit a company website.

• Click on "Chat Support" and type your question.

Best for:

• Getting quick help from companies.

• Resolving technical issues.

Tips for Safe Communication Online

Use strong passwords to protect your accounts.


Be respectful while chatting online.
Avoid sharing personal information with strangers.
Verify information before believing or sharing it.
Beware of scams and suspicious messages.

This is how you can communicate on the internet in different ways! Which one do you use the most?

What is the Domain Name System (DNS)?

The Domain Name System (DNS) is like the phonebook of the internet. It helps translate human-
friendly website names (like www.google.com) into numerical IP addresses (like 1️42️.2️50.1️82️.4) that
computers use to identify each other on the internet.

Why is DNS Needed?

Computers communicate using IP addresses, which are long strings of numbers. However,
remembering numbers like 1️92️.1️68.1️.1️ for every website would be very difficult for humans. DNS
makes it easy by allowing us to use names instead.

For example:
Instead of typing 1️42️.2️50.1️82️.4, you can simply type www.google.com, and DNS will handle the
rest!

How DNS Works (Step-by-Step Process)

5
Whenever you type a website address (like www.facebook.com) in your browser, the following steps
happen:

Step 1️: Your Computer Asks for the IP Address

• Your web browser sends a request to the DNS resolver (a special server) to find the IP address
of www.facebook.com.

• This request is called a DNS query.

Step 2️: Checking the Cache (Local Memory)

• Your computer first checks if it already knows the IP address from a recent visit (stored in the
cache).

• If found, it loads the website immediately.

• If not, it asks a DNS resolver.

Step 3: Asking the Recursive DNS Resolver

• The DNS resolver is like a librarian searching for a book.

• If it doesn’t know the answer, it will ask other DNS servers.

Step 4: Contacting the Root DNS Server

• The resolver first asks a Root DNS Server (the top-most level of DNS).

• The Root Server does not give the exact IP address but tells where to look next (TLD server).

Step 5: Asking the TLD Server (Top-Level Domain Server)

• The TLD server handles domains like .com, .net, .org, etc.

• Since we are looking for facebook.com, the TLD server for .com is contacted.

• It gives the address of the Authoritative DNS Server for Facebook.

Step 6: Getting the Final IP from the Authoritative DNS Server

• The Authoritative DNS Server has the actual IP address of www.facebook.com.

• It sends the IP address back to the DNS resolver.

Step 7: Your Browser Connects to the Website

• The resolver gives the IP address to your computer.

• Now, your browser can connect to www.facebook.com using its IP address and load the
webpage!

Types of DNS Servers

There are 4 main types of DNS servers:

6
1⃣ Recursive DNS Resolver – Finds the IP address by asking other DNS servers.
2⃣ Root DNS Server – Directs queries to the correct TLD server.
3⃣ TLD (Top-Level Domain) Server – Handles domain extensions like .com, .org, .net.
4⃣ Authoritative DNS Server – The final server that provides the actual IP address.

Example of DNS Lookup Process

If you want to visit www.amazon.com, here’s what happens:

1 You type www.amazon.com in your browser.


2 Your computer asks the DNS resolver for the IP address.
3 The resolver asks the Root DNS Server → The root directs it to the .com TLD Server.
4 The .com TLD Server sends the request to Amazon’s Authoritative DNS Server.
5 The Authoritative DNS Server replies with the IP address (e.g., 2️05.2️51️.2️42️.1️03).
6 Your browser connects to Amazon’s website using this IP address.

DNS Caching (Speeding Up the Process)

To make websites load faster, DNS responses are stored in cache (temporary memory).

Where is DNS caching done?


1 On your browser (like Chrome, Firefox).
2 On your operating system (Windows, macOS, Linux).
3 On your ISP’s (Internet Service Provider’s) DNS server.

This means, if you visit www.google.com today, and visit again tomorrow, your browser won’t need to
ask DNS servers again—it will remember the IP address.

Common DNS Issues and Errors

DNS_PROBE_FINISHED_NXDOMAIN → Domain name does not exist.


DNS_PROBE_FINISHED_BAD_CONFIG → Network issue or incorrect DNS settings.
ERR_NAME_NOT_RESOLVED → DNS lookup failed, website not found.

Fixing these issues can involve:


✔ Changing DNS settings (using Google DNS 8.8.8.8).
✔ Flushing DNS cache.
✔ Restarting the router.

Popular DNS Services (Public DNS Servers)

Instead of using your ISP’s DNS, you can use faster, more secure DNS servers:

7
Google Public DNS → 8.8.8.8 & 8.8.4.4
Cloudflare DNS → 1️.1️.1️.1️ (Fast & Privacy-focused)
OpenDNS → 2️08.67.2️2️2️.2️2️2️

Conclusion

DNS is the backbone of the internet, making it easy for humans to browse websites without
remembering long IP addresses.
It works like a phonebook, translating domain names into IP addresses.
There are multiple layers of DNS servers, working together to provide the correct website
address.
Caching helps speed up DNS lookups, making websites load faster.
If DNS fails, websites won’t load, so changing to a reliable DNS provider can improve
performance.

Would you like me to explain anything in more detail?

Procedure of Connectivity to the Internet

The internet is a vast network that connects computers and devices worldwide. To access the
internet, you need to follow a few simple steps. Here’s a detailed and easy-to-understand
explanation:

Step 1️: Choose an Internet Service Provider (ISP)

An ISP (Internet Service Provider) is a company that provides internet access. Some common ISPs
include Airtel, Jio, BSNL, Comcast, and AT&T. You need to select a suitable plan based on speed, data
limit, and cost.

Step 2️: Set Up the Required Devices

To connect to the internet, you need some essential devices:

1. Modem – A device that connects your home to the ISP through a wired or wireless connection.

2. Router (Optional) – If you want Wi-Fi (wireless internet) for multiple devices, a router is
required. It distributes the internet connection.

3. Computer, Smartphone, or Tablet – The device you will use to access the internet.

Step 3: Connect the Hardware

1. For Wired Connection (Broadband/DSL/Fiber):

o Connect the modem to the ISP’s cable using a telephone line, fiber optic cable, or
coaxial cable.

o Connect the modem to your computer or router using an Ethernet cable.

2. For Wireless Connection (Wi-Fi):

o Connect the modem to the router using an Ethernet cable.


8
o The router will provide wireless signals, which you can connect to from your
smartphone, laptop, or other devices.

Step 4: Configure the Network Settings

1. Open the settings on your computer or smartphone.

2. If using Wi-Fi, go to Wi-Fi settings, find your network name (SSID), and enter the password.

3. If using a wired connection, your computer should connect automatically.

4. Sometimes, ISPs require login credentials or custom settings, which they provide.

Step 5: Test the Internet Connection

1. Open a browser (Chrome, Firefox, Edge, etc.).

2. Try visiting a website like www.google.com to check if the connection is working.

3. If there is a problem, restart the modem and router or contact your ISP for troubleshooting.

Alternative Internet Connectivity Options

• Mobile Data (4G/5G): Use a SIM card with a mobile internet plan. Enable mobile data in phone
settings.

• Hotspot: Use a smartphone or portable device to share internet via Wi-Fi.

• Public Wi-Fi: Connect to free Wi-Fi networks available in cafes, airports, and libraries.

By following these steps, you can easily connect to the internet and start browsing, streaming, and
communicating online!

Note on IP Addressing

What is an IP Address?

An IP Address (Internet Protocol Address) is a unique numerical label assigned to each device
connected to a network. It acts like a home address for devices on the internet or a local network,
allowing them to send and receive data correctly.

Types of IP Addresses

IP addresses are of two main types:

1. IPv4 (Internet Protocol Version 4)

o Uses a 32️-bit addressing scheme.

o Written in four sets of numbers separated by dots (e.g., 192.168.1.1).

o Can support around 4.3 billion unique addresses.

o Due to the rapid growth of the internet, IPv4 addresses are running out.

2. IPv6 (Internet Protocol Version 6)

o Uses a 1️2️8-bit addressing scheme.

9
o Written in eight groups of four hexadecimal numbers (e.g.,
2001:0db8:85a3:0000:0000:8a2e:0370:7334).

o Can support trillions of unique addresses, solving the shortage issue.

o More secure and efficient compared to IPv4.

Types of IP Addressing

1. Public IP Address

o Used on the internet and assigned by Internet Service Providers (ISPs).

o Example: Websites, servers, and home routers use public IPs to connect globally.

2. Private IP Address

o Used within a local network (like home, office, or school networks).

o Not accessible directly from the internet.

o Example: 192.168.1.1 (used for home Wi-Fi routers).

3. Static IP Address

o Manually assigned and does not change over time.

o Commonly used for websites, servers, and networked devices.

4. Dynamic IP Address

o Assigned automatically by DHCP (Dynamic Host Configuration Protocol).

o Changes periodically, making it more secure and cost-effective.

o Most home internet users have dynamic IPs.

IP Address Classes (For IPv4)

IPv4 addresses are divided into five classes based on usage:

Class Range Usage

Class A 1.0.0.0 – 126.255.255.255 Large networks (e.g., big companies)

Class B 128.0.0.0 – 191.255.255.255 Medium-sized networks

Class C 192.0.0.0 – 223.255.255.255 Small networks (e.g., home, office)

Class D 224.0.0.0 – 239.255.255.255 Used for multicast groups

Class E 240.0.0.0 – 255.255.255.255 Reserved for future use

Subnetting and CIDR

• Subnetting helps divide a large network into smaller parts for better management and
security.

10
• CIDR (Classless Inter-Domain Routing) replaces the old class-based system and allows
efficient use of IP addresses. Example: 1️92️.1️68.1️.0/2️4, where /24 means the first 24 bits are
the network part.

Conclusion

IP addressing is essential for communication over networks and the internet. IPv4 is widely used, but
IPv6 is the future due to its larger address space. Understanding public/private, static/dynamic IPs,
and subnetting helps in better network management.

IP (Internet Protocol) addresses are unique identifiers assigned to devices on a network. They help in
communication between computers, servers, and other devices over the internet or a local network.

IP addresses are divided into five classes: A, B, C, D, and E. These classes define the range and
purpose of IP addresses.

1️. Class A

• Range: 1.0.0.0 to 126.255.255.255

• Purpose: Used for large networks (like big organizations or internet service providers).

• Structure:

o First octet (first number) represents the network ID.

o Remaining three octets represent the host ID (individual devices in the network).

• Example: 10.0.0.1

Class A is suitable for large-scale networking because it can support up to 16 million devices!

2️. Class B

• Range: 128.0.0.0 to 191.255.255.255

• Purpose: Used for medium-sized networks (like universities, companies).

• Structure:

o First two octets define the network ID.

o Last two octets define the host ID.

• Example: 172.16.0.1

Class B networks can handle around 65,000 devices.

3. Class C

• Range: 192.0.0.0 to 223.255.255.255

11
• Purpose: Used for small networks (like homes, small businesses).

• Structure:

o First three octets define the network ID.

o Last octet defines the host ID.

• Example: 192.168.1.1

Class C networks are common for home and office networks since they can support 254 devices.

4. Class D (Multicast)

• Range: 224.0.0.0 to 239.255.255.255

• Purpose: Used for multicasting (sending data to multiple devices at the same time).

• Example Use Case: Live streaming, video conferencing.

• Example IP: 224.0.0.1

Class D is not used for normal device communication; it's used for broadcasting information to
groups of devices.

5. Class E (Experimental)

• Range: 240.0.0.0 to 255.255.255.255

• Purpose: Reserved for experimental and research purposes.

• Example IP: 250.1.1.1

Class E is not used for regular networking. It is kept for future technologies.

Summary Table of IP Classes

Class IP Range Network Size Used For

A 1.0.0.0 – 126.255.255.255 Very Large Big organizations, ISPs

B 128.0.0.0 – 191.255.255.255 Medium Universities, businesses

C 192.0.0.0 – 223.255.255.255 Small Homes, small offices

D 224.0.0.0 – 239.255.255.255 Special Multicasting (streaming, conferencing)

E 240.0.0.0 – 255.255.255.255 Not Used Research & Future use

Hope this explanation helps! Let me know if you need further clarification.

12
A Note on TCP/IP

What is TCP/IP?

TCP/IP stands for Transmission Control Protocol/Internet Protocol. It is the set of rules (protocols)
that allow computers to communicate over the internet and other networks. It defines how data is
sent, transmitted, received, and understood across different devices.

Why is TCP/IP Important?

TCP/IP is the foundation of the internet. Without it, computers, smartphones, and other devices
wouldn’t be able to exchange information properly. It ensures that data sent from one device reaches
the correct destination safely and accurately.

Components of TCP/IP

TCP/IP consists of two main protocols:

1. TCP (Transmission Control Protocol)

o Responsible for breaking data into small packets before sending it.

o Ensures all packets are delivered correctly and in the right order.

o Provides error checking to detect lost or damaged packets and requests retransmission
if needed.

o Example: When you send an email or browse a website, TCP makes sure all parts of the
webpage or email arrive correctly.

2. IP (Internet Protocol)

o Handles addressing and routing of data packets.

o Every device connected to the internet has an IP address (like a home address) that
helps in identifying the sender and receiver.

o Example: When you visit a website, IP ensures that the data from the web server
reaches your computer.

Layers of TCP/IP Model

TCP/IP works in four layers, each with a specific function:

1. Application Layer

o Interacts with users and applications.

o Includes web browsers (HTTP), email (SMTP), and file transfer (FTP).

2. Transport Layer

o Responsible for data transmission between devices.

13
o Uses TCP (for reliable transmission) and UDP (for faster but less reliable transmission).

3. Internet Layer

o Handles data addressing and routing through IP addresses.

o Uses protocols like IP, ICMP (for error reporting), and ARP (for address resolution).

4. Network Access Layer

o Deals with hardware and physical connections like cables, Wi-Fi, and Ethernet.

o Converts data into signals to be transmitted over the network.

How TCP/IP Works (Simple Explanation)

1. You open a web browser and type a website address (e.g., www.google.com).

2. The browser requests the website using HTTP (an application layer protocol).

3. The request is broken into small packets by TCP and sent over the network.

4. IP assigns the correct destination address and routes the packets.

5. The packets travel through the internet and reach Google’s server.

6. Google’s server sends back the webpage data using the same TCP/IP process.

7. Your browser receives the packets, reassembles them, and displays the webpage.

Advantages of TCP/IP

✔ Reliable Communication – Ensures all data reaches its destination correctly.


✔ Scalability – Works on small networks (home Wi-Fi) and large networks (internet).
✔ Interoperability – Can connect different types of devices and systems.
✔ Fault Tolerance – If one path fails, TCP/IP can reroute data through another path.

Disadvantages of TCP/IP

Complex Setup – Requires knowledge of networking concepts.


Security Issues – Data packets can be intercepted if not encrypted.
Overhead – TCP ensures reliability, but it makes data transmission slower.

Conclusion

TCP/IP is the backbone of the internet. It allows different devices to communicate by ensuring data is
transmitted accurately and efficiently. Whether browsing a website, sending an email, or streaming a
video, TCP/IP makes everything possible.

Make distinction between website and webpage.

14
Aspect Website Webpage

A collection of related web pages A single document that is displayed in a web


Definition
hosted on a server. browser.

Comprises multiple webpages, Contains text, images, links, and multimedia


Components
images, videos, and files. content.

Identified by a specific URL that includes the


URL Identified by a domain name (e.g.,
webpage's path (e.g.,
Structure www.example.com).
www.example.com/about).

Provides a platform for various


Serves a specific purpose or contains specific
Functionality activities (e.g., e-commerce,
information (e.g., an article, product page).
blogging).

Includes a navigation system to link Usually contains links to other pages or


Navigation
different webpages. resources within the website.

www.example.com/contact (a specific
Examples www.example.com (a full website).
webpage).

The Domain Name System (DNS) is an essential part of how the internet functions. It acts like a phone
book for the internet, translating user-friendly domain names (like www.example.com) into IP
addresses (like 192.0.2.1) that computers use to identify each other on the network. Here’s a detailed
explanation in simple language:

What is DNS?

1. Purpose of DNS:

o When you want to visit a website, you typically enter a domain name in your web
browser. However, computers communicate using numerical IP addresses. DNS
translates the domain name into an IP address so that your computer can find and
connect to the server hosting that website.

2. Structure of DNS:

o Domain Names: A domain name is structured in levels, separated by dots. For


example, in www.example.com, "com" is the top-level domain (TLD), "example" is the
second-level domain, and "www" is a subdomain. The hierarchy helps organize and
locate websites more easily.

o DNS Records: DNS uses various types of records to store information about a domain.
Common types include:

▪ A Record: Maps a domain name to an IPv4 address.

▪ AAAA Record: Maps a domain name to an IPv6 address.

▪ CNAME Record: Maps one domain name to another (alias).

15
▪ MX Record: Specifies the mail server responsible for receiving email on behalf of
a domain.

How DNS Works

1. User Request:

o When you type a URL (like www.example.com) into your browser and hit enter, your
computer checks its local DNS cache to see if it already knows the IP address for that
domain.

2. Recursive DNS Resolver:

o If the IP address is not in the cache, your request goes to a DNS resolver (usually
provided by your internet service provider). The resolver's job is to find the IP address for
the domain.

3. Root Nameservers:

o The resolver starts by querying a root nameserver. Root nameservers know where to find
the nameservers for top-level domains (like .com, .org, etc.).

4. TLD Nameservers:

o The root nameserver responds with the address of the TLD nameserver for .com. The
resolver then queries this TLD nameserver.

5. Authoritative Nameservers:

o The TLD nameserver responds with the address of the authoritative nameserver for the
specific domain (example.com). This authoritative nameserver holds the DNS records
for that domain.

6. Getting the IP Address:

o The resolver queries the authoritative nameserver, which responds with the IP address
of the domain (e.g., 192.0.2.1).

7. Connecting to the Website:

o Finally, the resolver sends this IP address back to your computer. Your browser can now
connect to the server at that IP address, allowing you to view the website.

Example

Let’s say you want to visit www.example.com. Here’s how DNS works step-by-step:

1. You enter www.example.com in your browser.

2. Your computer checks if it knows the IP address. If not, it asks the DNS resolver.

3. The resolver queries a root nameserver and gets the address of the .com TLD nameserver.

4. The resolver then asks the .com TLD nameserver, which provides the address of the
authoritative nameserver for example.com.

5. The resolver queries the authoritative nameserver and receives the IP address (e.g., 192.0.2.1).
16
6. The resolver returns the IP address to your computer.

7. Your browser connects to the web server at 192.0.2.1 and loads the website.

Conclusion

In summary, the Domain Name System (DNS) is a crucial part of the internet that makes it easy for
users to access websites using simple domain names instead of complicated numerical IP
addresses. It involves a series of queries through various types of nameservers to find the correct IP
address, allowing users to connect to the desired website seamlessly.

Domain names are an essential part of how we navigate the internet, and they are created based on
specific rules and procedures established by the Domain Name System (DNS). Here’s a detailed
explanation of how domain names are formed within the framework of DNS, using simple language:

Understanding Domain Names

1. What is a Domain Name?

o A domain name is a human-readable address that identifies a specific location on the


internet. For example, www.google.com is a domain name that points to Google's
website. It is much easier to remember and type than a numeric IP address like
172.217.14.206.

2. Structure of Domain Names:

o Domain names are structured in a hierarchical format and consist of several parts:

▪ Top-Level Domain (TLD): This is the last part of the domain name, such as .com,
.org, .net, or country-specific extensions like .uk, .ca, etc. TLDs indicate the
nature or location of the website.

▪ Second-Level Domain (SLD): This is the part before the TLD. In


www.example.com, "example" is the second-level domain. It usually represents
the name of the organization, business, or purpose of the website.

▪ Subdomain: This is an optional part that precedes the second-level domain. For
example, in www.example.com, "www" is a subdomain often used to designate
the web version of the site.

Rules and Procedures for Forming Domain Names

1. Domain Name Registration:

o To create a domain name, you must register it with a domain registrar. Registrars are
organizations accredited by the Internet Corporation for Assigned Names and Numbers
(ICANN) or national authorities. They manage the reservation of domain names.

2. Availability Check:

o Before registering a domain name, you need to check if it is available. Each domain
name is unique, and if someone else has already registered it, you will need to choose a
different name.

17
3. Character Limitations:

o Domain names must follow specific character rules:

▪ They can only include letters (a-z), numbers (0-9), and hyphens (-).

▪ They cannot start or end with a hyphen.

▪ They cannot include special characters (like @, #, $, etc.).

▪ The length of a domain name can range from 1 to 63 characters (not including
the TLD).

4. Domain Name Hierarchy:

o Domain names are organized in a hierarchy. The highest level is the root, followed by
TLDs, second-level domains, and any subdomains. This structure helps in managing
and locating websites efficiently.

5. Naming Conventions:

o While creating a domain name, it’s important to choose a name that is easy to
remember, spell, and pronounce. Many businesses choose names that reflect their
brand or the services they provide.

Example of Domain Name Formation

Let’s say you want to create a website for a bakery named "Sweet Treats." Here’s how you would form
a domain name for it:

1. Choose a Domain Name: You might consider sweettreats.com as your domain name.

2. Check Availability: You would check with a domain registrar to see if sweettreats.com is
available. If it is taken, you may need to consider variations like sweettreatsbakery.com or
sweettreats.net.

3. Register the Domain: Once you find an available name, you would register it through a domain
registrar, which involves providing your information and paying a registration fee.

4. Follow Naming Rules: Ensure your chosen name follows the character limitations and
conventions mentioned earlier.

Conclusion

In summary, domain names are formed according to the rules and procedures established by the
Domain Name System (DNS). This includes registering the name through a registrar, ensuring its
availability, adhering to character limitations, and following naming conventions. By understanding
these processes, individuals and organizations can create memorable and functional domain names
that help them establish their presence on the internet.

Here are the rewritten questions along with their answers and explanations:

MCQ Questions with their answers

18
1. A ........................... is a software application which enables a user to display and interact
with text, images, videos, music, and other information that could be on a website.
Answer: A. Browser
Meaning: A browser is a software application that allows users to access and navigate the
web, displaying various types of content including text, images, and multimedia.

2. A ........................... is what you see on the screen when you type in a web address, click
on a link, or put a query in a search engine.
Answer: B. Web Page
Meaning: A web page is a document on the World Wide Web that can be displayed in a
browser, containing text, images, and links to other pages.

3. A ..........................., or domain name, is an address where you can be found online.


Answer: A. Web Address
Meaning: A web address, commonly known as a URL (Uniform Resource Locator), is the
address used to access a specific resource on the Internet.

4. A ........................... is an identification string that defines a realm of administrative


autonomy, authority, or control on the Internet.
Answer: C. Domain Name
Meaning: A domain name is a human-readable address used to identify a specific location or
resource on the Internet, usually associated with a website.

5. A ........................... is a label that is assigned to a device connected to a computer


network and that is used to identify the device in various forms of electronic
communication.
Answer: A. Hostname
Meaning: A hostname is a unique name assigned to a device on a network, allowing it to be
identified and accessed by users and other devices.

6. ........................... splits the signal in the telephone wire in two: voice and broadband.
Answer: B. Micro Filter
Meaning: A micro filter is a device used in telecommunications to separate voice signals from
broadband data signals on a telephone line.

7. The ........................... tab allows you to access the set of "Available" networks.
Answer: B. Wireless Networks
Meaning: The Wireless Networks tab in a network management interface displays a list of Wi-
Fi networks available for connection.

8. The IP address could be used either for ........................... or authentication purposes.


Answer: B. Statistic
Meaning: IP addresses can be used to gather statistics about network usage or for
authenticating devices and users on a network.

9. Using the ........................... function we get a list of all the IP addresses the hostname
resolves to.
Answer: A. System.Net.Dns.Get Host Entry
19
Meaning: The System.Net.Dns.GetHostEntry function retrieves the IP address associated with
a specified hostname, providing a way to resolve domain names to IP addresses.

10. A ........................... is the standard hostname given to the address assigned to the
loopback network interface.
Answer: B. Local Host
Meaning: "Local Host" refers to the standard hostname for the loopback interface, typically
used to establish a network connection to the same machine.

11. Communication technologies are unique to networked computer environments and have
come into wide popularity because of the Internet.
Answer: A. True
Meaning: This statement is true as communication technologies, such as email and instant
messaging, have become prevalent due to the Internet and its ability to connect devices and
users globally.

12. Communication technologies do not require more multimedia capabilities of computer


systems and are more taxing of network resources than the others.
Answer: B. False
Meaning: This statement is false; communication technologies often require advanced
multimedia capabilities and can indeed consume significant network resources.

13. An ........................... is an identifier for a computer or device on a TCP/IP network.


Answer: IP Address
Meaning: An IP address is a unique numerical label assigned to each device connected to a
TCP/IP network, enabling identification and communication between devices.

14. TCP handles ........................... between systems and IP handles the routing of packets.
Answer: Packet Flow
Meaning: TCP (Transmission Control Protocol) manages the transmission of data packets
between systems, ensuring reliable and orderly communication, while IP (Internet Protocol) is
responsible for directing those packets to their destinations.

15. The ........................... protocol with seven layers is the usual reference model.
Answer: ISO/OSI
Meaning: The ISO/OSI (International Organization for Standardization/Open Systems
Interconnection) model is a conceptual framework that standardizes the functions of a
telecommunication or computing system into seven layers.

Chapter 2: HTML Introduction


1️. History of HTML

HTML, or Hypertext Markup Language, was created by Tim Berners-Lee in 1991 while he was working
at CERN (the European Organization for Nuclear Research). The goal was to facilitate document
sharing over the internet.

20
• HTML 1️.0: The first version of HTML, released in 1993, allowed for basic document structure,
including headings, paragraphs, links, and images.

• HTML 2️.0: Released in 1995, it included more elements and features, like forms and tables.

• HTML 3.2️: Introduced in 1997, this version added support for applets, tables, and improved
styling.

• HTML 4.01️: Released in 1999, it brought improvements for multimedia support, scripting, and
accessibility.

• XHTML: In the early 2000s, a stricter version of HTML was developed, combining HTML and
XML (extensible Markup Language).

• HTML5: Released in 2014, it introduced new elements and APIs (Application Programming
Interfaces) for multimedia, better support for web applications, and improved semantics.
HTML5 is the current standard.

HTML continues to evolve, with ongoing updates to improve functionality and usability.

2️. Text Manipulating Tags in HTML

HTML provides several tags for formatting and manipulating text. Some commonly used tags include:

• <h1> to <h6>: These are heading tags, with <h1> being the largest and <h6> the smallest.

• <p>: This tag defines a paragraph.

• <strong>: This tag is used to make text bold and indicate strong importance.

• <em>: This tag italicizes text to indicate emphasis.

• <br>: This tag creates a line break in the text.

• <hr>: This tag inserts a horizontal rule, typically used to separate sections.

• <blockquote>: This tag is used for quotations, typically displayed with indentation.

• <span>: A generic inline container that can be used to apply styles or scripts to a portion of
text.

3. Advantages and Limitations of HTML

Advantages:

• Simplicity: HTML is relatively easy to learn and use, making it accessible to beginners.

• Wide Compatibility: HTML is supported by all web browsers, ensuring that web pages can be
viewed across different platforms.

• Structured Documents: HTML helps create a structured document, improving readability and
SEO (Search Engine Optimization).

• Multimedia Integration: HTML supports embedding images, audio, and video, enhancing web
content.

Limitations:

21
• Static Nature: HTML alone is static and cannot create dynamic content. To create dynamic
websites, additional technologies like JavaScript are needed.

• Limited Design Control: HTML provides basic styling capabilities, but for advanced design,
CSS (Cascading Style Sheets) is required.

• Not Suitable for Complex Applications: HTML is not designed for complex applications.
Server-side scripting languages like PHP or frameworks are needed for advanced
functionalities.

4. Difference Between Singular and Paired Tags

• Singular Tags: These tags do not require a closing tag. They are self-contained and perform
their function without needing to enclose other content. Examples include:

o <br>: Inserts a line break.

o <img>: Embeds an image.

o <hr>: Creates a horizontal line.

• Paired Tags: These tags consist of an opening tag and a closing tag, with content in between.
The closing tag is marked with a forward slash (/). Examples include:

o <p>Content goes here</p>: The opening <p> tag starts a paragraph, and the closing
</p> tag ends it.

o <strong>Important text</strong>: The opening <strong> tag indicates strong emphasis,


and the closing </strong> tag ends that emphasis.

5. How to Work on a Web Server

Working on a web server involves several steps:

1. Choose a Web Server Software: Popular options include Apache, Nginx, and Microsoft IIS.
These programs run on the server and handle requests from users' browsers.

2. Install the Server: Depending on the software you choose; you’ll need to install it on your
server. This often involves downloading the software and following installation instructions.

3. Configure the Server: Set up the server to meet your needs. This can include:

o Defining the root directory where your website files will be stored.

o Configuring security settings.

o Setting up virtual hosts if you want to host multiple websites.

4. Upload Your Files: Place your HTML, CSS, and other files in the server's root directory. This can
be done via FTP (File Transfer Protocol) or directly through the server’s file manager.

5. Start the Server: Once configured, start the server software. It will listen for incoming requests
from web browsers.

22
6. Access the Website: You can access your website by entering your server's IP address or
domain name into a web browser. The server will respond by sending the requested files (like
your HTML pages) back to the browser.

7. Maintenance and Monitoring: Regularly update your server software, back up files, and
monitor performance to ensure everything runs smoothly.

By understanding these concepts, you can better grasp how HTML functions within the broader
context of web development!

Here are detailed explanations for your questions regarding HTML and related concepts, formatted
with creative symbols and headings for clarity.

6. Advantages of HTML

HTML (HyperText Markup Language) is the standard language for creating web pages. Here are some
advantages:

Simplicity:
HTML is easy to learn and use. Its syntax is straightforward, making it accessible for beginners.

Platform Independence:
HTML documents can be viewed on various devices (like computers, tablets, and smartphones)
without needing special software.

SEO Friendly:
Search engines can easily read and index HTML content, helping websites rank higher in search
results.

Rich Media Support:


HTML supports images, videos, audio, and other multimedia elements, enhancing user experience.

Hyperlinking:
HTML allows for the creation of hyperlinks, enabling easy navigation between web pages and
websites.

7. Definition of a Web Browser

A web browser is a software application that enables users to access and view content on the World
Wide Web. Here are some key points:

Functionality:
Browsers retrieve, present, and traverse information on the internet. They interpret HTML, CSS, and
JavaScript to display web pages.

Popular Examples:
Some common web browsers include Google Chrome, Mozilla Firefox, Microsoft Edge, and Safari.

User Interface:
Browsers provide an interface that includes a navigation bar, bookmarks, tabs, and various tools for
browsing and searching.

23
Security Features:
Modern browsers include features to protect users from malware, phishing, and insecure websites.

8. What is a Markup Language?

A markup language is a system for annotating a document in a way that is syntactically


distinguishable from the text. Here’s a breakdown:

Structure and Formatting:


Markup languages use tags to define elements within a document. For example, HTML uses tags like
<h1> for headings and <p> for paragraphs.

Types of Markup Languages:


There are various markup languages, including:

• HTML: Used for creating web pages.

• XML (eXtensible Markup Language): Used for data storage and transport.

• Markdown: A lightweight markup language for formatting text.

Purpose:
Markup languages help browsers understand how to display content, allowing for structured,
organized documents.

Here’s a detailed explanation of the differences between DHTML and XHTML, presented in a simple
and creative format:

DHTML (Dynamic HTML)

Definition:
DHTML stands for Dynamic Hypertext Markup Language. It is not a specific language but a
combination of HTML, CSS, and JavaScript that allows web pages to be more interactive and dynamic.

Key Features of DHTML:

• Interactivity:

o Makes web pages dynamic by allowing content to change without reloading the
page.

o Users can interact with elements (e.g., clicking buttons, hovering over items) to
trigger changes.

• CSS Manipulation:

o Allows real-time styling changes using CSS. For example, changing colors, fonts, or
layouts based on user actions.

• JavaScript Functionality:

24
o Uses JavaScript to manipulate the Document Object Model (DOM), enabling
dynamic updates and animations.

• User Experience:

o Enhances user experience by creating engaging and responsive web pages.


Examples include image sliders, drop-down menus, and animated content.

XHTML (Extensible Hypertext Markup Language)

Definition:
XHTML stands for Extensible Hypertext Markup Language. It is a stricter and more standardized
version of HTML that follows XML syntax rules.

Key Features of XHTML:

• Well-formed Structure:

o Requires all elements to be properly nested and closed. For example, <br> must be
written as <br />.

• Case Sensitivity:

o All tags and attributes in XHTML must be in lowercase, unlike HTML where case
sensitivity is not enforced.

• Separation of Content and Presentation:

o Encourages a clear separation between content (HTML) and presentation (CSS),


making code cleaner and easier to maintain.

• Compatibility with XML:

o Being XML-based, XHTML documents can be parsed and processed by XML tools,
allowing for better integration with other technologies.

Key Differences Between DHTML and XHTML

Feature DHTML XHTML

A combination of technologies (HTML,


Nature A stricter version of HTML
CSS, JS)

Static content, focuses on


Interactivity Highly interactive with dynamic content
structure

Syntax Rules Follows HTML rules Follows strict XML syntax rules

25
Feature DHTML XHTML

Case-sensitive (all tags in


Tag Case Sensitivity Not case-sensitive
lowercase)

Browser More consistent due to strict


May vary across browsers
Compatibility standards

Not inherently related to


Use of JavaScript Essential for dynamic behavior
JavaScript

Summary

• DHTML is all about making web pages dynamic and interactive using HTML, CSS, and
JavaScript, enhancing the user experience.

• XHTML, on the other hand, focuses on maintaining a strict syntax and structure, ensuring that
web documents are well-formed and compatible with XML.

By understanding these differences, you can choose the right approach for your web development
needs, ensuring both functionality and structure in your web projects!

Creation of HTML: A Simple Guide

HTML, or HyperText Markup Language, is the standard language used to create web pages. Let’s
explore how HTML came to be, its evolution, and its basic structure in simple terms.

What is HTML?

HTML is a markup language that defines the structure of web pages. It uses "tags" to describe the
elements on a page, such as headings, paragraphs, links, images, and more.

The Birth of HTML

1️. The Beginning: 1️989-1️990

• Tim Berners-Lee: A British computer scientist, Tim Berners-Lee, proposed a system for
sharing information across the Internet.

• First Draft: In 1991, he released the first draft of HTML, which contained 18 tags that allowed
basic text formatting and linking.

2️. HTML 2️.0: 1️995

• Standardization: The Internet Engineering Task Force (IETF) created HTML 2.0 as the first
formal specification of HTML.

• Basic Features: It included essential features like forms, tables, and images.

3. HTML 3.2️: 1️997

26
• Wider Adoption: As the web grew, the World Wide Web Consortium (W3C) took over the
development of HTML.

• New Tags: HTML 3.2 introduced new elements like tables and applets, enhancing the
capabilities of web pages.

4. HTML 4.01️: 1️999

• Improvement and Accessibility: This version focused on improving the language for
accessibility and internationalization.

• Separation of Content and Presentation: It encouraged the use of CSS (Cascading Style
Sheets) for styling.

5. XHTML 1️.0: 2️000

• XML Syntax: XHTML was developed to enforce stricter syntax rules based on XML, allowing for
better data interchange.

• Legacy Support: While it was an evolution, many developers continued to use HTML 4.01.

6. HTML5: 2️01️4

• Major Upgrade: HTML5 introduced new features such as multimedia support (audio and
video), new semantic elements (like <header>, <footer>, and <article>), and APIs for improved
web applications.

• Responsive Design: It made it easier to create web pages that work well on various devices,
from desktops to smartphones.

Basic Structure of an HTML Document

An HTML document consists of several key parts, structured in a specific way. Here’s a simple
breakdown:

<!DOCTYPE html> <!-- Declaration to specify HTML5 -->

<html> <!-- Root element -->

<head> <!-- Metadata and title -->

<title>My First Web Page</title> <!-- Title of the page -->

</head>

<body> <!-- Content of the page -->

<h1>Welcome to My Website</h1> <!-- Main heading -->

<p>This is my first paragraph!</p> <!-- Paragraph -->

<a href="https://example.com">Click here</a> <!-- Hyperlink -->

</body>

</html>

27
Key Elements Explained:

• <!DOCTYPE html>: This tells the browser that this document is an HTML5 document.

• <html>: The root element that contains all other elements.

• <head>: Contains metadata, such as the title and links to stylesheets.

• <title>: Sets the title of the page that appears in the browser tab.

• <body>: Contains the main content of the webpage.

• <h1️> to <h6>: Headings used to organize content hierarchically.

• <p>: Defines a paragraph of text.

• <a>: Creates a hyperlink to another page or website.

Conclusion

HTML has evolved significantly since its inception, becoming the backbone of web development.
Understanding its structure and history is essential for anyone interested in creating websites or web
applications. As the web continues to grow, HTML will keep adapting to meet new challenges and
technologies!

MCQ Questions with their answers

1. ........................... is a markup language which tells the web browser how to display
content.
Answer: C. HTML
Meaning: HTML (Hypertext Markup Language) is the standard markup language used to create
web pages. It provides the structure and layout for web content.

2. A ....................... is a language that annotates text so that the computer can manipulate
the text.
Answer: B. Markup Language
Meaning: A markup language is designed for the processing, definition, and presentation of
text. It uses annotations to define the structure and formatting of the text.

3. ........................... Language can be described as a combination of several technologies


like HTML, client-side JavaScript, and Cascading Style Sheets.
Answer: D. Dynamic Hyper Text Markup
Meaning: Dynamic HTML (DHTML) combines HTML, CSS, and JavaScript to create interactive
and animated web content.

4. ........................... is a document markup language used mainly by mathematicians,


authors, etc. to typeset their content.
Answer: A. LaTeX
Meaning: LaTeX is a high-quality typesetting system commonly used for technical and
scientific documentation, especially for documents that include complex mathematical
expressions.

28
5. .......................... is used in voice interaction between humans and computers.
Answer: B. VoiceXML
Meaning: VoiceXML is a markup language designed for creating interactive voice response
applications, allowing voice-based communication with computers.

6. A ........................... is a program that, using the client/server model and the World Wide
Web’s Hypertext Transfer Protocol (HTTP), serves the files that form Web pages to Web
users.
Answer: A. Web Server
Meaning: A web server is software that delivers web pages to users' browsers via HTTP,
handling requests from clients and sending back the requested content.

7. Every computer on the Internet that contains a ........................... must have a Web server
program.
Answer: D. Web site
Meaning: Any computer hosting a website must have a web server to manage requests and
deliver content over the Internet.

8. ........................... is a software application used to locate, retrieve and also display


content on the World Wide Web, including Web pages, images, video, and other files.
Answer: B. Web Browser
Meaning: A web browser is a software application that allows users to access, navigate, and
display content on the World Wide Web.

9. A/An ........................... is identified by a Uniform Resource Identifier (URI) and may be a


web page, image, video, or other piece of content.
Answer: D. Information Resource
Meaning: An information resource refers to any digital content that can be identified by a URI,
such as web pages, images, and videos.

10. Unpaired tags are also known as ........................... Tags.


Answer: B. Singular or Stand-Alone
Meaning: Unpaired tags, or singular tags, do not require a closing tag. Examples include <img>
and <br>.

11. ........................... present in resources enable users easily to navigate their browsers to
related resources.
Answer: Hyperlinks
Meaning: Hyperlinks are clickable links that connect different web pages or resources,
allowing users to easily navigate the web.

12. Many browsers offer ........................... which extend the capabilities of a browser so it
can display multimedia information.
Answer: Plug-ins
Meaning: Plug-ins are software components that add specific features or functionalities to a
web browser, enabling it to handle various multimedia formats.

13. ........................... are instructions that are embedded directly into the text of an HTML
document.

29
Answer: Tags
Meaning: Tags are the fundamental building blocks of HTML that define the structure and
elements of a web page.

14. In paired tags, the first tag is referred to as Opening Tag and the second tag is referred to
as ........................... Tag.
Answer: Closing
Meaning: The closing tag is used to indicate the end of an element in HTML, and it is typically
written with a forward slash (/) before the tag name.

15. A tag is said to be a ........................... tag if the text is placed between a tag and its
companion tag.
Answer: Paired
Meaning: A paired tag consists of an opening tag and a closing tag that enclose content,
defining the scope of the element.

Chapter 3: HTML Command, Structure & Formatting


1️. What are HTML Commands? How Are They Used?

HTML commands, often referred to as tags, are the building blocks of an HTML document. They are
used to create elements on a webpage. Each command typically consists of an opening tag and a
closing tag.

Example:

• Opening Tag: <p> (indicates the start of a paragraph)

• Closing Tag: </p> (indicates the end of a paragraph)

Usage:

HTML commands are used to structure content, such as headings, paragraphs, links, images, and
lists. They help the web browser understand how to display the content.

2️. Advantages and Limitations of HTML

Advantages:

Simple to Learn: HTML is straightforward, making it accessible for beginners.


Widely Supported: All web browsers support HTML, ensuring consistency across platforms.
SEO Friendly: HTML allows for proper structuring of content, which is beneficial for search engine
optimization.
Multimedia Integration: It supports images, audio, and video, enhancing the user experience.
Hyperlinks: HTML enables the creation of links to other web pages, facilitating easy navigation.

Limitations:

30
Static Nature: HTML alone is static, meaning it does not support dynamic content without
additional languages like JavaScript.
Limited Styling: Basic HTML provides limited styling options. For advanced designs, CSS is
needed.
Browser Compatibility: Older browsers may not fully support the latest HTML features.
No Programming Logic: HTML cannot perform calculations or data manipulations, as it is not a
programming language.

3. Structure of an HTML Program

An HTML program has a standard structure that includes several essential components:

<!DOCTYPE html> <!-- Declaration -->

<html> <!-- Root element -->

<head> <!-- Metadata -->

<title>Page Title</title> <!-- Title of the document -->

</head>

<body> <!-- Main content -->

<h1>Hello, World!</h1> <!-- Heading -->

<p>This is a paragraph.</p> <!-- Paragraph -->

</body>

</html>

Breakdown:

• <!DOCTYPE html>: Defines the document type and HTML version.

• <html>: The root element of the HTML document.

• <head>: Contains metadata, links to CSS files, and the title.

• <body>: Contains the actual content of the webpage, such as text, images, and links.

4. Text Formatting Tags with Examples

HTML provides various tags to format text, making it visually appealing.

Common Text Formatting Tags:

• Bold: <strong>text</strong>
Example: <strong>This is bold text.</strong> results in This is bold text.

• Italic: <em>text</em>
Example: <em>This is italic text.</em> results in This is italic text.

31
• Underline: <u>text</u>
Example: <u>This text is underlined.</u> results in This text is underlined.

• Strike Through: <s>text</s>


Example: <s>This text is strikethrough.</s> results in This text is strikethrough.

5. What Do You Mean by Text Effect?

Text effects refer to the visual enhancements applied to text to improve its presentation and
emphasis. These effects can be achieved through CSS or HTML tags.

Examples of Text Effects:

• Color: Changing the color of text to make it stand out.

• <span style="color: red;">This is red text.</span>

• Font Size: Increasing or decreasing the size of text for emphasis.

• <span style="font-size: 20px;">This is larger text.</span>

• Shadow: Adding shadow effects to text for depth.

• <span style="text-shadow: 2px 2px 4px #000000;">This text has a shadow.</span>

• Background Color: Highlighting text by adding a background color.

• <span style="background-color: yellow;">This text has a background color.</span>

Text effects enhance readability and visual appeal, making web pages more engaging for users.

This overview covers the key concepts of HTML, including commands, structure, text formatting, and
effects, in a simple and organized manner. Let me know if you have any more questions!

Sure! Let's break down these topics one by one in a simple and detailed way, using headings and
creative symbols for clarity.

6. Different Types of Header Tags

Header tags in HTML are used to define headings on a webpage. There are six levels of header tags,
ranging from <h1> to <h6>. Here’s what they look like:

• <h1️>: This is the highest level heading, typically used for the main title of a page.

o Example: <h1>Welcome to My Website</h1>

• <h2️>: This tag represents the second level heading, used for main sections.

o Example: <h2>About Us</h2>

• <h3>: The third level heading, used for subsections under an <h2>.

32
o Example: <h3>Our Mission</h3>

• <h4>: This is used for further subsections under an <h3>.

o Example: <h4>Our Values</h4>

• <h5>: The fifth level heading, used for minor headings.

o Example: <h5>Commitment to Excellence</h5>

• <h6>: This is the lowest level heading, often used for the least important sections.

o Example: <h6>Contact Information</h6>

Importance of Header Tags

• They help structure the content.

• Search engines use them to understand the content hierarchy.

• They improve accessibility for users with screen readers.

7. What is Preformatted Text?

Preformatted text in HTML is used to display text exactly as it is written in the HTML document,
including spaces and line breaks. This is done using the <pre> tag.

• Example:

• <pre>

• This is preformatted text.

• It preserves spaces and

• line breaks.

• </pre>

Features of Preformatted Text

• Displays text in a fixed-width font (usually Courier).

• Maintains whitespace and formatting, making it useful for code snippets or ASCII art.

8. Discuss Preformatted Text

Preformatted text is essential when you want to show text that requires a specific layout. The <pre>
tag tells the browser to display text in the exact format it is written.

• Use Cases:

o Code Samples: When showing programming code, it’s vital to maintain indentation and
formatting.

33
o Poems or Lyrics: Any text where formatting is crucial for understanding.

Example:

<pre>

function helloWorld() {

console.log("Hello, World!");

</pre>

This code will display exactly as written, maintaining indentation and line breaks.

9. Guidelines for Rendering HTML Pre Element

When using the <pre> element, consider the following guidelines:

• Maintain Formatting: Always remember that the <pre> tag preserves whitespace and line
breaks. Use it when you need this feature.

• Use Appropriate Font Size: The default font may not always be readable, so consider
adjusting font size and type for better visibility.

• Avoid Excessive Length: Avoid using <pre> for very long text blocks as it can lead to
horizontal scrolling, making it hard to read.

• Combine with Other Elements: You can use <pre> with other HTML elements to create
more complex layouts while maintaining the preformatted text.

1️0. Tags Used for Text Formatting

HTML provides various tags for formatting text to enhance readability and structure. Here are some
commonly used formatting tags:

• <strong>: Makes text bold, indicating strong importance.

o Example: <strong>Important!</strong> will display as Important!

• <em>: Italicizes text, indicating emphasis.

o Example: <em>Emphasized Text</em> will display as Emphasized Text.

• <u>: Underlines text.

o Example: <u>Underlined Text</u> will display as Underlined Text.

• <small>: Reduces the font size of text.

o Example: <small>This is smaller text</small> will display as This is smaller text.

• <mark>: Highlights text, typically for search results.


34
o Example: <mark>Highlighted Text</mark> will display as Highlighted Text.

• <del>: Indicates deleted text, usually shown with a strikethrough.

o Example: <del>This text is deleted</del> will display as This text is deleted.

Why Use Formatting Tags?

• Enhance Clarity: Helps convey the importance of specific text.

• Improves Readability: Makes content easier to digest.

• Visual Appeal: Creates a more engaging experience for readers.

MCQ Questions with their answers

1. HTML ........................... tells a web browser where the HTML part in your document
begins and ends.
Answer: B. tags
Meaning: Tags in HTML are special codes that indicate the start and end of HTML elements,
allowing the web browser to understand how to render the content.

2. The “...........................” contains all of the document’s header information like the web
document’s title and information about the document itself.
Answer: D. head
Meaning: The <head> section of an HTML document includes metadata, title, links to
stylesheets, and scripts, which provide essential information about the document.

3. The HTML pre element inserts a block of ........................... text.


Answer: A. preformatted
Meaning: The <pre> tag is used to display text in a fixed-width font, preserving spaces and line
breaks, making it ideal for preformatted content.

4. A ........................... tag controls how the characters are formatted.


Answer: B. physical
Meaning: Physical tags in HTML directly affect the visual presentation of text, such as bold or
italic styles, by altering the way the content appears.

5. A ........................... tag describes how the text is being used, not necessarily how it is
formatted.
Answer: D. logical character
Meaning: Logical character tags indicate the meaning of the text (e.g., emphasis or strong
importance) rather than just its visual appearance.

6. The ........................... font style slants the text to the right and thus can also be used to
draw special attention to one or more words.
Answer: A. italics
Meaning: Italics are used in text formatting to create a slanted effect, often employed for
emphasis or to denote titles of works.

35
7. A HTML ........................... is basically separated into two parts: the head and the body.
Answer: D. Document
Meaning: An HTML document is structured into two main sections, the <head> and the
<body>, where the head contains metadata and the body contains the content displayed on
the web page.

8. Every well-written HTML document begins with a basic declaration that defines what type
of document it is, and this declaration is made using the ........................... tag.
Answer: C. !DOCTYPE
Meaning: The <!DOCTYPE> declaration is used to specify the HTML version being used,
helping browsers render the page correctly.

9. ........................... tag is used to create a horizontal line on your page you use the empty
tag.
Answer: A.
Meaning: The <hr> tag creates a horizontal rule (line) in HTML, often used to separate sections
of content visually.

10. In HTML, bold copy is created by using the ........................... tag.


Answer: C. strong
Meaning: The <strong> tag is used to define text with strong importance, which typically
renders as bold in browsers.

11. Using ........................... is helpful in situations where you just need one or two spaces in
between characters or words for stylistic or aesthetic effect.
Answer:
Meaning: The &nbsp; (non-breaking space) entity creates a space in HTML where regular
whitespace is collapsed, allowing for precise spacing.

12. The tag ........................... changes the color of a few words or a section of text.
Answer: Font Color
Meaning: The <font> tag with the color attribute can be used to change the text color in HTML,
although it is now deprecated in favor of CSS.

13. The code to align text in HTML for a post or single page is ...........................
Answer:
Meaning: The <p align="direction"> attribute is used to specify the alignment of paragraph text
in HTML (e.g., left, right, center).

14. ........................... tag is a non-standard tag and can be very irritating if used on large areas
of text, so use it sparingly.
Answer:
Meaning: The <blink> tag was used to create blinking text but is considered non-standard and
can be distracting, so it's not recommended for use in modern web design.

15. ........................... tag is used to create a moving text effect, similar to some “matrix” type
LED and illuminated signs.
Answer:

36
Meaning: The <marquee> tag creates scrolling text effects in HTML, but it is also deprecated
and should be used with caution.

Chapter 4: HTML List and Graphs


1️. Emphasizing Information for an Order List

When preparing an order list, it's important to focus on specific information to ensure accuracy and
efficiency. Here are the key elements to emphasize:

• Item Description: Clearly state what each item is (e.g., product name, size, color).

• Quantity: Specify how many of each item you need.

• Price: Include the cost of each item for budgeting.

• Supplier Information: Note the source of each item for easy reordering.

• Delivery Date: Mention when you expect to receive the items.

• Special Instructions: Include any specific details or requests for each item.

2️. Methods for HTML List

HTML offers several methods to create lists, primarily categorized into three types:

• Ordered Lists (ol): For lists where the order matters (e.g., steps in a recipe).

• Unordered Lists (ul): For lists where the order doesn't matter (e.g., shopping items).

• Description Lists (dl): For lists of terms and their descriptions (e.g., glossary terms).

Each type uses specific HTML tags to define the list and its items.

3. Creating Lists in HTML

Let’s look at how to create ordered lists, unordered lists, and nested lists in HTML.

Ordered Lists (ol)

An ordered list is created using the <ol> tag, and each item is defined with the <li> tag.

<ol>

<li>Step 1: Gather ingredients</li>

<li>Step 2: Mix the ingredients</li>

<li>Step 3: Bake for 30 minutes</li>

</ol>

Unordered Lists (ul)


37
An unordered list is created using the <ul> tag, with each item also defined by the <li> tag.

<ul>

<li>Milk</li>

<li>Bread</li>

<li>Eggs</li>

</ul>

Nested Lists

You can create lists within lists (nested lists) by placing an ordered or unordered list inside a list item.

<ul>

<li>Fruits

<ul>

<li>Apple</li>

<li>Banana</li>

</ul>

</li>

<li>Vegetables

<ol>

<li>Carrot</li>

<li>Broccoli</li>

</ol>

</li>

</ul>

4. IMG Attributes

The <img> tag is used to embed images in HTML. Here are some important attributes:

• src: Specifies the path to the image file.

• alt: Provides alternative text for the image, which is important for accessibility and displays if
the image fails to load.

• width: Defines the width of the image in pixels or as a percentage.

• height: Defines the height of the image in pixels or as a percentage.

• title: Adds a tooltip that appears when the user hovers over the image.

38
Example:

<img src="image.jpg" alt="A beautiful sunset" width="500" height="300" title="Sunset View">

5. Graphic Image Alignment Parameters in HTML

Aligning images in HTML can enhance the layout of your page. Here are some alignment methods:

• Align Attribute (Deprecated): Older versions of HTML used the align attribute. Although it's
deprecated in HTML5, it's good to know for legacy code.

<img src="image.jpg" align="left" alt="Image on the left">

• CSS Styles: The modern way to align images is through CSS.

<img src="image.jpg" style="float: left; margin: 10px;" alt="Floating image">

Example of CSS Alignment:

<style>

.center {

display: block;

margin-left: auto;

margin-right: auto;

</style>

<img src="image.jpg" class="center" alt="Centered image">

Using these methods helps you control the layout and position of images on your web page.

6. Three Different Types of HTML Lists

HTML provides three main types of lists, each serving different purposes:

1️. Unordered List (<ul>)

• Description: Displays items in no order.

• Use Case: Best for lists where the sequence of items doesn’t matter.

• Example:

• <ul>

• <li>Apples</li>

• <li>Bananas</li>
39
• <li>Cherries</li>

• </ul>

2️. Ordered List (<ol>)

• Description: Displays items in a specific sequence, using numbers or letters.

• Use Case: Ideal for lists where the order is important, like steps in a recipe.

• Example:

• <ol>

• <li>Preheat the oven.</li>

• <li>Mix the ingredients.</li>

• <li>Bake for 20 minutes.</li>

• </ol>

3. Description List (<dl>)

• Description: Comprises a set of terms and their descriptions.

• Use Case: Useful for defining terms, like a glossary.

• Example:

• <dl>

• <dt>HTML</dt>

• <dd>Hypertext Markup Language</dd>

• <dt>CSS</dt>

• <dd>Cascading Style Sheets</dd>

• </dl>

7. Difference Between Unordered List and Ordered List

Feature Unordered List (<ul>) Ordered List (<ol>)

Appearance Bulleted items (•) Numbered or lettered items (1., A.)

Order Significance No significance to the order Order is significant and meaningful

Use Case Shopping lists, features Instructions, ranked lists

8. Methods for Unordered List Item

40
• Adding Items: Use the <li> tag to add items within an <ul>.

• <ul>

• <li>Item 1</li>

• <li>Item 2</li>

• </ul>

• Nesting Lists: You can create a sub-list by adding another <ul> within an <li>.

• <ul>

• <li>Fruits

• <ul>

• <li>Apple</li>

• <li>Banana</li>

• </ul>

• </li>

• <li>Vegetables</li>

• </ul>

• Styling Lists: Use CSS to change bullet styles, spacing, etc.

• ul {

• list-style-type: square; /* Change bullet type */

• }

9. How to Insert an Image in the Current Page

To insert an image in HTML, use the <img> tag. Here’s how:

• Syntax:

• <img src="image_url.jpg" alt="Description of image" width="500" height="300">

• Attributes:

o src: Specifies the image source URL.

o alt: Provides alternative text for the image (important for accessibility).

o width and height: Set the dimensions of the image.

• Example:

• <img src="https://example.com/photo.jpg" alt="A beautiful landscape" width="600"


height="400">

41
1️0. Classes of HTML List

HTML lists can be categorized based on their function and structure:

1️. Block-Level Lists

• Description: These lists occupy the full width of the parent container.

• Example: Unordered and ordered lists are typically block-level elements.

2️. Inline Lists

• Description: Lists displayed inline, often used in navigation menus.

• Example: Use CSS to style <li> elements as inline-block.

• li {

• display: inline-block;

• }

3. Nested Lists

• Description: Lists within lists, useful for hierarchies.

• Example:

• <ul>

• <li>Main Item

• <ul>

• <li>Sub Item 1</li>

• <li>Sub Item 2</li>

• </ul>

• </li>

• </ul>

MCQ Questions with their answers

1. The ........................... classes allow you to easily create lists within your HTML pages.
Answer: A. HTML List
Meaning: The HTML List classes, such as <ul> (unordered list) and <ol> (ordered list), enable
you to create various types of lists on your web pages.

2. The ........................... OrderedList and OrderedListItem are used to create ordered lists in
your HTML pages.
Answer: C. Classes

42
Meaning: Classes like OrderedList and OrderedListItem are used in some frameworks or
libraries to create ordered lists, enhancing organization and styling.

3. By using the methods in ..........................., you can override the numbering and type for a
specific item in the list.
Answer: D. OrderedListItem
Meaning: The OrderedListItem class provides methods to customize the appearance and
numbering of specific items in an ordered list.

4. ........................... lists are purely a list of related items, in which their order does not
matter nor do they have a numbered or alphabetical list element.
Answer: B. Unordered
Meaning: Unordered lists consist of items where the sequence is not important, typically
represented with bullet points.

5. By default, most browsers represent each list item with a ...........................


Answer: C. Bullet
Meaning: In unordered lists, list items are generally represented by bullet points (often
circular) by default.

6. The solid dot is referred to as the list item element and can be changed using
...........................
Answer: C. CSS
Meaning: CSS (Cascading Style Sheets) can be used to modify the appearance of list items,
including changing the bullet style.

7. ........................... lists place strong importance on the order of items.


Answer: A. Ordered
Meaning: Ordered lists are used when the sequence of items is significant, such as in
instructions or rankings.

8. Creating a definition list in HTML is accomplished using the ........................... element.


Answer: D. dl
Meaning: The <dl> (definition list) element is used to create lists of terms and their definitions
in HTML.

9. The ........................... actually requires two elements: the definition term element, dt,
and the definition description element, dd.
Answer: B. Definition list
Meaning: A definition list requires both <dt> (definition term) and <dd> (definition description)
elements to properly format terms and their meanings.

10. An image that is displayed on a web browser is referred to as an “...........................”


Answer: C. Inline image
Meaning: An inline image is one that is displayed directly within the content of a web page, as
opposed to being a background image.

11. ........................... tag indicates that an image—such as a photograph, icon, animation,


cartoon, or other graphic—is to be displayed at that location.

43
Answer: <IMG>
Meaning: The <IMG> tag is used in HTML to embed images in a web page.

12. The only way to center a graphic horizontally on a page is to use <CENTER>&</CENTER>
tags around the ........................... tag.
Answer: <IMG SRC>
Meaning: The <CENTER> tags can be used to center an image in older HTML standards,
wrapping around the <IMG SRC> tag.

13. “...........................” aligns the bottom of the image with the bottom of the current line.
Answer: ABSBOTTOM
Meaning: The ABSBOTTOM value is used in the align attribute of the <IMG> tag to position the
bottom of the image with the baseline of surrounding text.

14. ........................... indicates a server-side image map.


Answer: ISMAP
Meaning: The ISMAP attribute in an <IMG> tag indicates that the image is part of a server-side
image map, linking different areas of the image to different destinations on the server.

15. ........................... indicates a client-side image map.


Answer: USEMAP
Meaning: The USEMAP attribute is used in the <IMG> tag to indicate that the image contains a
client-side image map, where clickable areas are defined using an associated <map> element.

Chapter 5: Creating Tables and Frames


1️. How HTML Tables are Created

HTML tables are used to display data in a structured format with rows and columns. Tables help
organize information visually.

Basic Structure of an HTML Table:

• A table starts with the <table> tag.

• Inside the table, you create rows with the <tr> tag.

• Each row contains data cells represented by <td> (table data) tags.

• You can also add header cells with the <th> (table header) tag.

2️. Steps Involved in Creating HTML Tables

To create an HTML table, follow these simple steps:

Step 1️: Start the Table

<table>

Step 2️: Add a Table Header (Optional)

<tr>

44
<th>Header 1</th>

<th>Header 2</th>

</tr>

Step 3: Add Table Rows and Data Cells

<tr>

<td>Data 1</td>

<td>Data 2</td>

</tr>

<tr>

<td>Data 3</td>

<td>Data 4</td>

</tr>

Step 4: Close the Table

</table>

Example of a Complete HTML Table:

<table>

<tr>

<th>Name</th>

<th>Age</th>

</tr>

<tr>

<td>Alice</td>

<td>30</td>

</tr>

<tr>

<td>Bob</td>

<td>25</td>

</tr>

</table>

3. Linking Documents
45
Linking documents in HTML means connecting one web page to another. This is primarily done using
hyperlinks, which allow users to navigate between different resources.

Creating a Hyperlink:

• Use the <a> tag to create a hyperlink.

• The href attribute specifies the URL of the page you want to link to.

Example:

<a href="https://www.example.com">Visit Example</a>

When a user clicks on this link, it will take them to the specified URL.

4. Three Attributes of the <BODY> Tag

The <body> tag represents the content of the web page. Here are three important attributes you can
specify:

• bgcolor: Sets the background color of the webpage.

• <body bgcolor="#f0f0f0"> <!-- Light gray background -->

• text: Specifies the color of the text on the page.

• <body text="#000000"> <!-- Black text -->

• link: Defines the color of unvisited links.

• <body link="#0000FF"> <!-- Blue links -->

5. Hyperlinks and Their Types

Definition of Hyperlinks: Hyperlinks, or links, are elements in a web page that allow users to click
and navigate to another page or resource. They are fundamental to web navigation.

Types of Hyperlinks:

• Internal Links: These link to another page within the same website.

• <a href="about.html">About Us</a>

• External Links: These link to a page on a different website.

• <a href="https://www.example.com">Visit Example</a>

• Anchor Links: These link to a specific section within the same page.

• <a href="#section1">Go to Section 1</a>

Conclusion: Hyperlinks enhance the user experience by allowing easy navigation and access to more
information.

46
6. Justify the Use of Link List Creation in an HTML Document

What is a Link List?

A link list is a collection of hyperlinks that allows users to navigate through a website or between
different websites.

Reasons to Use Link Lists

• Improved Navigation: Link lists provide a clear structure for users to find related content
easily.

• Accessibility: They help visually impaired users using screen readers to understand the
layout and navigate effectively.

• SEO Benefits: Search engines use link lists to crawl and index pages, improving the site's
visibility.

• Organization: They help in categorizing related links (e.g., resources, references) making it
easier to manage content.

Example

<ul>

<li><a href="https://example.com">Example Site</a></li>

<li><a href="https://anotherexample.com">Another Example</a></li>

</ul>

7. How to Display a Table with Borders

Creating a Table in HTML

Tables are used to present data in rows and columns.

Adding Borders

To display a table with borders, you can use the border attribute in the <table> tag or apply CSS styles.

Example

<table border="1">

<tr>

<th>Name</th>

<th>Age</th>

</tr>

<tr>

<td>Alice</td>

47
<td>30</td>

</tr>

<tr>

<td>Bob</td>

<td>25</td>

</tr>

</table>

Using CSS for Borders

<style>

table {

border-collapse: collapse; /* Merge borders */

th, td {

border: 1px solid black; /* Create cell borders */

padding: 8px; /* Add padding */

</style>

8. How to Link to a Page on Another Website

Creating External Links

To link to a page on another website, use the <a> (anchor) tag with the href attribute pointing to the
URL.

Example

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

• href: Specifies the URL to which the link points.

• target="_blank": Opens the link in a new tab.

Explanation

• When users click on this link, they will be directed to the specified website. Using
target="_blank" is useful for keeping users on your site while allowing them to explore other
sites.

48
9. Steps to Move to a Specific Location on a Web Page

Using Anchor Links

To move to a specific location on a web page, you can use anchor links, which navigate to a specific
section of the page.

Steps

1. Create an Anchor: Use the id attribute to mark the specific location.

2. Link to the Anchor: Create a link that points to the anchor.

Example

<!-- Step 1: Create an Anchor -->

<h2 id="section1">Section 1</h2>

<p>This is Section 1 content.</p>

<!-- Step 2: Create a Link -->

<a href="#section1">Go to Section 1</a>

Explanation

• Clicking the link will scroll the page to the part marked with id="section1". This is particularly
useful for long web pages with multiple sections.

MCQ Questions with their answers

1. Tables are defined with the ........................... tag.


Answer: C. <table>
Meaning: The <table> tag is used to create a table in HTML, which can hold rows and columns
of data.

2. The letters ........................... stands for “table data,” which is the content of a data cell.
Answer: A. TD
Meaning: The <td> tag (table data) is used to define individual cells within a table row,
containing the data displayed in the table.

3. A ........................... can contain text, images, lists, paragraphs, forms, horizontal rules,
tables, etc.
Answer: C. Data Block
Meaning: A data block refers to a section of content that can encompass various elements like
text, images, and more, typically represented in structured formats like tables.

4. A table row is defined by ........................... tag.


Answer: D. <tr>

49
Meaning: The <tr> tag (table row) is used to define a row in an HTML table, which can contain
one or more data cells.

5. When you finish all of the cells for a row, you would then close the row with the ending row
tag, ...........................
Answer: C. </tr>
Meaning: The </tr> tag is used to close a table row definition in HTML, indicating the end of that
row's content.

6. If you do not specify a ........................... attribute, the table will be displayed without any
borders.
Answer: A. Border
Meaning: The border attribute determines whether the table has visible borders. Without this
attribute, the table will not display any borders.

7. Headings in a table are defined with the ........................... tag.


Answer: B. <th>
Meaning: The <th> tag (table header) is used to define header cells in a table, which are
typically bold and centered by default.

8. Links are defined with the ........................... tag.


Answer: D. <a>
Meaning: The <a> tag (anchor) is used to create hyperlinks in HTML, allowing users to navigate
to different pages or resources.

9. The text between the <a> and the </a> is used as the ........................... for the link.
Answer: C. Caption
Meaning: The text inside the <a> tags serves as the caption or clickable text of the link, which
users see and click on.

10. You can use a/an ........................... to separate words in your file names.
Answer: A. Underscore, “_”
Meaning: Using an underscore (_) is a common practice for separating words in file names,
enhancing readability.

11. If the file is not present in the current directory, a ........................... path can be specified.
Answer: Relative or Absolute
Meaning: A relative path refers to the location of a file in relation to the current directory, while
an absolute path specifies the full path from the root of the file system.

12. If you want to preserve all of your links and space of your blog you can use
........................... box which contains link list.
Answer: Scrollable
Meaning: A scrollable box is a user interface element that allows users to scroll through a list
of links, keeping the blog layout neat and organized.

13. The ........................... tag defines a division or a section in an HTML document. In a div
element, the overflow property is set to auto.
Answer: <div>

50
Meaning: The <div> tag is used to create a block-level division in an HTML document, often
used for styling and layout purposes.

14. <img> causes an “...........................” to be inserted into the output.


Answer: Inline Image
Meaning: The <img> tag is used to embed images within a webpage, allowing the image to
appear inline with the surrounding content.

15. Image ........................... are constructed by embedding an <img> tag inside of an anchor
element <a>.
Answer: Links
Meaning: Image links are created by wrapping an <img> tag within an <a> tag, allowing users to
click on the image to navigate to a different page or resource.

Chapter 6: DHTML
Here’s a differentiation between HTML and DHTML in tabular form:

HTML (Hypertext Markup


Aspect DHTML (Dynamic HTML)
Language)

A standard markup language for An extension of HTML that includes dynamic


Definition
creating web pages. content.

Static content; the structure and


Static vs. Dynamic content; allows changes to the
content do not change after
Dynamic content without reloading the page.
loading.

Technologies
Uses HTML tags only. Combines HTML, CSS, and JavaScript.
Used

Limited interactivity; mainly static High interactivity; supports animations,


Interactivity
links and forms. updates, and user interactions.

User Basic user experience; primarily Enhanced user experience; allows for
Experience displays content. interactive features and real-time updates.

Browser Requires modern browsers that support


Supported by all web browsers.
Support JavaScript and CSS.

Basic web pages with text and Web applications with interactive elements
Examples
images. like menus, forms, and animations.

More complex; requires understanding of


Easier to learn; suitable for
Learning Curve additional technologies like CSS and
beginners.
JavaScript.

Explanation in Simple Language


51
What is HTML?

HTML stands for HyperText Markup Language. It's the foundation of web pages. Think of it as the
skeleton of a webpage. With HTML, you create the structure and layout by using various tags (like <h1>
for headings, <p> for paragraphs, and <a> for links). However, HTML alone cannot create interactive or
dynamic content. It simply displays text and images as they are written.

What is DHTML?

DHTML, or Dynamic HTML, is a more advanced version of HTML. It combines HTML with Cascading
Style Sheets (CSS) and JavaScript to create interactive and animated web pages. DHTML allows
content to change without needing to reload the entire page. For instance, when you hover over a
button and it changes color or reveals a hidden menu, that’s DHTML in action.

Key Differences Explained

• Static vs. Dynamic:

o HTML: Once the page is loaded, nothing changes unless you refresh it.

o DHTML: The page can change in response to user actions without a full refresh.

• Interactivity:

o HTML: You can click links or fill out forms, but there’s little else happening.

o DHTML: You can have moving elements, dropdown menus, and other engaging
features.

• User Experience:

o HTML: Just shows you the content; it’s pretty basic.

o DHTML: Makes the website lively and engaging, improving the overall experience.

Conclusion

In summary, HTML is essential for building the basic structure of web pages, while DHTML takes it a
step further by introducing interactivity and dynamic content. If you want to create modern, engaging
web experiences, learning DHTML (or the technologies it comprises) is the way to go!

2️. Advantages of DHTML over HTML

• Interactivity: DHTML allows users to interact with web pages through animations and
dynamic changes, making the experience more engaging.

• Real-time Updates: Content can be updated in real-time without requiring a full page
reload, enhancing user experience.

• Styling Control: With CSS in DHTML, developers can apply styles dynamically, creating
visually appealing designs.

52
• Responsive Design: DHTML supports responsive layouts that adapt to different screen
sizes, improving accessibility on various devices.

3. Advantage of Using an External Style Sheet

• Separation of Concerns: Using an external style sheet (CSS file) separates content from
presentation, making the HTML cleaner and easier to manage.

• Consistency: You can apply the same styles across multiple pages, ensuring a uniform
look and feel throughout the website.

• Ease of Maintenance: Changing styles in one external file updates all linked pages, saving
time and effort in maintaining your website.

• Improved Loading Time: Browsers cache external style sheets, which can improve page
load times when navigating between different pages.

4. What is CSS?

• Definition: CSS (Cascading Style Sheets) is a stylesheet language used to describe the
presentation of a document written in HTML. It controls the layout, colors, fonts, and overall
visual appearance of web pages.

• Key Features:

o Selectors: CSS uses selectors to target HTML elements for styling (e.g., class, id, or
element types).

o Box Model: CSS manages spacing and positioning of elements using margins, borders,
padding, and content areas.

o Responsive Design: Media queries allow CSS to adapt layouts based on the device’s
screen size.

• Benefits:

o Enhances visual appeal and user experience.

o Facilitates quick updates to styles without altering HTML.

5. What is Class?

• Definition: In HTML and CSS, a class is an attribute that can be added to an HTML element
to apply specific styles or behaviors. It allows multiple elements to share the same style.

• Usage:

o Classes are defined in the HTML element using the class attribute. For example: <div
class="myClass">Content</div>.
53
o In CSS, styles are applied to all elements with that class. For example:

o .myClass {

o color: blue;

o font-size: 20px;

o }

• Benefits:

o Reusability: You can define styles once and apply them to multiple elements, reducing
redundancy.

o Customization: Classes provide flexibility in styling different elements without altering


the core HTML structure.

6. What is an External Style Sheet? How to Link?

Definition:
An external style sheet is a separate CSS (Cascading Style Sheets) file that contains styles for
multiple web pages. This allows for a consistent design across a website.

Linking an External Style Sheet:


To link an external style sheet to an HTML document, use the <link> tag in the <head> section of your
HTML file. Here’s how you do it:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

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

<link rel="stylesheet" href="styles.css"> <!-- Linking the external stylesheet -->

<title>My Website</title>

</head>

<body>

<h1>Hello World!</h1>

</body>

</html>

7. What are the Features of DHTML?

Dynamic HTML (DHTML) is an advanced version of HTML that allows for interactive and animated
web pages. Here are some of its key features:
54
• Dynamic Content:

o Content can change without reloading the entire page. This enhances user experience.

• Interactive Elements:

o Users can interact with elements like buttons, forms, and images, leading to a more
engaging experience.

• Animations:

o DHTML allows for animations and transitions, making the web pages visually appealing.

• Positioning:

o Elements can be moved around the page, enabling creative layouts.

• Event Handling:

o DHTML responds to user actions, such as clicks and key presses, to trigger events and
updates.

8. How Does DHTML Work with JavaScript?

Integration of DHTML and JavaScript:


DHTML works hand-in-hand with JavaScript to create dynamic content. Here’s how they collaborate:

• JavaScript Manipulation:

o JavaScript can change the content and style of HTML elements dynamically. For
example, you can use JavaScript to change text or hide/show elements.

• Event Handling:

o JavaScript listens for user actions (like clicks) and executes code to manipulate the
page in real time.

• DOM (Document Object Model):

o DHTML utilizes the DOM, which represents the structure of a web page. JavaScript can
interact with the DOM to change elements, styles, and attributes.

Example of JavaScript with DHTML:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>DHTML Example</title>

<style>

#myDiv {

width: 100px;
55
height: 100px;

background-color: blue;

</style>

<script>

function changeColor() {

document.getElementById("myDiv").style.backgroundColor = "red";

</script>

</head>

<body>

<div id="myDiv"></div>

<button onclick="changeColor()">Change Color</button>

</body>

</html>

9. What are the Attributes that Make Up a DHTML?

Attributes of DHTML:
DHTML is characterized by several key attributes that enable its dynamic capabilities:

• Style Properties:

o Attributes like color, background-color, font-size, etc., are modified using CSS.

• Element Positioning:

o Attributes such as position, top, left, z-index allow precise control over the layout.

• Visibility and Display:

o Attributes like visibility and display determine whether elements are visible or hidden.

• Event Attributes:

o Attributes that trigger JavaScript functions (like onclick, onmouseover) enable


interactivity.

1️0. Illustrate the Concept of Embedded Style Sheet with Example

Embedded Style Sheet Definition:


An embedded style sheet is CSS code included directly within an HTML document using the <style>
tag in the <head> section. It affects only the specific page where it's defined.

Example of an Embedded Style Sheet:


56
<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

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

<title>Embedded Style Sheet</title>

<style>

body {

background-color: lightgray;

h1 {

color: blue;

p{

font-size: 20px;

</style>

</head>

<body>

<h1>Welcome to My Page!</h1>

<p>This is a simple example of an embedded style sheet.</p>

</body>

</html>

In this example, the CSS styles defined in the <style> tag will only apply to this specific HTML
document.

MCQ Questions with their answers

1. ........................ enables authors to create visually compelling Web sites without the
overhead of server-side programs or complicated sets of controls to achieve special
effects.
Answer: B. DHTML
Meaning: DHTML (Dynamic HTML) allows authors to create interactive and animated web

57
pages using a combination of HTML, CSS, and JavaScript without relying heavily on server-side
programming.

2. ............................ is used for the presentation part of the web page.


Answer: C. CSS (Cascading Style Sheet)
Meaning: CSS is a stylesheet language that describes the presentation of a document written
in HTML or XML, allowing developers to control the layout, colors, fonts, and overall visual
appearance of web pages.

3. .......................... is the weakest link in DHTML as many of the browsers do not support the
DOM functionality.
Answer: C. DOM (Dynamic Object Model)
Meaning: The DOM is a programming interface that browsers use to structure and manipulate
HTML and XML documents. Its inconsistent support across different browsers can be a
limitation for DHTML applications.

4. CSS was first developed in ................................., as a way for Web developers to define
the look and feel of their Web pages.
Answer: A. 1️997
Meaning: CSS was introduced in 1997 to provide web developers with a standardized way to
style web pages, enabling better separation of content and presentation.

5. External style sheet is also known as ...................................


Answer: D. Linked style sheet
Meaning: An external style sheet is a separate CSS file linked to an HTML document, allowing
the same stylesheet to be used across multiple pages, promoting consistency and easier
maintenance.

6. .......................... style sheet is used when you want to define styles for the current page.
Answer: B. Embedded
Meaning: An embedded (or internal) style sheet is defined within the <style> tags in the HTML
document, applying styles specifically to that page.

7. An ...................................... style sheet is a separate file where you can declare all the
styles that you want to use on your website.
Answer: A. External
Meaning: An external style sheet is a standalone CSS file that can be linked to multiple HTML
pages, allowing for centralized control of the website's design.

8. The ................... element changes the style of the text it encloses.


Answer: C. SPAN
Meaning: The <span> element is an inline container used to apply styles or manipulate a part
of the text without affecting the surrounding elements.

9. The ......................... element includes a paragraph break.


Answer: D. DIV
Meaning: The <div> element is a block-level container that can be used to group content,
including creating paragraph breaks and defining sections in an HTML document.

58
10. The DIV elements define ......................... divisions in your web page.
Answer: B. Logical
Meaning: <div> elements are used to create logical divisions in a web page, allowing
developers to structure content semantically.

11. The DIV element gives you the chance to define the ........................ of whole sections of
the HTML.
Answer: A. Style
Meaning: The <div> element allows you to apply styles to entire sections of content, facilitating
layout control and styling.

12. CSS would not be very useful if it did not allow you to have many different types of formats
for a single HTML tag.
Answer: A. True
Meaning: CSS is valuable because it enables multiple styles to be applied to the same HTML
element, allowing for varied presentations and responsive designs.

13. For using classes, you are not required to add an extension to the typical CSS code.
Answer: B. False
Meaning: While using classes in CSS does not require an extension, they must be properly
defined in the CSS file to work effectively in the HTML.

14. DHTML files are huge compared to other interactive media.


Answer: B. False
Meaning: DHTML files are typically not larger than other types of interactive media. In fact, they
can be more efficient since they combine HTML, CSS, and JavaScript into a cohesive format.

15. The World Wide Web Consortium or the W3C is currently implementing standards for
DHTML technologies.
Answer: A. True
Meaning: The W3C is responsible for developing web standards and guidelines, including
those that pertain to DHTML technologies, ensuring consistency and interoperability across
the web.

Chapter 7: Introduction to Java Script


1️. Why Scripting Languages Are Used?

Scripting languages are used for various reasons, including:

• Web Development: They are essential for creating interactive and dynamic web pages. For
example, JavaScript is commonly used to enhance user experiences on websites.

• Automation: Scripting languages automate repetitive tasks, making processes faster and
reducing human error. For instance, shell scripts can automate system administration tasks.

59
• Rapid Development: They allow developers to write code quickly and easily. The syntax of
scripting languages is often simpler than compiled languages, enabling faster prototyping.

• Integration: Scripting languages can easily integrate with other applications and services,
facilitating data exchange and communication between different systems.

2️. Brief History of JavaScript

• Origin (1️995): JavaScript was created by Brendan Eich while working at Netscape
Communications Corporation. It was initially called Mocha, later renamed to LiveScript, and
finally became JavaScript.

• Standardization (1️997): JavaScript was standardized under the name ECMAScript by the
European Computer Manufacturers Association (ECMA). This standardization helped ensure
consistent implementation across different browsers.

• Growth: Over the years, JavaScript has evolved significantly, with major updates like
ECMAScript 5 (2009), which introduced features like strict mode, and ECMAScript 6 (2015),
which added classes, modules, and arrow functions.

• Popularity: JavaScript became one of the most popular programming languages due to the
rise of web applications. It is now used not only in the browser but also on servers (Node.js)
and in mobile app development (React Native).

3. Difference Between Java and JavaScript

Feature Java JavaScript

Type Compiled language Interpreted language

Syntax Strictly typed Dynamically typed

Platform Can run on any platform with JVM Runs in web browsers or servers (Node.js)

General-purpose, large Web development, enhancing


Use Case
applications interactivity

Object-
Yes, class-based Yes, prototype-based
Oriented

4. Data Types in JavaScript

JavaScript has several data types, categorized into two groups: primitive and non-primitive.

Primitive Data Types:

60
1. Number: Represents both integer and floating-point numbers.

o Example: let age = 30;

2. String: Represents a sequence of characters.

o Example: let name = "John";

3. Boolean: Represents a true or false value.

o Example: let isAdult = true;

4. 🪣 Null: Represents a deliberate non-value or empty value.

o Example: let emptyValue = null;

5. Undefined: Represents a variable that has been declared but not assigned a value.

o Example: let notAssigned;

6. Symbol: A unique and immutable value, often used as object property keys.

o Example: let uniqueSymbol = Symbol("id");

Non-Primitive Data Type:

1. Object: A complex data structure that allows storing multiple values as key-value pairs.

o Example: let person = { name: "John", age: 30 };

5. How JavaScript Can Be Tagged with HTML

To include JavaScript in an HTML document, you can use the <script> tag. Here’s how you can do it:

Inline JavaScript:

You can write JavaScript directly inside the <script> tag.

<!DOCTYPE html>

<html>

<head>

<title>My Web Page</title>

</head>

<body>

<h1>Hello, World!</h1>

<script>

alert("Welcome to my website!");

</script>

61
</body>

</html>

External JavaScript:

You can also link to an external JavaScript file using the src attribute.

<!DOCTYPE html>

<html>

<head>

<title>My Web Page</title>

<script src="script.js"></script> <!-- Link to external JS file -->

</head>

<body>

<h1>Hello, World!</h1>

</body>

</html>

Placement of <script> Tag:

• Inside <head>: It loads before the content. If it contains DOM manipulations, it might cause
errors as elements may not be loaded yet.

• Before </body>: This is the preferred method, as it ensures that the HTML elements are loaded
before the script runs.

6. JavaScript Browser Compatibility

JavaScript is a programming language that runs in web browsers, and its compatibility can vary across
different browsers. Here's a breakdown of what you need to know:

• Cross-Browser Support: Different browsers (like Chrome, Firefox, Safari, and Edge) may
interpret JavaScript code differently. This can lead to inconsistencies in how web pages
behave.

• Feature Support: New features (like ES6, ES7, etc.) are introduced in JavaScript, but not all
browsers support them at the same time. For example, older browsers may not support newer
syntax or APIs.

• Tools for Compatibility:

o Polyfills: These are pieces of code that provide functionality in browsers that do not
support certain features.

62
o Transpilers: Tools like Babel can convert modern JavaScript into a version that is
compatible with older browsers.

• Testing: Always test your web applications in multiple browsers to ensure they function
correctly.

7. Why is JavaScript Named JavaScript?

The name "JavaScript" can be a bit misleading, and here's the story behind it:

• Origin of the Name: JavaScript was originally named "Mocha" and then "LiveScript" before it
was finally branded as "JavaScript" in 1995.

• Marketing Strategy: At the time, Java was a popular programming language, and naming it
"JavaScript" helped increase interest and adoption. However, the two languages are quite
different in their design and use cases.

• Relationship with Java: Despite the name, JavaScript is more similar to languages like C and
Scheme. It's a lightweight, interpreted language primarily used for web development.

8. Typecasting in JavaScript

Typecasting in JavaScript refers to converting one data type to another. JavaScript is a loosely typed
language, meaning variables can hold any type of data. Here’s how typecasting works:

• Implicit Type Conversion (Coercion): This happens automatically when you use operators.
For example:

o 5 + '5' results in '55' (number converted to a string).

• Explicit Type Conversion: You can also manually convert types using functions:

o String: String(123) converts the number 123 to '123'.

o Number: Number('123') converts the string '123' to 123.

o Boolean: Boolean(0) results in false, while Boolean(1) results in true.

9. Arrays in JavaScript

Arrays are used to store multiple values in a single variable. They are very flexible and powerful in
JavaScript:

• Creating Arrays: You can create an array using brackets []:

o let fruits = ['apple', 'banana', 'cherry'];

• Accessing Elements: Each element can be accessed using its index (starting from 0):

o fruits[0] gives 'apple'.

• Array Methods: JavaScript provides many methods for working with arrays:

o push(): Adds an item to the end of the array.

o pop(): Removes the last item from the array.


63
o map(): Creates a new array with the results of calling a function on every element.

1️0. Converting Numbers Between Different Bases in JavaScript

JavaScript provides methods to convert numbers between different bases (like binary, octal, decimal,
and hexadecimal):

• Converting to Different Bases:

o toString(base): This method converts a number to a string in the specified base.

▪ Example:

▪ let num = 10;

▪ num.toString(2) gives '1010' (binary).

▪ num.toString(16) gives 'a' (hexadecimal).

• Parsing Strings in Different Bases:

o parseInt(string, base): This function parses a string and returns an integer of the
specified base.

▪ Example:

▪ parseInt('1010', 2) gives 10 (binary to decimal).

▪ parseInt('a', 16) gives 10 (hexadecimal to decimal).

1️1️. The Purpose of Backslash in JavaScript

Understanding the Backslash (\)

The backslash in JavaScript serves as an escape character. It allows you to include special
characters in strings that would otherwise be difficult to represent. For example:

• Escape Sequences: It is used to escape characters like quotes or newlines. For instance:

o \" is used to include double quotes inside a string.

o \' is for single quotes.

o \\ is for including a literal backslash.

o \n represents a new line.

Example:
If you want to create a string that includes both single and double quotes, you can write:

She said, "It's a beautiful day!"

In JavaScript, you might represent it as:

"She said, \"It's a beautiful day!\""

64
1️2️. What is an Operator?

Defining Operators

An operator is a special symbol that performs operations on variables and values. Operators can be
thought of as tools that allow you to manipulate data.

Types of Operators:

• Arithmetic Operators: Used for mathematical calculations (like addition and subtraction).

• Comparison Operators: Used to compare two values (like checking if they are equal).

• Logical Operators: Used to perform logical operations (like AND, OR).

Example:
In the expression 5 + 3, the + symbol is an operator that adds the two numbers together.

13. Differentiating Between Arithmetic and Bitwise Operators

Feature Arithmetic Operators Bitwise Operators

Used to perform mathematical Operate on the binary representations


Definition
calculations on numbers. of numbers.

Common + (Addition), - (Subtraction), ×


& (AND),
Operators (Multiplication), ÷ (Division)

Works with integer and floating- Works primarily with integer types
Input Types
point numbers. (binary values).

Returns a numeric result (integer Returns a numeric result, typically in


Result Type
or float). binary form.

Used for low-level programming, bit


Used for arithmetic calculations,
Usage Context manipulation, and optimizing
like totals and averages.
operations.

Example Calculating the sum of expenses Setting flags, masking bits, or shifting
Application or determining an average score. values for efficiency.

Has a specific precedence, often lower


Generally higher precedence over
Precedence than arithmetic but higher than
comparison operators.
relational.

Changes the numeric value


Alters individual bits in the binary
Effect on Data through standard arithmetic
representation of a number.
operations.

65
Feature Arithmetic Operators Bitwise Operators

Visual Operates on numbers directly as Operates on binary digits (0s and 1️s)
Representation we see them. behind the scenes.

Arithmetic Operators

• Purpose: Perform standard math operations.

• Examples:

o Addition (+): Combining numbers to get a sum.

o Subtraction (-): Finding the difference between numbers.

o Multiplication (×): Scaling a number by another.

o Division (÷): Splitting a number into equal parts.

• Use Cases: Useful in everyday calculations, finance, and statistical analysis.

Bitwise Operators

• Purpose: Manipulate individual bits in a number’s binary form.

• Examples:

o AND (&): Sets a bit to 1️ only if both bits are 1️.

o OR (|): Sets a bit to 1️ if at least one of the bits is 1️.

o XOR (^): Sets a bit to 1️ if the bits are different.

o NOT (~): Flips the bits (0s to 1️s and vice versa).

o Left Shift (<<): Moves bits to the left, filling with zeros.

o Right Shift (>>): Moves bits to the right, filling with zeros or sign bits.

• Use Cases: Essential in systems programming, graphics processing, and performance


optimization.

Summary

• Arithmetic operators are essential for basic mathematical operations, suitable for high-
level calculations in various fields. They operate directly on the numbers as we perceive
them.

• Bitwise operators work on the underlying binary representations of numbers, allowing for
precise control over data and efficient manipulation of bits, which is particularly valuable
in low-level programming tasks.

This structured comparison highlights the fundamental differences and applications of


arithmetic and bitwise operators in programming and computing.

66
1️4. Why Comparison Operators Are Used?

Understanding Comparison Operators

Comparison operators are used to compare two values and determine their relationship. They help
you evaluate conditions in programming.

Types of Comparison Operators:

• Equal to (==): Checks if two values are equal.

• Strict Equal to (===): Checks if two values are equal and of the same type.

• Not Equal to (!=): Checks if two values are not equal.

• Greater Than (>): Checks if one value is greater than another.

• Less Than (<): Checks if one value is less than another.

Example:
In a game, you might check if a player’s score is greater than a certain value to determine if they win.

1️5. Logical Operators

Understanding Logical Operators

Logical operators are used to combine multiple conditions or expressions. They help in making
decisions based on multiple criteria.

Types of Logical Operators:

• AND (&&): Returns true if both conditions are true.

• OR (||): Returns true if at least one condition is true.

• NOT (!): Reverses the truth value of a condition.

Example: Imagine you have two conditions:

1. It’s raining.

2. You have an umbrella.

Using logical operators:

• AND: You can go outside only if it’s not raining AND you have an umbrella.

• OR: You can go outside if it’s not raining OR you have an umbrella.

• NOT: You can go outside if it is NOT raining.

1️6. What is the === Operator?

67
The === operator in JavaScript is known as the strict equality operator. It compares two values to
determine if they are equal, and it checks both the value and the data type. Here’s how it works:

• Type Checking: It does not perform type coercion. This means if you compare a number to a
string, it will return false unless they are of the same type.

o Example:

▪ 5 === 5 returns true (same value, same type).

▪ 5 === "5" returns false (same value, different type).

In summary, === ensures that both the value and type are exactly the same, making it a safer choice
for comparisons.

1️7. What Does the Delete Operator Do?

The delete operator is used to remove properties from an object in JavaScript. When you use delete, it
permanently removes the specified property, and it can’t be restored.

• Key Points:

o It can only be used on object properties, not on variables or functions.

o If you try to delete a property that does not exist, it won’t throw an error; it will simply
return true.

For example, if you have an object representing a car and you want to remove the color property, you
would use the delete operator.

1️8. What is the Function of Boolean Operators in JavaScript?

Boolean operators are logical operators that are used to combine or modify boolean values (true or
false). In JavaScript, the main Boolean operators are:

• AND (&&): Returns true if both operands are true.

• OR (||): Returns true if at least one operand is true.

• NOT (!): Reverses the boolean value (true becomes false and vice versa).

Use Cases:

• You can use these operators in conditions (like in if statements) to control the flow of your
program based on multiple conditions.

1️9. Evaluate “1️” + 2️ + 4.

In this expression, JavaScript performs operations based on the types of the values involved:

1. The first value is a string ("1").

68
2. The second value is a number (2).

3. The third value is another number (4).

When you add a string to a number, JavaScript converts the number to a string and concatenates
them. So, the evaluation happens as follows:

• First, "1" + 2 becomes "12" (the number 2 is converted to a string).

• Then, "12" + 4 becomes "124" (the number 4 is also converted to a string).

Final Result: "124" (a string).

2️0. Solve 2️ + 5 + "8".

Similar to the previous question, this expression involves both numbers and a string:

1. Start with the first two values: 2 and 5.

2. The last value is a string ("8").

The evaluation goes like this:

• First, 2 + 5 becomes 7 (both are numbers, so they are added normally).

• Then, 7 + "8" becomes "78" (the number 7 is converted to a string).

Final Result: "78" (a string).

2️1️. What Do You Mean by Expression in JavaScript?

An expression in JavaScript is any piece of code that evaluates to a value. This can be a combination
of values, variables, operators, and function calls that JavaScript interprets and produces a result.

Types of Expressions:

• Literal Expressions: Like numbers or strings (e.g., 42, "hello").

• Mathematical Expressions: Involving operations (e.g., 3 + 4).

• Logical Expressions: Involving Boolean operations (e.g., true && false).

Importance: Expressions are fundamental building blocks in programming as they can be used
wherever a value is expected, like in conditions, assignments, and function arguments.

MCQ Questions with their answers

1. Developed under the name ..........................., Live Script was the official name for the
language when it first shipped in beta releases of Netscape Navigator 2️.0.
Answer: C. Mocha
Meaning: Mocha was the original name for JavaScript before it was renamed to LiveScript and
later to JavaScript. It was part of the early development of web programming.
69
2. The change of name from ........................... to JavaScript roughly coincided with
Netscape adding support for Java technology in its Netscape Navigator web browser.
Answer: B. LiveScript
Meaning: LiveScript was the name before JavaScript, and the renaming reflected the
integration of Java technologies into web development.

3. ........................... is a scripting language designed primarily for adding interactivity to


WebPages and creating Web applications.
Answer: D. JavaScript
Meaning: JavaScript is a widely-used programming language that enables interactive features
on websites, such as form validation and dynamic content updates.

4. JavaScript is the scripting language implemented on...........................


Answer: A. Web
Meaning: JavaScript is primarily used in web development to enhance user interactions on
websites.

5. JavaScript can put ........................... text into an HTML page.


Answer: D. Dynamic
Meaning: JavaScript can generate and manipulate dynamic text content in HTML, allowing for
real-time updates and changes.

6. A JavaScript can be used to validate form data before it is submitted to a


...........................
Answer: B. Server
Meaning: JavaScript can check user input for errors or required fields before the data is sent to
a server for processing.

7. In JavaScript, ........................... tags can be inserted into three places: in between the two
BODY tags, in between the two HEAD tags, and as a link to an external file, also in the
HEAD section.
Answer: A. SCRIPT
Meaning: <script> tags are used to embed JavaScript code directly within HTML documents or
link to external JavaScript files.

8. If your JavaScript references any of the web pages ..........................., there may be a
slight delay in the fancy effects you want to apply, or it may just not work at all.
Answer: C. elements
Meaning: JavaScript relies on specific elements within the web page; if they are not properly
loaded or referenced, the intended effects may not function.

9. Browsers that do not support JavaScript will display JavaScript as ...........................


Answer: B. Page Content
Meaning: If JavaScript is not supported, the browser may display the script as plain text rather
than executing it.

10. Add an HTML comment tag ................before the first JavaScript statement, and a —> (end
of comment) after the last JavaScript statement.
Answer: B. <!

70
Meaning: The correct way to add comments in HTML is to use <!-- to start the comment and --
> to end it.

11. .......................... data types are the types that can be assigned a single literal value.
Answer: D. Primitive
Meaning: Primitive data types (such as numbers, strings, and booleans) represent single
values and are not objects.

12. .......................... are rows of characters enclosed in either double or single quotes.
Answer: A. String Literals
Meaning: String literals are sequences of characters used in programming, typically enclosed
in quotes to define them.

13. To get the value of the ........................... element, we can use the value property of the
text input object.
Answer: C. Text Input
Meaning: The value property retrieves the current input value from text fields in a web form.

14. The code for obtaining a reference to a ........................... element is oTextarea =


oForm.elements["textarea_element_name"].
Answer: B. Text Area
Meaning: This code snippet demonstrates how to access a text area element from a form
using JavaScript.

15. ........................... allows you to access a specific value as if it were of a different type.
Answer: D. Type Casting
Meaning: Type casting is the process of converting a variable from one data type to another to
perform operations.

16. Type casts ........................... casts the given value as a number.


Answer: Number(value)
Meaning: The Number() function converts a value to a number data type in JavaScript.

17. An ........................... is a special variable, which can hold more than one value at a time.
Answer: Array
Meaning: An array is a data structure that allows you to store multiple values in a single
variable, organized in an indexed format.

18. Each element in the array has its own ........................... so that it can be easily accessed.
Answer: ID
Meaning: Each element in an array can be accessed using its index (ID), which is its position
within the array.

19. ........................... operators test to see if two variables relate to each other in the
specified way.
Answer: Comparison
Meaning: Comparison operators evaluate relationships between values (such as equality or
inequality).

71
20. ........................... is called the Bitwise NOT Operator, which is a unary operator and
operates by reversing all bits in the operand.
Answer: ~
Meaning: The Bitwise NOT operator (~) inverts the bits of its operand, turning 1s into 0s and
vice versa.

21. The operator ........................... is the multiply AND assignment operator; it multiplies the
right operand with the left operand and assigns the result to the left operand.
*Answer: =
Meaning: The *= operator combines multiplication and assignment into one operation,
updating the left operand with the product.

22. The decrement operator ........................... the variable.


Answer: Reduces
Meaning: The decrement operator (--) decreases the value of a variable by one.

23. ........................... Operator first evaluates an expression for a true or false value and then
executes one of the two given statements depending upon the result of the evaluation.
Answer: Conditional
Meaning: Conditional operators (such as if) control the flow of execution based on boolean
expressions.

24. The ........................... is a unary operator that is placed before its single operand, which
can be of any type.
Answer: Type of
Meaning: The typeof operator is used to determine the data type of a variable or expression.

25. The ........................... of operators determines the order they are applied when evaluating
an expression.
Answer: Precedence
Meaning: Operator precedence defines the hierarchy of operations in an expression, affecting
the order in which they are computed.

26. The operator ........................... checks if the value of two operands is equal or not; if
values are not equal, then the condition becomes true.
Answer: !=
Meaning: The != operator evaluates to true if the two operands are not equal, regardless of
their data types.

27. Due to the possibly confusing nature of pre-and post-increment behavior, code can be
easier to read if the ........................... operators are avoided.
Answer: Increment
Meaning: Pre-increment (++var) and post-increment (var++) operators can lead to ambiguity;
avoiding them can improve code clarity.

28. An operator | is called ........................... Operator. It performs a Boolean OR operation on


each bit of its integer arguments.
Answer: Bitwise OR

72
Meaning: The Bitwise OR operator (|) compares each corresponding bit of two integers and
returns a new integer with bits set to 1 where either input has a 1.

29. An ........................... is any valid set of literals, variables, operators, and expressions that
evaluates to a single value.
Answer: Expression
Meaning: An expression is a combination of values and variables that can be computed to
yield a result.

30. The special keyword null denotes a ...........................


Answer: Null Value
Meaning: The null keyword represents the intentional absence of any object value, signifying
that a variable is empty.

31. An expression can have one of two values based on a ...........................


Answer: Condition
Meaning: Conditional expressions evaluate to true or false based on specified criteria, leading
to different outcomes.

32. ........................... expression evaluates to a character string.


Answer: String
Meaning: String expressions produce sequences of characters that can be manipulated and
displayed in code.

33. Variables that have not been assigned a value are undefined, and cannot be used without
a ........................... error.
Answer: Run-Time
Meaning: Accessing undefined variables leads to run-time errors, as the interpreter cannot
reference a variable that hasn't been initialized.

Chapter 8: Programming Constructs in JavaScript


1️. Use of If-Else and Switch Statements

Both if-else and switch statements help in decision-making in a program. They allow the program to
take different actions based on conditions.

If-Else Statement:

• The if condition checks whether a statement is true or false.

• If true, it executes a specific block of code.

• If false, it either does nothing or executes an alternative block of code (else).

• It is useful when there are complex conditions or range-based decisions.

73
Example Usage:
Imagine an online shopping website. If the total bill is above ₹1000, the customer gets a discount. If
not, they pay the full amount.

Switch Statement:

• The switch statement is used when a variable needs to be checked for multiple possible
values.

• It helps in cases where multiple if-else statements can make the code too long.

• Each case represents a possible value and contains specific actions to perform.

• It is mainly used when we have fixed choices to check (e.g., days of the week, menu options).

Example Usage:
A restaurant menu can use switch to display prices based on what the user selects (Pizza, Burger, or
Pasta).

2️. Break & Continue Statements

These two statements control the flow of loops and conditionals.

Break Statement:

• It stops the loop completely when a certain condition is met.

• After breaking out, the program jumps to the next statement after the loop.

• Used when we want to exit a loop immediately upon meeting a certain condition.

Example Usage:
Imagine you are searching for a book in a library. As soon as you find it, you stop looking and leave. The
break statement works in the same way.

Continue Statement:

• Instead of stopping the loop, continue skips the current iteration and moves to the next one.

• It is useful when you want to ignore specific values but still continue looping.

Example Usage:
In a classroom, a teacher is checking student marks. If a student was absent (marked "A"), the
teacher skips grading them but continues checking other students.

3. Difference Between For and While Loop Statements

Both loops are used to repeat a set of instructions, but they work in different ways.

For Loop:

• Used when the number of repetitions is already known.


74
• It has a clear start, condition, and step in a single line.

• Best for situations like counting numbers, printing tables, or iterating over lists.

Example Usage:
Imagine you are counting from 1️ to 1️0. You know in advance that you need 1️0 steps, so a for loop is
ideal.

While Loop:

• Used when the number of repetitions is unknown and depends on a condition.

• The loop continues running as long as the condition remains true.

• Best for user input-based loops or situations where stopping depends on dynamic
conditions.

Example Usage:
A mobile phone keeps checking for incoming calls while it is powered on. The number of checks is
unknown, so a while loop is better.

4. Difference Between Do-While and While Loop Statements

While Loop:

• Checks the condition first before executing the loop body.

• If the condition is false from the start, the loop never runs.

Example Usage:
A bank only allows transactions if an account has sufficient balance. If the condition is not met, the
transaction does not proceed.

Do-While Loop:

• Executes the loop at least once, even if the condition is false.

• The condition is checked after running the loop body.

Example Usage:
A vending machine asks "Do you want another item?" after each purchase. Even if you press "No",
the machine asks at least once before stopping.

5. Is Switch Case the Best for Testing All Outcomes?

Statement: “The switch case conditional statement is used to test all of the possible outcomes for
the application being designed.”

Agree, But With Limitations!

75
The switch case statement is very helpful when dealing with multiple predefined choices. However,
it does not cover all possible outcomes in every situation.

Why Switch is Useful:


✔ Best when there are limited and fixed choices (e.g., colors, days, menu options).
✔ Makes the code cleaner compared to long if-else chains.
✔ Works faster for simple value checks.

Why Switch is Limited:


Cannot handle ranges (e.g., "values between 10-20").
Cannot check complex conditions (e.g., mathematical comparisons).
Not useful for boolean (true/false) conditions.

Example Consideration:
Imagine a traffic light system with Red, Yellow, and Green. A switch case is perfect because there
are only three fixed states.
However, if a weather app needs to check temperature ranges, a switch case would not be
useful—an if-else statement would work better.

MCQ Questions with their answers

1. ........................... statements give the JavaScript code you are writing the ability to make
decisions or perform single or multiple tasks.
Answer: A. Conditional
Meaning: Conditional statements allow the execution of different code blocks based on
whether a specified condition evaluates to true or false, enabling decision-making in
programming.

2. The ........................... conditional statement is used to perform an action if the condition


is met.
Answer: B. If
Meaning: The if statement evaluates a condition and executes a block of code if the condition
is true, allowing for control flow based on logical conditions.

3. The ........................... conditional statement is used to test all of the possible outcomes
for the application you are designing.
Answer: A. Switch case
Meaning: The switch statement is used to select one of many code blocks to execute, based
on the value of an expression, effectively testing multiple conditions.

4. The ........................... loop is used when you know in advance how many times the script
should run.
Answer: A. For
Meaning: The for loop is a control structure that allows for repeated execution of a block of
code a specified number of times, making it useful for scenarios where the iteration count is
known beforehand.

76
5. The ........................... loop loops through a block of code while a specified condition is
true.
Answer: C. While
Meaning: The while loop continues to execute a block of code as long as the specified
condition remains true, making it suitable for situations where the number of iterations is not
known in advance.

6. The ........................... loop will execute the block of code ONCE, and then it will repeat
the loop as long as the specified condition is true.
Answer: B. Do-while
Meaning: The do-while loop guarantees that the code block runs at least once before the
condition is tested, allowing for situations where the initial execution is necessary.

7. The ........................... statement will break the loop and continue executing the code that
follows after the loop (if any).
Answer: D. Break
Meaning: The break statement is used to exit a loop prematurely, allowing the program to
continue with the next line of code following the loop.

8. The ........................... statement will break the current loop and continue with the next
value.
Answer: C. Continue
Meaning: The continue statement skips the rest of the code inside the loop for the current
iteration and proceeds to the next iteration of the loop.

9. A/An ........................... dialog box is mostly used to give a warning message to the users.
Answer: A. Alert
Meaning: An alert dialog box is a simple popup that displays a message to the user, typically
used for warnings or important notifications.

10. The ........................... dialog box is very useful when you want to pop up a text box to get
user input.
Answer: D. Prompt
Meaning: A prompt dialog box displays a message along with an input field, allowing users to
enter data, making it useful for gathering information.

11. A ........................... dialog box is mostly used to take the user's consent on any option.
Answer: B. Confirmation
Meaning: A confirmation dialog box is used to ask users for their consent or decision before
proceeding with an action, typically providing options like "OK" or "Cancel."

12. In .......................... loop, you know in advance how many times the script should run.
Answer: B. For
Meaning: The for loop is specifically designed for situations where the number of iterations is
predetermined, making it easy to manage the loop's execution.

13. The ........................... gives the JavaScript code you are writing the ability to make
decisions or perform single or multiple tasks.
Answer: Control statement

77
Meaning: Control statements include constructs like if, switch, and loops that enable
decision-making and control the flow of execution in JavaScript.

14. To test all of the possible outcomes for the application being designed, the
........................... conditional statement is used.
Answer: Switch-case
Meaning: The switch-case statement is effective for evaluating multiple potential conditions or
outcomes based on a single expression.

15. In case of the ........................... loop, the block of code will execute ONCE, and then it will
repeat the loop as long as the specified condition is true.
Answer: Do-while
Meaning: The do-while loop ensures that the code within it is executed at least once before
checking the condition for further iterations.

Chapter 9: Functions in JavaScript


1. Difference Between Functions and Statements in JavaScript

JavaScript is a powerful language that consists of functions and statements to perform different
tasks. Let’s break them down in a simple and creative way!

Tabular Comparison

Feature Function Statement

A reusable block of code that performs a A single instruction that performs an


Definition
specific task. action in the program.

Executes a specific action, like


Helps in organizing and reusing code
Purpose declaring variables or making
efficiently.
decisions.

Can be called multiple times to execute Usually runs once unless controlled by
Reusability
the same logic. loops or conditions.

Input & Output Can take inputs (parameters) and return Mostly executes an action without
outputs. returning anything.

Dependency Functions may depend on statements Statements can exist independently


inside them to work properly. without needing a function.

A function is like a machine – you give it A statement is like a command – you


Examples in
inputs (raw materials), and it processes tell JavaScript to do something, and it
Concept
them to give outputs (finished products). follows the order immediately.

78
Feature Function Statement

Can be simple or very complex, containing Usually simple, performing one task at
Complexity
many statements inside. a time.

Runs immediately when the script


Execution Needs to be called to run.
reaches it.

Explanation of Functions

What is a Function?
A function is like a machine in a factory. You put something inside, it processes it, and then it gives an
output. Functions help in organizing code, making it reusable and efficient.

Why Are Functions Useful?


Reduce repetition – Instead of writing the same code multiple times, we create a function and
reuse it.
Improve readability – Code becomes easier to understand and manage.
Allow input (parameters) – We can pass different values to a function to get different results.
Can return a result – After processing, a function can send back an output for further use.

How Do Functions Work?


1⃣ You define a function (like building a machine).
2⃣ You call or invoke the function (like turning on the machine).
3⃣ It processes the inputs and gives an output.

Explanation of Statements

What is a Statement?
A statement is a single instruction that tells JavaScript to do something. It is like a command given to
a computer.

Types of Statements in JavaScript


Declaration Statements – Used to declare variables or constants.
Assignment Statements – Assign values to variables.
Conditional Statements – Make decisions (like "if" something happens, do this).
Loop Statements – Repeat tasks multiple times.
Expression Statements – Perform calculations or operations.

Why Are Statements Important?


They form the building blocks of a JavaScript program.
Each statement performs a specific task to control the program flow.
They help JavaScript execute actions like calculations, decisions, and loops.

79
How Do Statements Work?
1⃣ The browser reads JavaScript line by line.
2⃣ Each statement is executed immediately.
3⃣ Based on the statement, JavaScript might store values, make decisions, or repeat actions.

Final Thoughts

Functions help structure, reuse, and organize code effectively.


Statements are the basic building blocks that instruct JavaScript on what to do.
Functions contain statements, but statements do not contain functions directly.

JavaScript Functions & Dialog Boxes Explained Simply

2️. What Are Built-in Functions in JavaScript?

Built-in functions in JavaScript are predefined functions that are already available for use without
writing any extra code. These functions help developers perform common tasks easily, such as
manipulating strings, working with numbers, and handling arrays.

Features of Built-in Functions:

They come with JavaScript automatically.


No need to define them manually.
Saves time and effort.
Improves efficiency and code readability.

Examples of Built-in Functions (Without Code)

String Functions → Help in working with text, like converting letters to uppercase or finding the
length of a word.
Math Functions → Used for calculations, like finding the square root or rounding a number.
Array Functions → Allow operations on lists, like sorting or filtering data.
Date Functions → Help in working with dates, like getting the current day or time.

3. Difference Between Built-in Functions & User-Defined Functions

Feature Built-in Functions User-Defined Functions

Functions already available in


Definition Functions created by the programmer.
JavaScript.

Can be used directly without writing


Ease of Use Must be written and defined manually.
extra code.

80
Feature Built-in Functions User-Defined Functions

length (for strings), round (for Custom functions like calculating discounts
Examples
numbers), sort (for arrays). or generating greetings.

Modification Cannot be modified by the user. Fully customizable based on user needs.

Solve common programming problems Solve specific problems based on project


Purpose
efficiently. needs.

In Simple Words: Built-in functions are predefined helpers, while user-defined functions are
custom-made solutions for specific problems.

4. What Is the Use of Dialog Boxes in JavaScript?

Dialog boxes in JavaScript are pop-up windows that appear on the screen to interact with users. They
help in displaying messages, taking input, or confirming actions before continuing with a task.

Why Are Dialog Boxes Useful?

Grab the user’s attention instantly.


Allow communication between the website and the user.
Provide an easy way to collect input from users.
Help in displaying warnings or important notifications.

Types of Dialog Boxes in JavaScript

1⃣ Alert Box → Shows a simple message to the user.


2⃣ Prompt Box → Asks for input from the user.
3⃣ Confirm Box → Asks the user to accept or cancel an action.

5. Difference Between Alert & Prompt Dialog Boxes

Feature Alert Box Prompt Box

Displays a message or warning to


Purpose Asks the user to enter some input.
the user.

User Input Does not take any input. Takes user input in a text box.

Buttons Shown Only an OK button. Two buttons: OK and Cancel.

Example Showing an error message or


Asking for a user’s name or age.
Usage warning.

81
Feature Alert Box Prompt Box

User Requires the user to type something before


Only requires the user to click OK.
Interaction clicking OK.

In Simple Words:
✔ Alert Box = Just shows a message and waits for OK.
✔ Prompt Box = Asks a question, lets the user type a response, and then presses OK or Cancel.

6. What is the use of the Confirm Dialog Box in JavaScript?

A Confirm Dialog Box is a special type of popup message that appears on a web page to ask the user
for confirmation before performing an action.

Purpose of the Confirm Dialog Box

Takes User Permission – It asks the user to either accept or decline an action.
Prevents Mistakes – Useful in situations where the action cannot be undone (e.g., deleting a
file).
Improves User Experience – Provides an interactive decision-making process.
Two Response Options – The user can confirm (OK) or cancel (Cancel) the action.
Used for Critical Actions – Example: "Are you sure you want to log out?"

Common Use Cases

Deleting files or data – “Do you really want to delete this item?”
Form submission – “Are you sure you want to submit this form?”
Logging out of an account – “Do you want to log out now?”
Removing an item from a cart – “Are you sure you want to remove this item?”

7. Differences Between Confirm and Alert Dialog Boxes in JavaScript

Both Confirm and Alert dialog boxes are used to communicate messages to the user, but they serve
different purposes.

Comparison Table: Confirm vs. Alert Dialog Box

Feature Confirm Dialog Box Alert Dialog Box

Purpose Used to get user confirmation Used to show important messages

User Response Offers two buttons: OK & Cancel Offers only one button: OK

User Decision User can accept or reject the action User can only acknowledge the message

82
Feature Confirm Dialog Box Alert Dialog Box

Used before performing critical Used for warnings, notifications, or


Usage
actions alerts

Example “Are you sure you want to delete


“Error: Invalid Password!”
Message this?”

Key Differences Explained Simply

Alert Box – Just displays a message and waits for the user to click OK.
Confirm Box – Asks the user a Yes/No type question, allowing them to confirm or cancel an
action.

When to Use Which?

Use Alert Box – When you just want to inform the user about something.
Use Confirm Box – When you need the user’s decision before proceeding.

MCQ Questions with their answers

1. To keep the browser from executing a script when the page loads, you can put your script
into a .....................
Answer: A. function
Meaning: Wrapping your script in a function allows you to control when it executes, preventing
it from running automatically on page load.

2. A/an ........................... is an expression that defines an unnamed function.


Answer: C. function literal
Meaning: A function literal, also known as an anonymous function, is defined without a name
and can be used as a value in expressions or passed as an argument.

3. An ........................... function saves us from rewriting the same code again and again and
helps us to make our application smaller.
Answer: D. user-defined
Meaning: A user-defined function is created by the programmer to encapsulate code that can
be reused throughout the application, improving efficiency.

4. The ........................... object is a local variable available within all functions.


Answer: B. arguments
Meaning: The arguments object is an array-like object that holds all the arguments passed to a
function, making it available within that function.

5. .......................... variables exist only inside a particular function hence they have Local
Scope.
Answer: C. local
Meaning: Local variables are declared within a function and are only accessible within that
function, preventing external access and avoiding name conflicts.

83
6. An ........................... dialog box is mostly used to give a warning message to the users.
Answer: B. alert
Meaning: An alert dialog box is used to display a message to the user, typically to inform them
of an important piece of information or warning.

7. The ........................... dialog box is very useful when you want to pop-up a text box to get
user input.
Answer: A. prompt
Meaning: A prompt dialog box asks the user for input and displays a text box where they can
enter their response.

8. ……………… are blocks of JavaScript code that perform a specific task and often return a
value.
Answer: C. Functions
Meaning: Functions in JavaScript are reusable blocks of code designed to perform a specific
task and can return a value when called.

9. ………….. are a standard technique via which control data can be passed to a function.
Answer: D. Parameters
Meaning: Parameters are variables listed as part of a function's definition, allowing values to
be passed into the function when it is called.

10. JavaScript provides the ability to pick up user input or display a small amount of text to
the user by using …………….
Answer: B. dialog boxes
Meaning: Dialog boxes in JavaScript are used to interact with users, allowing for input or
display of messages.

11. A function contains ……… that will be executed by an event or by a call to the function.
Answer: A. code
Meaning: A function consists of executable code that performs tasks when invoked either by
user action or programmatically.

12. A …………. is an expression that defines an unnamed function.


Answer: B. function literal
Meaning: A function literal defines a function without a name, allowing it to be used as a value
or passed to other functions.

13. A ……………. function saves us from rewriting the same code again and again and helps us
to make our application smaller.
Answer: D. user-defined
Meaning: A user-defined function allows for code reuse, which simplifies the program and
makes it easier to manage.

14. …………… can be used to raise an alert, or to get confirmation on any input or to have a
kind of input from the users.
Answer: B. dialog boxes
Meaning: Dialog boxes are used for various user interactions, such as alerts, confirmations,
and input requests.

84
15. A. parseFloat() function takes a string as a parameter and parses it to a floating point
number.
Answer: A. parseFloat()
Meaning: The parseFloat() function converts a string representation of a number into a
floating-point number, allowing for numerical operations.

Chapter 10: DOM Model & Browser Objects


Understanding the DOM (Document Object Model)

The Document Object Model (DOM) is a programming interface that represents a web page as a
structured tree of objects. It allows programming languages (like JavaScript) to interact with and
manipulate the content, structure, and style of a webpage dynamically.

1️. What is DOM?

The Document Object Model (DOM) is a tree-like representation of an HTML or XML document. It
provides a structured way to access, modify, and manage webpage elements using scripting
languages like JavaScript.

Key Features of DOM:


It represents a webpage as a hierarchical tree.
It allows programs to dynamically update content.
It makes webpages interactive.

Imagine DOM as a blueprint of a webpage that helps browsers understand and manipulate the
structure of HTML elements.

2️. Explain the DOM Interface

The DOM Interface is a collection of objects and methods that define how programs can interact
with the document.

Major Components of the DOM Interface:


Document Object – Represents the entire HTML page.
Element Objects – Represents individual HTML elements (like <p>, <div>, <h1>, etc.).
Attribute Objects – Stores properties of elements (like id, class, etc.).
Text Objects – Represents the text inside an HTML element.
Events & Methods – Allow interaction with the document (like clicks, mouse movements,
etc.).

The DOM Interface acts as a bridge between web documents and programming languages.

85
3. How do you define DOM?

DOM is a structured representation of an HTML document, allowing programs to read,


manipulate, and update webpage content.

Think of DOM as a family tree where:

• The document is the root.

• Elements are branches.

• Text and attributes are leaves.

This hierarchical representation makes it easy for developers to interact with elements dynamically.

4. How do you define nodes in HTML DOM?

A node in the DOM is a single point in the document tree that represents an element, attribute, or text.

Types of Nodes:
Element Nodes – Represent HTML elements (<p>, <h1>, <img>, etc.).
Text Nodes – Contain actual text inside elements.
Attribute Nodes – Represent attributes like id, class, href, etc.
Comment Nodes – Store comments inside HTML (<!-- This is a comment -->).

Example: In <h1 class="title">Hello</h1>, the Element Node is <h1>, the Text Node is "Hello",
and the Attribute Node is class="title".

5. How do you define node tree in HTML DOM?

A node tree is a hierarchical structure where elements, attributes, and text are organized in a parent-
child relationship.

Structure of Node Tree:


Root Node – The main document (HTML).
Parent Nodes – Elements that contain child nodes.
Child Nodes – Nested elements inside parent nodes.
Sibling Nodes – Elements at the same level under the same parent.

Analogy: Think of a node tree as a family tree, where:

• Grandparent = <html>

• Parent = <body>

• Children = <h1>, <p>, <div>

6. What are the properties and methods of HTML DOM?

86
DOM provides properties (to get/set values) and methods (to perform actions).

Common Properties:
document.title – Gets/sets the webpage title.
document.body – Accesses the <body> tag.
element.innerHTML – Modifies an element's content.
element.className – Changes the class of an element.

Common Methods:
getElementById() – Finds an element by ID.
getElementsByClassName() – Selects elements by class.
querySelector() – Finds the first matching element.
createElement() – Creates a new element.

Think of these as commands that help manipulate a webpage like a remote control.

7. Write a Short Note on HTML Element Properties

HTML elements have built-in properties that define their behavior and appearance.

Important Element Properties:


id – Unique identifier for an element.
className – Defines the CSS class of an element.
innerHTML – Gets or sets the content inside an element.
style – Allows inline styling of elements.

Example Analogy:
An HTML element is like a box, and these properties define its label (id), appearance (className),
and contents (innerHTML).

8. Describe the Properties of Document Object

The document object represents the entire HTML page and provides properties to interact with it.

Important Document Properties:


document.title – Stores the webpage title.
document.URL – Contains the page URL.
document.body – Refers to the <body> section.
document.head – Refers to the <head> section.

Example: Just like a book has a title, chapters, and content, the document object organizes
webpage data.

9. Illustrate the Representation of DOM with Example


87
The DOM structure follows a tree-like model, where elements are arranged in a hierarchical manner.

Example Representation:
Imagine the following HTML:

<!DOCTYPE html>

<html>

<head>

<title>My Page</title>

</head>

<body>

<h1>Hello, World!</h1>

</body>

</html>

DOM Representation (Tree Structure):

Document

├── <html>

│ ├── <head>

│ │ ├── <title> "My Page"

│ ├── <body>

│ ├── <h1> "Hello, World!"

Think of this as an organizational chart, where each element has a role.

Conclusion

The DOM is like a blueprint of a webpage.


It organizes elements in a tree structure.
Developers use properties and methods to modify elements dynamically.
The document object acts as the main entry point for DOM interaction.

10. Difference Between onMouseOver and onMouseOut

Both onMouseOver and onMouseOut are mouse events in web development that detect when a user
moves their cursor over an element. However, they behave differently in specific scenarios. Let's
break them down in a tabular format for better clarity.

88
Comparison Table: onMouseOver vs. onMouseOut

Feature onMouseOver onMouseOut

Activates when the cursor enters an Activates when the cursor leaves an
Triggering Condition
element element

Highlights or changes an element when Removes the effect when the cursor
Effect
hovered moves away

Works with Child Yes, it also triggers when moving Yes, it triggers when leaving the
Elements? between child elements element entirely

Showing a tooltip when hovering over a Hiding the tooltip when the cursor
Example Use Case
button leaves the button

Common UI Hover menus, tooltips, image Removing highlights, closing


Applications enlargements dropdowns

Detailed Explanation of Each Event

What is onMouseOver?

This event fires when the mouse pointer enters an element or any of its child elements.
It is commonly used to create hover effects such as color changes, pop-up descriptions, or
dropdown menus.
If the element has nested elements (children), the event keeps firing when moving between
them.

What is onMouseOut?

This event fires when the mouse pointer leaves an element or any of its child elements.
It is mostly used to remove hover effects when the cursor is no longer over an element.
If an element has nested child elements, the event triggers only when the mouse leaves the
entire parent element, not when moving between children.

Real-Life Analogy

Imagine a Shopping Store:

• onMouseOver → When you walk into a store, the staff greets you.

• onMouseOut → When you leave the store, they stop interacting with you.

This is exactly how these two events work—one welcomes you when you enter, and the other says
goodbye when you leave!

89
1️1️. What is the History Object Function in JavaScript?

The History object allows us to navigate through the pages a user has visited in their browser session.
It helps in managing browser history without reloading the page.

Functions of History Object:

• Go Backward → Moves the user to the previous page in history.

• Go Forward → Takes the user to the next page in history.

• Go to a Specific Page → Allows navigation to a particular page in history by specifying the


index.

• Check History Length → Tells how many pages exist in the history stack.

The history object is useful in single-page applications (SPA) where users can navigate without
refreshing the page.

1️2️. Short Note on Location Object Properties

The Location object provides information about the current page URL and allows redirection to
another page.

Key Properties of the Location Object:

• href → Gets or sets the complete URL of the page.

• hostname → Shows the domain name (e.g., www.example.com).

• pathname → Displays the path of the current page (e.g., /home).

• port → Shows the port number (e.g., 8080).

• reload() → Reloads the current page.

• replace() → Replaces the current page without saving it in history.

The Location object is mainly used for page navigation, redirection, and getting URL details.

1️3. What is Document Object Model (DOM)?

The DOM (Document Object Model) represents a web page as a structured tree-like model where
elements (like text, images, buttons) can be added, removed, or modified.

DOM is Like a Tree:

• Root (Document) → The whole webpage.

• Branches (Elements) → HTML tags like <div>, <p>, <h1>.

• Leaves (Text, Attributes, Styles) → Content inside the tags.


90
The DOM allows JavaScript to interact with the webpage dynamically, making websites more
interactive.

1️4. How Do You Assign Object Properties?

In JavaScript, an object is like a container that holds multiple pieces of related information.

Ways to Assign Properties:

• Create and Assign at the Same Time → Define properties when creating an object.

• Modify Existing Properties → Change property values later.

• Add New Properties → Introduce new properties dynamically.

Objects help in organizing data in a meaningful way and improve code efficiency.

1️5. How Do You Create a New Object in JavaScript?

An object is like a box that holds related data together.

Ways to Create Objects:

• Using Object Literals → The simplest way to define an object with key-value pairs.

• Using Object Constructor → A method to create objects dynamically.

• Using a Class → The modern and structured way to create objects.

• Using Object.create() → Allows creating an object from an existing one.

Objects are building blocks in JavaScript that help manage related data efficiently.

1️6. What is the Function of NaN (Not-a-Number)?

NaN stands for "Not-a-Number" and is a special value that appears when a mathematical operation
fails.

When Does NaN Occur?

• Dividing a string by a number → ("hello" / 5)

• Using an undefined variable in math

• Operations with non-numeric data

NaN helps in error detection in calculations and ensures data integrity.

1️7. What is the Function of Document Object Model (DOM)?

91
The DOM acts as a bridge between JavaScript and HTML, allowing JavaScript to modify the webpage
dynamically.

Functions of DOM:

• Change Content → Modify text, images, and other elements.

• Change Styles → Apply different colors, fonts, and layouts.

• Add or Remove Elements → Dynamically update the webpage.

• Handle Events → Listen to user actions like clicks or typing.

The DOM makes web pages interactive and responsive.

1️8. Define Screen Object Properties

The Screen object provides details about the user’s display screen.

Important Screen Properties:

• width & height → Gives the screen's total dimensions.

• availWidth & availHeight → Shows the usable screen size excluding taskbars.

• colorDepth → Represents the number of colors the screen can display.

• pixelDepth → Indicates the screen resolution in bits per pixel.

The Screen object is useful for creating responsive designs and optimizing website display settings.

1️9. Discuss the Methods of Navigator Object

The Navigator object provides information about the browser and device.

Common Navigator Methods:

• userAgent → Tells the browser type and version.

• language → Shows the preferred language of the user.

• onLine → Checks if the user is online or offline.

• geolocation → Retrieves the user’s location (if allowed).

• cookieEnabled → Checks if cookies are enabled.

The Navigator object helps in detecting browser compatibility, network status, and user
preferences.

Conclusion

92
JavaScript has various built-in objects like History, Location, Document, Screen, and Navigator
that make web development more dynamic and interactive. These objects help in managing
browser history, interacting with the page, getting device info, and more.

MCQ Questions with their answers

1. The ........................... is a programming API for documents.


Answer: C. Document Object Model
Meaning: The Document Object Model (DOM) is a programming interface that allows scripts to
update the content, structure, and style of a document while it is being displayed.

2. The DOM Core represents the functionality used for ........................... documents.
Answer: B. XML
Meaning: The DOM Core provides an interface for manipulating XML documents, allowing
access to the document's structure and content.

3. Variables associated with an object are called ........................... of the object.


Answer: A. properties
Meaning: Properties are attributes or values that are associated with an object in
programming, defining the characteristics of that object.

4. The M in DOM stands for Model, but it could just as easily stand for ...........................
Answer: D. Map
Meaning: While "Model" is the standard interpretation, "Map" could conceptually represent
how the DOM provides a mapped representation of the document structure.

5. A ........................... is an interface from which a number of DOM types inherit, and allows
these various types to be treated (or tested) similarly.
Answer: A. Node
Meaning: A Node is a fundamental building block of the DOM, representing any object in the
document tree, allowing for consistent manipulation of different types of objects.

6. The ........................... tag is used to include objects such as images, audio, videos, Java
applets, ActiveX, PDF, and Flash into a webpage.
Answer: C.
Meaning: The <object> tag is used to embed multimedia elements and external resources into
HTML documents.

7. The Document object is the root of a/an ...........................


Answer: D. Document tree
Meaning: The Document tree is a hierarchical representation of the structure of the HTML or
XML document, with the Document object as the top node.

8. ........................... is used to create an attribute node.


Answer: B. createAttribute()
Meaning: The createAttribute() method is used in the DOM to create a new attribute node that
can be added to an element.

93
9. ........................... method is used to import a node from another document.
Answer: B. importNode()
Meaning: The importNode() method allows for the copying of a node from one document to
another, preserving its attributes and child nodes.

10. ........................... are actions that can be detected by JavaScript.


Answer: A. Event
Meaning: Events are occurrences or actions (like clicks, key presses, etc.) that can trigger
JavaScript functions in a web page.

11. Every element on a ........................... has certain events which can trigger a JavaScript.
Answer: C. Web page
Meaning: Elements within a web page can respond to various events, enabling interactivity
through JavaScript.

12. The ........................... event is often used to check the visitor’s browser type and browser
version, and load the proper version of the web page based on the information.
Answer: C. onLoad
Meaning: The onLoad event is fired when a document has finished loading, often used to
execute scripts or load resources based on the browser's capabilities.

13. The ........................... event is used to validate ALL form fields before submitting it.
Answer: D. onSubmit
Meaning: The onSubmit event occurs when a form is submitted, allowing for validation of form
fields to ensure all required information is correctly filled out.

14. onMouseOver and onMouseOut are often used to create “...........................” buttons.
Answer: B. Animated
Meaning: These events are used to create interactive effects, such as changing button
appearance when a user hovers over or leaves the button area.

15. ........................... is a frame set, document, or form object such as a text field loses the
focus for input.
Answer: B. Blur
Meaning: The blur event occurs when an element loses focus, typically used for input fields to
trigger validation or changes in appearance.

16. For a ........................... window, the parent and top properties refer to the window itself.
Answer: top-level
Meaning: In a top-level window, both parent and top refer to the window object itself,
indicating that it is not contained within another frame.

17. ........................... method decodes a string of encoding data using base-64 encoding.
Answer: A. Atob
Meaning: The Atob() method decodes a base-64 encoded string, converting it back to its
original format.

18. ........................... evaluates an expression or calls a function after a specified number of


milliseconds.
Answer: setTimeout
94
Meaning: The setTimeout() function is used to execute a function or expression after a delay,
specified in milliseconds.

19. ........................... contains information about the version, mime type, and what plug-ins
users have installed of Navigator in use.
Answer: Navigator objects
Meaning: The Navigator object provides information about the user's browser, including its
version and capabilities.

20. ........................... property specifies version information for the Navigator.


Answer: appVersion
Meaning: The appVersion property of the Navigator object provides the version of the browser
currently in use.

21. ........................... property tests whether Java is enabled.


Answer: javaEnabled
Meaning: The javaEnabled() method of the Navigator object checks if the Java plugin is
enabled in the user's browser.

22. The JavaScript ........................... is a property of the window object.


Answer: History Object
Meaning: The History object stores the URLs visited in the current session, allowing navigation
through the browser history.

23. ........................... function will accept an integer or a string.


Answer: go(relPos | string)
Meaning: The go() method of the History object allows navigation to a specified position in the
browser's history, accepting both integer and string parameters.

24. The ........................... property specifies the number of entries in the history object.
Answer: length
Meaning: The length property of the History object indicates how many entries are stored in
the session history.

25. The JavaScript ........................... is a property of the window object.


Answer: location object
Meaning: The location object contains information about the current URL of the document and
allows for navigation to different URLs.

26. ........................... is the part of the URL that is used to point to a particular part of a page
where a named anchor is.
Answer: Hash
Meaning: The hash portion of a URL (preceded by #) refers to a specific location within a web
page, often used for named anchors.

27. ........................... property specifies the URL hostname and port.


Answer: Host
Meaning: The host property of the location object contains the hostname and port number of
the current URL.

95
28. The JavaScript ........................... is the container for all HTML HEAD and BODY objects
associated within the HTML tags of an HTML document.
Answer: Document object
Meaning: The Document object represents the entire HTML document and serves as the entry
point to the DOM for accessing and manipulating elements.

29. ........................... property sets the background color of the web page.
Answer: bgColor
Meaning: The bgColor property can be used to set the background color of the document body
in HTML.

30. ........................... property specifies the text color attribute set in the tag.
Answer: fgColor
Meaning: The fgColor property specifies the foreground (text) color for content within the body
of an HTML document.

Chapter 11: Handling Events Using JavaScript


Understanding Events in JavaScript

1️. What do you mean by events?

In JavaScript, events are actions or occurrences that happen in a web page, which the browser can
recognize and respond to. Events are triggered by user interactions like clicking, typing, hovering, or
even page loading.

Examples of events:
Clicking a button
Pressing a key on the keyboard
Moving the mouse over an element
Loading a webpage

2️. Why do we use events in JavaScript?

Events help make web pages interactive and responsive. Without events, web pages would be static
and unresponsive to user actions.

Key reasons to use events in JavaScript:


Interactivity – Users can interact with buttons, forms, and other elements.
Real-time response – The webpage can change dynamically based on user actions.
Enhanced user experience – Improves usability and functionality.
Control over browser actions – Developers can customize how elements behave when users
interact with them.

96
3. How to use onMouseOver and onMouseOut events?

These two events are mainly used to detect when a user moves their mouse over an element and
when they move the mouse away from it.

onMouseOver: This event is triggered when the mouse pointer enters an element.
onMouseOut: This event is triggered when the mouse pointer leaves the element.

Common uses:
Highlighting text when hovered
Changing an image when hovered
Showing tooltips when hovered

4. How to change the background color of an element?

Changing the background color of an element can improve the visual appearance of a webpage. It is
often used in response to events like clicking a button, hovering over an element, or submitting a form.

Common use cases:


Changing background color when hovered
Indicating success or error messages
Highlighting selected items

5. How do you define onLoad and onUnload events?

These events are related to the loading and unloading of a webpage in the browser.

onLoad: This event occurs when the webpage finishes loading completely. It ensures that scripts
or images are fully loaded before executing any action.
onUnload: This event occurs when the user leaves the webpage or closes the browser tab. It is
often used to save user progress or show a warning before exiting.

Common uses:
Displaying welcome messages when a page loads
Tracking user activity on the page
Showing exit warnings when leaving the page

6. Define onLoad calls and onUnload calls.

These terms refer to the functions or actions that are executed when the onLoad or onUnload events
occur.

onLoad Calls: These are the actions triggered when the page loads.
onUnload Calls: These are the actions triggered when the page is closed or navigated away from.

97
Examples of usage:
Preloading images when the page loads
Saving form data before exiting the page
Sending analytics data when a user leaves the site

7. Explain onBlur Event Handler.

The onBlur event is triggered when an element loses focus. This is mainly used in form fields where
users enter data.

Common uses:
Validating input fields when a user moves to another field
Hiding tooltips when a user clicks outside a text box
Checking if a required field is left empty

8. Why do we use onSelect Event Handler?

The onSelect event is triggered when a user selects text inside an input field or textarea.

Common uses:
Automatically copying selected text
Highlighting selected text in a different color
Showing character count for selected text

9. Describe onSubmit Event Handler.

The onSubmit event occurs when a form is submitted. It is mainly used for form validation before
sending the data to the server.

Common uses:
Preventing form submission if required fields are empty
Showing success messages after submission
Sending form data to the server

Conclusion:
JavaScript events help create dynamic and interactive web pages. By using events, developers can
control how elements respond to user actions, improving the overall user experience!

10. Understanding onMouseOver and onMouseOut

Both onMouseOver and onMouseOut are events in web development that respond to mouse actions
on elements. Let's break them down in a table format:

98
Aspect onMouseOver onMouseOut

Triggered when the mouse pointer moves Triggered when the mouse pointer leaves
Definition
over an element. an element.

Used to highlight or change elements Used to revert or change elements when


Usage Context
when hovered. the mouse leaves.

Activates a specified action while the Activates a specified action when the
Behavior
mouse is over the element. mouse exits the element.

Common Use Change background color, display Revert background color, hide tooltips,
Cases tooltips, enlarge images. shrink images back.

Event Bubbling Yes, it can propagate to parent elements. Yes, it can propagate to parent elements.

Typically enhances or modifies the style Typically resets or removes


Effect on Style
of the element. enhancements applied on hover.

Detailed Explanation

What is onMouseOver?

• Definition:

o The onMouseOver event occurs when the mouse pointer hovers over a specific element
on a webpage.

• Usage:

o This event is commonly used to create dynamic effects. For example, when you hover
over a button, it might change color, or an image might enlarge to grab attention.

• Common Effects:

o Highlighting: The background color of a button might change to indicate it's


clickable.

o Tooltips: Additional information about an element can be displayed, providing


helpful context.

o Image Zoom: An image may zoom in to provide a closer view when hovered over.

What is onMouseOut?

• Definition:

o The onMouseOut event occurs when the mouse pointer leaves the area of an element.

• Usage:

99
o This event is typically used to revert any changes made by onMouseOver. For example, if
you highlighted a button on hover, it would return to its original state when the mouse
moves away.

• Common Effects:

o Reverting Styles: The background color of a button might change back to its original
color.

o Hiding Tooltips: Any displayed tooltips will disappear to reduce clutter.

o Image Reset: An image might return to its normal size when the mouse is no longer
hovering over it.

Key Differences at a Glance

• Triggering Action:

o onMouseOver is about entering an area, while onMouseOut deals with exiting that
area.

• User Interaction:

o onMouseOver often enhances the user experience by providing feedback when


hovering, whereas onMouseOut ensures that the interface returns to a stable state.

Conclusion

Understanding onMouseOver and onMouseOut is essential for creating interactive web experiences.
These events help developers provide visual feedback to users, making websites more engaging and
user-friendly. By using these events creatively, you can significantly improve the interactivity and
usability of your web applications.

MCQ Questions with their answers

1. .............................. are normally used in combination with functions, and the function
will not be executed before the event occurs!
Answer: C. Events
Meaning: Events are actions or occurrences that happen in the browser, such as clicking a
button or loading a page. They are often used to trigger functions, which only execute when the
event occurs.

2. The .............................. and onUnload events are triggered when the user enters or leaves
the page.
Answer: A. onload
Meaning: The onload event occurs when a web page has finished loading, while the onUnload

100
event occurs when a user leaves the page. Both are crucial for managing actions during page
transitions.

3. The ..................................... event is often used to check the visitor’s browser type and
browser version, and load the proper version of the web page based on the information.
Answer: D. onLoad
Meaning: The onLoad event is triggered when a page is fully loaded, making it an ideal point to
check the browser type and load content accordingly.

4. The onFocus, onBlur, and onChange events are often used in combination with
............................ of form fields.
Answer: B. Validation
Meaning: These events are commonly used for validating user input in form fields, ensuring
that the data entered meets specific criteria before submission.

5. The ................................. event is used to validate ALL form fields before submitting it.
Answer: D. onSubmit
Meaning: The onSubmit event is triggered when a form is submitted, allowing for validation of
all fields to ensure that the input is correct and complete.

6. onMouseOver and onMouseOut are often used to create “............................” buttons.


Answer: A. Animation
Meaning: These events are used to create hover effects, where buttons change appearance
when the mouse is over them, adding interactivity and visual appeal.

7. The ............................ property returns the onClick event handler code on the current
element.
Answer: C. onclick
Meaning: The onclick property is used to access the JavaScript code that executes when an
element is clicked, allowing developers to define specific actions for that event.

8. ............................ is often a name of a function declared elsewhere or a function


expression.
Answer: B. functionRef
Meaning: A functionRef refers to a reference to a function that can be used to invoke it, either
by name or as an expression, facilitating code reuse.

9. The event object passed to the specified event handler function is a ............................
Answer: A. MouseEvent
Meaning: The MouseEvent is an object that contains information about mouse-related events
(like clicks or movements), which is passed to event handler functions for further processing.

10. A ............................ event occurs when a user selects some of the text within a text or
textarea field.
Answer: C. Select
Meaning: The select event is triggered when a user highlights text in a text input or textarea,
often used for enabling specific functionalities, like copying or modifying the selected text.

11. The .............................. handler executes JavaScript code when a select event occurs.
Answer: D. onSelect event
101
Meaning: The onSelect event handler is activated when text is selected, allowing developers to
run specific JavaScript code in response to that action.

12. The onSubmit event is used to validate ALL form fields before submitting it.
Answer: A. True
Meaning: This statement is true, as the onSubmit event is specifically designed to validate all
form inputs to ensure they are correct before the form is sent.

13. When using the onclick event to trigger an action, there is no need to consider adding this
same action to the onkeydown event.
Answer: B. True
Meaning: This statement is true; if an action is already triggered by the onclick event, adding it
to the onkeydown event is usually unnecessary unless a different user interaction is desired.

14. The onclick property returns the onClick event handler code on the previous element.
Answer: B. False
Meaning: This statement is false; the onclick property pertains to the current element, not the
previous one.

15. MouseEvent is an event object passed to the specified event handler function.
Answer: A. True
Meaning: This statement is true, as the MouseEvent object is indeed passed to event handler
functions to provide information about the mouse actions that triggered the event.

Chapter 12: HTML Form


1️. What Are Forms? How Are They Created?

Definition: Forms are sections of a webpage where users can enter information. They are
essential for collecting user data, like names, email addresses, and feedback.

Creation:

• HTML Structure: Forms are created using the <form> tag. This tag acts as a container for
various input elements.

• Input Elements: Inside a form, you can use different types of input fields, like text boxes, radio
buttons, and checkboxes.

2️. How Do You Use Scripts in HTML?

Definition: Scripts are pieces of code that can add functionality to your HTML page, like
interactivity and dynamic content.

Usage:

• Script Tag: You can use the <script> tag to include JavaScript. This can be placed in the
<head> section or at the end of the <body> to enhance the page's interactivity.

102
• External Scripts: You can also link to external JavaScript files using the src attribute in the
<script> tag.

3. Form’s Action Attribute and Submit Button in HTML

Action Attribute:

• Definition: The action attribute specifies where the form data should be sent after submission
(like a server endpoint).

• Example: If your action is set to "submit.php", the data will be sent there when the form is
submitted.

Submit Button:

• Function: The submit button, created with the <input type="submit"> tag, sends the data from
the form to the server defined in the action attribute.

• Appearance: You can customize the button's label to inform users about the action, like
"Submit" or "Send".

4. Text Field and Radio Button in a Form

Text Field:

• Usage: A text field allows users to input single-line text data, like names or email addresses.
It's created using the <input type="text"> tag.

• Labeling: Always pair it with a label for clarity, so users know what information to enter.

Radio Button:

• Usage: Radio buttons let users select one option from a set. They are created using <input
type="radio">.

• Grouping: To ensure that only one radio button in a group can be selected, they should share
the same name attribute.

5. Understanding Forms Output

Output:

• When a form is submitted, the data entered by the user is sent to the server specified in the
action attribute.

• The output can be displayed back to the user or processed to perform actions, like saving to a
database or sending an email.

• Feedback messages (like "Thank you for your submission!") can enhance user experience.

103
6. How to Create Tables in HTML

Definition: Tables are used to display data in rows and columns, making it easy to read and
compare information.

Creation:

• Start with the <table> tag.

• Use <tr> for table rows, <th> for headers, and <td> for data cells.

7. Useful Table Tags in HTML

Tags:

• <table>: Defines the table.

• <tr>: Defines a row in the table.

• <th>: Defines a header cell (bold and centered by default).

• <td>: Defines a standard data cell.

• <caption>: Adds a title to the table.

8. Significance of Comments in HTML

Purpose:

• Comments are notes written in the code that do not appear on the webpage. They help
developers understand the code better.

• They are added using <!-- comment here --> syntax, making it easier to document complex
sections or remind yourself of important details.

9. Using HTML Checkboxes in a Form

☑️ Checkbox:

• Definition: Checkboxes allow users to select multiple options at once. They are created using
<input type="checkbox">.

• Grouping: Each checkbox should have its unique name attribute to distinguish them when
processing data.

Example: Imagine a survey asking about favorite fruits. You could have checkboxes for options like
"Apple," "Banana," and "Cherry," allowing users to select as many as they like.

1️0. Describe the Use of <font> with Example

104
Font Tag:

• Definition: The <font> tag was used to change text appearance, such as size, color, and
typeface. However, it's outdated and not recommended for modern web design.

• Usage: It was typically used like this: <font color="red" size="4">This is red text.</font>.

Note: Today, it's better to use CSS for styling text to ensure better compatibility and
maintainability.

MCQ Questions with their answers

1. Which method sends the form information by including it on the URL?


C. get
Explanation: The GET method appends form data to the URL in name/value pairs, making it
visible in the URL.

2. Which method sends the form information in the HTTP environment?


B. Post
Explanation: The POST method sends form data within the HTTP request body, making it more
secure than GET, as data is not displayed in the URL.

3. Which attribute specifies the URL to send the data to?


A. Action
Explanation: The action attribute of the tag defines the URL to which the form data will be sent
upon submission.

4. Which tag is used to create a basic button?


D.
Explanation: The tag can be used to create various types of user interface elements, including
buttons.

5. Within the code, which type is used to set the control to a button?
A. button
Explanation: Setting type="button" in the tag creates a button that can trigger a JavaScript
function or submit a form.

6. A text field is placed on a web page using the tag, with the attribute set with a value of
“text”.
C. type
Explanation: The type attribute defines the type of input control, such as text, password,
checkbox, etc.

7. The HTML tag that represents a group of introductory or navigational aids is?
B.
Explanation: The tag is used to group introductory content or navigational links in an HTML
document.

105
8. What are text fields that can span several lines called?
D. Text areas
Explanation: A text area is an input element that allows users to enter multi-line text.

9. Which tag is used to end the text area?


A.
Explanation: The tag is used to close a text area that was opened with the tag.

10. What is used when you want to let the visitor select one or more options from a set of
alternatives?
C. Check boxes
Explanation: Checkboxes allow users to select multiple options from a list.

11. If only one option is to be selected at a time, you should use?


A. Radio buttons
Explanation: Radio buttons allow only one option to be selected at a time from a group.

12. The Radio Button in HTML is a type of?


Input
Explanation: Radio buttons are input elements that allow users to select one option from a
group.

13. What specifies the output value of an input element in an HTML page when it is clicked?

Explanation: The value attribute of an input element defines the data that is sent to the server
when the form is submitted.

14. HTML fields that provide essentially the same functionality as HTML Checkbox Fields are?
Select
Explanation: A select field allows users to choose one or more options from a dropdown list,
similar to checkboxes.

15. Depending on your settings, what can serve the same purpose as radio buttons or
checkboxes?
Drop-down menu
Explanation: A drop-down menu allows users to select one or more options, similar to radio
buttons or checkboxes, but in a compact format.

Chapter 13: Building Object of JavaScript


1️. JavaScript as a Scientific Calculator

JavaScript can be used to create a scientific calculator, which performs complex mathematical
operations. Here’s how it works:

• Basic Operations: You can perform addition, subtraction, multiplication, and division using
JavaScript's arithmetic operators.

106
• Advanced Functions: JavaScript includes the Math object, which provides advanced
mathematical functions like square roots, exponents, trigonometric functions (sine, cosine),
and logarithms.

• User Input: You can create forms that allow users to input numbers and select operations,
which the JavaScript code processes to display results.

• Dynamic Updates: Using JavaScript, you can make your calculator update results in real-time
without needing to refresh the page.

2️. Objects in JavaScript

In JavaScript, an object is a collection of properties and methods. Here are the key points:

• Properties: These are values associated with the object. For example, a car object may have
properties like color, model, and year.

• Methods: These are functions that belong to the object and can perform actions or
calculations. For example, a car object might have a method called drive() that changes its
state.

• Types of Objects: JavaScript has built-in objects (like Date, Math, and String) and allows you to
create your own custom objects.

3. Methods of the Math Object in JavaScript

The Math object provides several useful methods for mathematical calculations. Some of them
include:

• Math.abs(): Returns the absolute value of a number.

• Math.ceil(): Rounds a number up to the nearest integer.

• Math.floor(): Rounds a number down to the nearest integer.

• Math.sqrt(): Calculates the square root of a number.

• Math.pow(): Raises a number to the power of another number.

• Math.random(): Generates a random number between 0 and 1.

4. Properties of the Math Object in JavaScript

The Math object also includes several properties that are constants:

• Math.PI: Represents the value of π (pi), approximately 3.14159.

• Math.E: Represents Euler's number, approximately 2.71828.

• Math.LN2️: The natural logarithm of 2, approximately 0.693147.

107
• Math.LN1️0: The natural logarithm of 10, approximately 2.302585.

• Math.SQRT2️: The square root of 2, approximately 1.414214.

5. Creating a New Object in JavaScript

You can create a new object in JavaScript using different methods:

• Object Literal: You can create an object using curly braces {} and defining properties.

• Constructor Function: You can define a function that serves as a blueprint for creating objects
and use the new keyword.

• Object.create(): You can create a new object with a specified prototype object.

6. User-Defined Objects

User-defined objects are custom objects that you create in your JavaScript code. Here’s what you
should know:

• Customization: You can define properties and methods that are specific to your needs.

• Organization: They help in organizing code by grouping related data and functions together.

• Examples: You might create a Person object with properties like name and age, and methods
like greet().

7. Properties and Methods of the Date Object

The Date object in JavaScript is used to work with dates and times. Key points include:

• Properties:

o Date.now(): Returns the current timestamp.

o getFullYear(): Gets the year (4 digits) of the specified date.

o getMonth(): Gets the month (0-11) for the specified date.

• Methods:

o setDate(): Sets the day of the month for a specified date.

o getHours(): Returns the hour (0-23) of a specified date.

o toString(): Returns a string representation of the date.

8. String Object in JavaScript

A String object represents a sequence of characters. Here’s what it includes:

108
• Immutable: Strings in JavaScript are immutable, meaning once created, they cannot be
changed.

• Properties:

o length: Returns the number of characters in a string.

• Methods:

o charAt(): Returns the character at a specified index.

o indexOf(): Returns the position of the first occurrence of a specified value in a string.

o toLowerCase(): Converts the string to lowercase.

9. Get Methods of the Date Object

The Date object has several "get" methods that retrieve specific information about a date:

• getDate(): Returns the day of the month (1-31) for the specified date.

• getDay(): Returns the day of the week (0-6) for the specified date, where 0 is Sunday.

• getHours(): Returns the hour (0-23) for the specified date.

• getMinutes(): Returns the minutes (0-59) for the specified date.

• getSeconds(): Returns the seconds (0-59) for the specified date.

10. Overview of String Methods

In JavaScript, strings are a fundamental data type used to represent text. Two important methods for
searching within strings are indexOf and lastIndexOf. These methods help locate the position of a
specified substring (a part of the string) within the main string.

Comparison Table

Feature indexOf lastIndexOf

Finds the first occurrence of a Finds the last occurrence of a substring in a


Purpose
substring in a string. string.

Search Searches from the beginning (left to


Searches from the end (right to left).
Direction right).

Return Returns the index (position) of the Returns the index of the last occurrence, or -1 if
Value first occurrence, or -1 if not found. not found.

109
Feature indexOf lastIndexOf

Accepts an optional parameter to Also accepts an optional parameter to specify


Starting
specify the starting position for the the starting position for the search (searching
Position
search. backwards).

Use Useful when you want to find where Useful when you want to find the position of the
Cases a word or character first appears. last occurrence of a word or character.

Detailed Explanation

Purpose

• indexOf: This method is designed to find the first occurrence of a specified substring within a
string. For example, if you have a sentence and want to know where the first occurrence of the
word "apple" appears, indexOf will help you find it.

• lastIndexOf: In contrast, this method finds the last occurrence of a specified substring in the
string. So, if you're interested in knowing where the last "apple" appears in the same sentence,
lastIndexOf will provide that information.

Search Direction

• indexOf: When you use indexOf, the search starts from the left side (the beginning) of the
string and moves towards the right. This means it looks for the substring as it encounters
characters from the start of the string to the end.

• lastIndexOf: Conversely, lastIndexOf begins its search from the right side (the end) of the
string and moves towards the left. It scans backwards, making it effective for locating the final
instance of the substring.

Return Value

• indexOf: If the substring is found, indexOf returns the index (or position) of its first
appearance. If the substring is not present in the string, it returns -1️.

• lastIndexOf: Similarly, lastIndexOf returns the index of the last occurrence of the specified
substring. If it cannot find the substring, it also returns -1️.

Starting Position

• Both Methods: Both indexOf and lastIndexOf can accept an optional parameter that indicates
the starting position for the search. For indexOf, you can start searching from any index in the
string, and for lastIndexOf, you can also specify an index from which the backward search will
start.

Use Cases

110
• indexOf: This method is particularly useful in situations where you want to know where
something first occurs, like when validating user input, checking for keywords in a search, or
parsing text data.

• lastIndexOf: This method is handy when you need to know the last position of a substring,
such as when processing logs, looking for the most recent instance of a word, or when
analyzing a string that may have repeating patterns.

MCQ Questions with their answers

1. JavaScript’s Math object provides advanced arithmetic and trigonometric functions,


expanding on JavaScript’s basic arithmetic operators.

o Answer: C. Math
Meaning: The Math object in JavaScript is a built-in object that provides mathematical
constants and functions, enhancing the basic arithmetic capabilities of the language.

2. The Date object is useful when you want to display a date or use a timestamp in some sort
of calculation.

o Answer: A. Date
Meaning: The Date object allows you to work with dates and times in JavaScript,
providing methods to manipulate date and time values.

3. A Property is a value or set of values (in the form of an array or object) that is a member of
an object.

o Answer: D. Property
Meaning: Properties are characteristics of objects, defined by key-value pairs. They can
hold various types of values, including arrays and other objects.

4. A Method is a function that is a member of an object.

o Answer: B. Method
Meaning: Methods are functions that belong to an object, allowing the object to
perform actions related to its properties.

5. The String object lets you work with a series of characters and wraps JavaScript’s string
primitive data type with a number of helper methods.

o Answer: C. String
Meaning: The String object provides various methods to manipulate and interact with
strings in JavaScript, such as searching, slicing, and concatenating.

6. The Prototype property allows you to add properties and methods to an object.

o Answer: A. Prototype
Meaning: The prototype property is used to share properties and methods across all
instances of an object, facilitating inheritance in JavaScript.

7. Unlike the other global objects, Math is not a/an constructor.

111
o Answer: D. constructor
Meaning: Math is a built-in object that contains static methods and properties and is
not intended to be instantiated like typical objects.

8. All properties and methods of Math are static and can be called by using Math as an
object without creating it.

o Answer: D. static
Meaning: Static properties and methods belong to the class itself rather than instances
of the class, allowing direct access without instantiation.

9. The Date Object is used to work with dates and times.

o Answer: B. Date Object


Meaning: The Date Object provides functionality to handle dates and times, enabling
various operations and formats.

10. Date objects are created with the Date() constructor.

o Answer: A. Date()
Meaning: The Date constructor is called to create new Date objects, allowing you to
create instances that represent specific points in time.

11. All user-defined objects and built-in objects are descendants of an object called Object.

o Answer: C. Object
Meaning: In JavaScript, all objects inherit from a common prototype called Object,
which is the base for all objects in the language.

12. The New operator is used to create an instance of an object.

o Answer: B. New
Meaning: The new operator is used to create new instances of objects, invoking
constructors to initialize them.

13. A Constructor is a function that creates and initializes an object.

o Answer: D. Constructor
Meaning: A constructor is a special type of function used to create objects, often
initializing their properties with specific values.

14. The Variable contains a reference to the new object.

o Answer: B. Variable
Meaning: When an object is created using a constructor, the new object is assigned to a
variable, which holds a reference to that object.

15. The properties assigned to the object are not variables and are not defined with the Var
keyword.

o Answer: A. Var
Meaning: Properties of an object are not declared with the var keyword; they are
assigned directly to the object, differing from variable declarations.

112
Chapter 14: Basics of jQuery
1️. Should jQuery be Used?

Reasons to Use jQuery:

• Simplifies JavaScript: jQuery is a fast, small, and feature-rich JavaScript library that
simplifies things like HTML document traversal and manipulation, event handling, and
animation. It makes it easier for developers to work with JavaScript.

• Cross-Browser Compatibility: jQuery handles many of the inconsistencies between


different web browsers. This means you can write code once and expect it to work across
various browsers without having to add additional checks or fixes.

• Powerful Effects and Animations: jQuery provides many built-in methods for creating
effects and animations, making it simple to add dynamic behavior to web pages without having
to code complex animations from scratch.

• Extensive Plugins: The jQuery community has developed a wide range of plugins that can
easily be integrated into projects, adding functionality like sliders, pop-ups, and more with
minimal effort.

• Easy DOM Manipulation: jQuery provides an intuitive syntax for selecting and
manipulating HTML elements, making tasks like changing text, adding classes, or modifying
attributes straightforward.

Reasons Against Using jQuery:

• Performance Overhead: jQuery can add extra weight to your project, which may impact
performance. For simple tasks, native JavaScript methods can be more efficient.

• Learning Curve: If you are new to JavaScript, learning jQuery might add unnecessary
complexity, as it introduces another layer of abstraction.

• Modern Alternatives: With advancements in JavaScript (like ES6 and beyond) and the rise
of frameworks like React, Vue, and Angular, many developers prefer using native JavaScript or
these modern frameworks instead of jQuery.

2️. Different Ways of Selecting Elements in HTML and Performing Actions on Them

Common Ways to Select Elements:

• By ID: Use document.getElementById('id') to select a unique element by its ID.

• By Class Name: Use document.getElementsByClassName('className') to select


elements by their class. This returns a collection of elements.

• By Tag Name: Use document.getElementsByTagName('tagName') to select all elements of


a specified type.
113
• Query Selector: Use document.querySelector('selector') to select the first element that
matches a CSS selector, or document.querySelectorAll('selector') for all matching elements.

Performing Actions on Selected Elements:

Once elements are selected, various actions can be performed, such as:

• Changing Content: Modify the inner HTML or text content of an element.

• Changing Styles: Apply CSS styles to the selected elements.

• Adding/Removing Classes: Use methods to add or remove CSS classes for styling
changes.

• Adding Event Listeners: Attach events (like clicks or hovers) to perform actions when a
user interacts with an element.

3. Different jQuery Selectors with Examples

jQuery Selectors:

• Basic Selector: Selects elements by tag, class, or ID.

o Example: $('p') selects all <p> tags.

• Child Selector: Selects direct children of an element.

o Example: $('ul > li') selects <li> elements that are direct children of <ul>.

• Attribute Selector: Selects elements based on attributes.

o Example: $('[href]') selects all elements with an href attribute.

• Contains Selector: Selects elements that contain a specific text.

o Example: $(':contains("Hello")') selects elements containing the text "Hello".

• Multiple Selectors: Selects multiple elements at once.

o Example: $('h1, h2, h3') selects all <h1>, <h2>, and <h3> tags.

Using Selectors:

These selectors can be used in conjunction with jQuery methods to perform actions like changing
text, adding classes, or even chaining multiple actions together for a streamlined approach.

4. What is a jQuery Event Method?

Definition:

jQuery event methods are functions that allow you to capture and respond to user interactions with
elements on a webpage, such as clicks, hovers, and keyboard inputs.

114
Implementing Event Methods:

1. Click Event: Use .click() to execute a function when an element is clicked.

o Example: $('#button').click(function() { alert('Button clicked!'); });

2. Hover Event: Use .hover() to specify functions to run when an element is hovered over.

o Example: $('#element').hover(function() { $(this).css('color', 'red'); }, function() {


$(this).css('color', 'black'); });

3. Key Event: Use .keydown() or .keyup() to trigger a function when a key is pressed or
released.

o Example: $(document).keydown(function(event) { console.log(event.key); });

4. Form Events: Handle events like .submit() to perform actions when a form is submitted.

o Example: $('form').submit(function(event) { event.preventDefault(); alert('Form


submitted!'); });

Summary:

Event methods make it easy to create interactive and responsive web pages by enabling developers to
specify what happens when users interact with different elements.

5. Replacing an Element in the HTML DOM with replaceChild()

Overview:

The replaceChild() method is a DOM manipulation function that allows you to replace an existing child
node with a new node.

How It Works:

1. Select the Parent Node: First, select the parent element that contains the child you want to
replace.

2. Create the New Node: Use document.createElement() or similar methods to create a new
node.

3. Select the Child Node: Identify the child node you want to replace.

4. Replace the Child: Call the replaceChild() method, passing in the new node and the old node.

Example Concept:

Imagine you have a <div> that contains an old image and you want to replace it with a new one:

• Original Element: <div id="container"><img src="old.jpg" alt="Old Image" /></div>

• New Element: Create a new image element with src="new.jpg".

Implementation:

<div id="container">
115
<img id="oldImage" src="old.jpg" alt="Old Image" />

</div>

• JavaScript Logic:

o Select the parent <div>.

o Create the new <img> element.

o Use replaceChild() to replace the old image with the new one.

Summary:

Using replaceChild() allows you to dynamically change parts of the HTML DOM, providing a way to
update the content without removing the entire parent element.

MCQ Questions with their answers

1. The ______________ property returns the number of the internet host port (of the current
page).
A. window.location.port
Explanation: This property retrieves the port number used in the URL of the current page,
which is part of the window.location object.

2. The ______________ property returns the URL of the current page.


C. window.location.href
Explanation: The href property provides the complete URL of the current page, including the
protocol, host, port, path, and query string.

3. How are the objects organized in the HTML DOM?


D. hierarchy
Explanation: The HTML Document Object Model (DOM) organizes elements in a hierarchical
structure, resembling a tree, where each node represents a part of the document.

4. The DOM is a W3C____ standard.


B. W3C
Explanation: The DOM (Document Object Model) is a standard defined by the World Wide Web
Consortium (W3C) to provide a way to interact with and manipulate HTML and XML
documents.

5. Which of the following is/are the part/parts of the W3C DOM standard?
D. Core DOM, XML DOM, and HTML DOM
Explanation: The W3C DOM standard comprises three parts: Core DOM (which deals with the
general structure of documents), XML DOM (which specifically addresses XML documents),
and HTML DOM (which relates to HTML documents).

6. _________ standard model for all document types.


A. Core DOM
Explanation: The Core DOM is a standard model applicable to all document types, providing a
basic structure for representing documents.
116
7. What among the following is an appropriate event handler for input text among the below
options?
B. onchange
Explanation: The onchange event handler is triggered when the value of an input element
changes and the element loses focus, making it suitable for input fields.

8. What among the following is appropriate when an event occurs when the user clicks on an
element?
A. onclick
Explanation: The onclick event handler is triggered when a user clicks on an element, making
it useful for interactive elements like buttons.

9. What is the purpose of the Legacy DOM?


C. Allows access to a few keys and elements
Explanation: The Legacy DOM allows limited access to certain keys and elements in the
document, primarily for backward compatibility with older scripts.

10. What is the purpose of the NamedNodeMap object?


C. Unordered collection of nodes
Explanation: A NamedNodeMap is an unordered collection of nodes, often used to represent
attributes of an element.

11. According to the W3C HTML DOM standard, everything in an HTML document is a ______.
NODE
Explanation: In the HTML DOM, every component of an HTML document (elements, attributes,
text, etc.) is represented as a node.

12. The _________ Constraint Validation HTML Input attribute specifies that the input field
requires an element.
required
Explanation: The required attribute indicates that a user must fill out the input field before
submitting the form.

13. The ________ HTML object property returns the domain name of the document server.
document.domain
Explanation: The document.domain property provides the domain name of the server that
hosts the current document.

14. The ________ JavaScript DOM method is used to create an HTML element.
document.createElement(element)
Explanation: This method creates a new HTML element specified by the element argument,
allowing dynamic manipulation of the document structure.

15. The __________ object lies at the top of the DOM hierarchy.
window object
Explanation: The window object is the root of the DOM hierarchy and serves as the global
object in web browsers, containing all global variables and functions.

117

You might also like