Web Systems and Technologies Light
Web Systems and Technologies Light
Selectors ...................................................................................................................... 85
For more than two decades, web development has been the architect of the online world,
transforming how we communicate, do business, and access information. From simple static
pages to dynamic web applications, developers create the intricate tapestry of the digital
landscape.
They use languages like HTML, CSS, and JavaScript to transform data into visually appealing
and functionally flawless experiences. Their knowledge extends beyond the visible screen,
encompassing databases, servers, and security protocols to ensure a strong and secure
foundation.
Web development is more than just a technical pursuit; it is a catalyst for innovation. It
enables businesses to reach global audiences, fosters community connections, and drives
progress across industries. From innovative e-commerce platforms to interactive educational
tools,
4
How the Web Works?
The World Wide Web (WWW), initially termed the web, represents just one avenue for
disseminating information across the internet. Its distinctive feature lies in the ability to
interconnect documents through hypertext links, creating an expansive 'web' of
interconnected information. The web operates on the HyperText Transfer Protocol (HTTP), a
familiar acronym as the initial four letters in the majority of website addresses.
To better understand, Figure 1-1 shows a short representation on how the web works. You
visit a website like google.com. The moment you enter this address in your browser and you
hit ENTER, a lot of different things happen:
5
2. A Request is sent to the server of the website
3. The response of the server is parsed
4. The page is rendered and displayed
Actually, every single step could be split up in multiple other steps, but for a good overview
of how it all works, that's something we can ignore here.
6
A Multitude of Devices
Until 2007, we could be relatively certain that our users were visiting our sites while sitting
at their desks, looking at a large monitor, using a speedy internet connection. We had all
more or less settled on 960 pixels as a good width for a web page based on the most
common monitor size. Back then, our biggest concern was dealing with the dozen or so
desktop browsers and jumping through a few extra hoops to support quirky old versions of
Internet Explorer. And we thought we had it rough!
Although you could access web pages and web content on mobile phones prior to 2007, the
introduction of the iPhone and Android smartphones as well as faster networks heralded a
huge shift in how, when, and where we do our web surfing (particularly in the United States,
which lagged behind Asia and the EU in mobile technology). Since then, we’ve seen the
introduction of phones and tablets of all different dimensions, as well as web browsers on
TVs, gaming systems, and other devices. And the diversity is only going to increase. I think
mobile web design expert Brad Frost sums it up nicely in his illustrations in Figure 1-2.
Figure 1-2: Brad Frost sums up the reality of device diversity nicely (bradfrostweb.com).
7
Setting Up Code Editor
Setting up a code editor is a crucial step in the process of web development, as it directly
influences the efficiency and productivity of developers. While there are various code editors
available, Visual Studio Code (VSCode) stands out as a highly recommended choice due to
its robust features, extensibility, and widespread adoption in the development community.
Intelligent Code Assistance: Code editors like Visual Studio Code provide intelligent
suggestions and code assistance, aiding developers in writing cleaner and error-free
code. Features like IntelliSense make it easier to explore APIs, libraries, and
frameworks, leading to a smoother coding experience.
Version Control Integration: Integration with version control systems, such as Git,
is essential in collaborative web development projects. A good code editor streamlines
version control processes, allowing developers to commit, pull, and push changes
seamlessly.
8
Extensions
Icons
You can install Material Icon Theme it supports almost every file extension and can be
customized for everyone's needs.
Automatically rename paired HTML/XML tag, same as Visual Studio IDE does.
Automatically add HTML/XML close tag, same as Visual Studio IDE or Sublime Text does.
A basic spell checker that works well with code and documents. The goal of this spell
checker is to help catch common spelling errors while keeping the number of false positives
low.
Error Lens
ErrorLens turbocharges language diagnostic features by making diagnostics stand out more
prominently, highlighting the entire line wherever a diagnostic is generated by the language
and also prints the message inline.
ESLint
GitLens
GitLens supercharges Git inside VS Code and unlocks untapped knowledge within each
repository. It helps you to visualize code authorship at a glance via Git blame annotations
and CodeLens, seamlessly navigate and explore Git repositories, gain valuable insights via
rich visualizations and powerful comparison commands, and so much more.
Import Cost
This extension will display inline in the editor the size of the imported package. The
extension utilizes webpack in order to detect the imported size.
Prettier is an opinionated code formatter. It enforces a consistent style by parsing your code
9
and re-printing it with its own rules that take the maximum line length into account,
wrapping code when necessary.
The extension provides syntax highlighting, TypeScript support, and intellisense for template
expressions and component props.
10
Module 2 - Introduction to HTML
(HyperText Markup Language)
HTML, or HyperText Markup Language, is the fundamental building block of the World Wide
Web. It provides the structure for creating and presenting content on the internet.
Developed by Sir Tim Berners-Lee in 1991, HTML plays a pivotal role in web development by
defining the structure of web pages.
What is HTML?
HTML is a markup language that uses a system of tags to structure and format content on a
webpage. Each tag defines a specific element on the page, such as headings, paragraphs,
images, links, and more. HTML documents consist of a hierarchy of nested tags, forming a
tree-like structure that browsers interpret to render web pages.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Document Title</title>
</head>
<body>
<!-- Content goes here -->
</body>
</html>
<!DOCTYPE html>: Declares the document type and version of HTML being used.
<html>: The root element that wraps the entire HTML content.
<head>: Contains meta-information about the document, such as character encoding
11
and viewport settings.
<meta>: Provides additional information about the document, like character set and
viewport configuration.
<title>: Sets the title of the webpage, displayed in the browser's title bar or tab.
<body>: Contains the main content of the webpage, including text, images, links, and
other elements.
HTML Tags:
HTML tags are enclosed in angle brackets (< >) and come in pairs – an opening tag and a
closing tag. The content to be formatted is placed between these tags. For example:
<h1>This is a Heading</h1>
<p>This is a paragraph of text.</p>
<a href="https://www.example.com">Visit Example.com</a>
<img src="image.jpg" alt="Description of the image">
<h1> to <h6>: Headings, with <h1> being the largest and <h6> the smallest.
<p>: Paragraphs of text.
<a>: Links to other web pages.
<img>: Images.
Once created, you can open your HTML file in a web browser to see how it renders. As you
progress in your web development journey, you'll learn to enhance your HTML pages with
CSS (Cascading Style Sheets) for styling and JavaScript for interactivity.
HTML is the cornerstone of web development, providing the structure that allows browsers
to interpret and display content, making it an essential language for anyone aspiring to build
websites.
12
Marking Up Text
HTML Anatomy
HTML is composed of elements. These elements structure the webpage and define its
content. Let’s take a look at how they’re written.
The diagram below displays an HTML paragraph element. As we can see, the paragraph
element is made up of:
A tag and the content between it is called an HTML element. There are many tags that we
can use to organize and display text and other types of content, like images.
13
bracket.
Opening Tag — the first HTML tag used to start an HTML element. The tag type is
surrounded by opening and closing angle brackets.
Content — The information (text or other elements) contained between the opening
and closing tags of an HTML element.
Closing tag — the second HTML tag used to end an HTML element. Closing tags have
a forward slash (/) inside of them, directly after the left angle bracket.
The Body
One of the key HTML elements we use to build a webpage is the body element. Only content
inside the opening and closing body tags can be displayed to the screen. Here’s what
opening and closing body tags look like:
<body>
</body>
Once the file has a body, many different types of content – including text, images, and
buttons – can be added to the body.
<body>
<p>Welcome, IT Buddies!</p>
</body>
Exercise 2-1
HTML Structure
HTML is organized as a collection of family tree relationships. As you saw in the last
14
exercise, we placed <p> tags within <body> tags. When an element is contained inside
another element, it is considered the child of that element. The child element is said to be
nested inside the parent element.
<body>
<p>This paragraph is a child of the body</p>
</body>
In the example above, the <p> element is nested inside the <body> element. The <p>
element is considered a child of the <body> element, and the <body> element is
considered the parent. You can also see that we’ve added two spaces of indentation (using
the space bar) for better readability.
Since there can be multiple levels of nesting, this analogy can be extended to grandchildren,
great-grandchildren, and beyond. The relationship between elements and their ancestor and
descendent elements is known as hierarchy.
Let’s consider a more complicated example that uses some new tags:
<body>
<div>
<h1>Sibling to p, but also grandchild of body</h1>
<p>Sibling to h1, but also grandchild of body</p>
</div>
</body>
In this example, the <body> element is the parent of the <div> element. Both the <h1>and
<p> elements are children of the <div> element. Because the <h1> and <p> elements are
at the same level, they are considered siblings and are both grandchildren of the <body>
element.
Understanding HTML hierarchy is important because child elements can inherit behavior and
styling from their parent element. You’ll learn more about webpage hierarchy when you
start digging into CSS.
Exercise 2-2
1. Insert the following html snippet to your html file then open to your browser.
15
<body>
<h1>Hello World</h1>
<p>This paragraph is a child of the body element</p>
<div>
<p>This paragraph is a child of the div element and a grandchild
of the body element</p>
</div>
</body>
Headings
Headings in HTML are similar to headings in other types of media. For example, in
newspapers, large headings are typically used to capture a reader’s attention. Other times,
headings are used to describe content, like the title of a movie or an educational article.
HTML follows a similar pattern. In HTML, there are six different headings, or heading
elements. Headings can be used for a variety of purposes, like titling sections, articles, or
other forms of content.
The following is the list of heading elements available in HTML. They are ordered from
largest to smallest.
<h1> — used for main headings. All other smaller headings are used for subheadings.
<h2>
<h3>
<h4>
<h5>
<h6>
The following example code uses a headline intended to capture a reader’s attention. It uses
the largest heading available, the main heading element:
<h1>ANNOUNCEMENT</h1>
Exercise 2-3
1. Now that you know how to structure HTML elements, we’ll spend the rest building an
informational website using some of the most common HTML elements. We’ve put
some elements in to get you started, but you’ll write the rest of the page on your own.
16
<body>
<h1>The Brown Bear</h1>
<h2>About Brown Bears</h2>
<h3>Species</h3>
<h3>Features</h3>
</body>
2. Below the <h3> heading that says Features, add an <h2> heading that says Habitat.
3. Below the Habitat heading, add an <h3> heading that says Countries with Large
Brown Bear Populations.
4. On the next line, add one more <h3> heading that says Countries with Small Brown
Bear Populations.
5. Finally, on the next line add an <h2> heading that says Media.
Divs
One of the most popular elements in HTML is the <div> element. <div> is short for
“division” or a container that divides the page into sections. These sections are very useful
for grouping elements in your HTML together.
<body>
<div>
<h1>Why use divs?</h1>
<p>Great for grouping elements!</p>
</div>
</body>
`<div>`s can contain any text or other HTML elements, such as links,
images, or videos. Remember to always add two spaces of indentation or
tab when you nest elements inside of `<div>`s for better readability.
17
Exercise 2-4
<body>
<h1>The Brown Bear</h1>
<h2>About Brown Bears</h2>
<h3>Species</h3>
<h3>Features</h3>
<h2>Habitat</h2>
<h3>Countries with Large Brown Bear Populations</h3>
<h3>Countries with Small Brown Bear Populations</h3>
<h2>Media</h2>
</body>
2. Below the <h1> heading that says The Brown Bear, add an opening <div> tag. Place
the closing </div> tag after the <h3> element that says Features. Remember to use
your tab to add indentation when you nest elements.
3. Above the <h2> element that says Habitat, add an opening <div> tag. Close the
</div> tag after the <h3> element that says Countries with Small Brown Bear
Populations.
4. Above the <h2> element that says Media, add an opening <div> tag. Place the
closing </div> tag right above the closing </body> tag.
Attributes
If we want to expand an element’s tag, we can do so using an attribute. Attributes are
content added to the opening tag of an element and can be used in several different ways,
from providing information to changing styling. Attributes are made up of the following two
parts:
One commonly used attribute is the id. We can use the id attribute to specify different
content (such as <div>s) and is really helpful when you use an element more than once. ids
have several different purposes in HTML, but for now, we’ll focus on how they can help us
identify content on our page.
18
<div id="intro">
<h1>Introduction</h1>
</div>
Exercise 2-5
<body>
<h1>The Brown Bear</h1>
<div>
<h2>About Brown Bears</h2>
<h3>Species</h3>
<h3>Features</h3>
</div>
<div>
<h2>Habitat</h2>
<h3>Countries with Large Brown Bear Populations</h3>
<h3>Countries with Small Brown Bear Populations</h3>
</div>
<div>
<h2>Media</h2>
</div>
</body>
2. Add an id attribute with the value "introduction" to the <div> tag that’s below the
The Brown Bear <h1> heading.
3. Add an id attribute with the value "habitat" to the opening <div> tag that has the
Habitat <h2> heading as a child.
4. Add an id attribute with the value "media" to the opening <div> tag that has the
Media <h2> heading as a child.
Displaying Text
If you want to display text in HTML, you can use a paragraph or span:
19
<div>
<h1>Technology</h1>
</div>
<div>
<p><span>Self-driving cars</span> are anticipated to replace up to 2
million jobs over the next two decades.</p>
</div>
In the example above, there are two different <div>. The second <div> contains a <p>
with <span>Self-driving cars</span>. This <span> element separates “Self-driving cars”
from the rest of the text in the paragraph.
It’s best to use a <span> element when you want to target a specific piece of content that is
inline, or on the same line as other text. If you want to divide your content into blocks, it’s
better to use a <div>.
Exercise 2-5
<body>
<h1>The Brown Bear</h1>
<div id="introduction">
<h2>About Brown Bears</h2>
<h3>Species</h3>
<h3>Features</h3>
</div>
<div id="habitat">
<h2>Habitat</h2>
<h3>Countries with Large Brown Bear Populations</h3>
<h3>Countries with Small Brown Bear Populations</h3>
</div>
<div id= "media">
<h2>Media</h2>
</div>
</body>
2. Below the <h2> element that says About Brown Bears, add <p> opening and closing
tags, and inside the tags put the following text:
20
The brown bear (Ursus arctos) is native to parts of northern Eurasia and
North America. Its conservation status is currently Least Concern. There
are many subspecies within the brown bear species, including the Atlas
bear and the Himalayan brown bear.
Remember to always add indentation when you nest elements inside <div>s for better
readability.
3. Below the <h3> element that says Features, add a paragraph with the following text:
Brown bears are not always completely brown. Some can be reddish or
yellowish. They have very large, curved claws and huge paws. Male brown
bears are often 30% larger than female brown bears. They can range from
5 feet to 9 feet from head to toe.
4. Under the <h3> element that says: Countries with Small Brown Bear
Populations
Styling Text
You can also style text using HTML tags. The <em> tag emphasizes text, while the
<strong> tag highlights important text.
Later, when you begin to style websites, you will decide how you want browsers to display
content within <em> and <strong> tags. Browsers, however, have built-in style sheets that
will generally style these tags in the following ways:
21
<p><strong>The Nile River</strong> is the <em>longest</em> river in the
world, measuring over 6,850 kilometers long (approximately 4,260
miles).</p>
In this example, the <strong> and <em> tags are used to emphasize the text to produce
the following:
The Nile River is the longest river in the world, measuring over 6,850 kilometers long
(approximately 4,260 miles).
Exercise 2-6
<body>
<h1>The Brown Bear</h1>
<div id="introduction">
<h2>About Brown Bears</h2>
<p>The brown bear (Ursus arctos) is native to parts of northern
Eurasia and North America. Its conservation status is currently Least
Concern. There are many subspecies within the brown bear species,
including the Atlas bear and the Himalayan brown bear.</p>
<h3>Species</h3>
<h3>Features</h3>
<p>Brown bears are not always completely brown. Some can be reddish
or yellowish. They have very large, curved claws and huge paws. Male
brown bears are often 30% larger than female brown bears. They can range
from 5 feet to 9 feet from head to toe.</p>
</div>
...
22
...
<div id="habitat">
<h2>Habitat</h2>
<h3>Countries with Large Brown Bear Populations</h3>
<h3>Countries with Small Brown Bear Populations</h3>
<p>Some countries with smaller brown bear populations include
Armenia, Belarus, Bulgaria, China, Finland, France, Greece, India,
Japan, Nepal, Poland, Romania, Slovenia, Turkmenistan, and
Uzbekistan.</p>
</div>
<div id="media">
<h2>Media</h2>
</div>
</body>
2. In the first paragraph that starts “The brown bear…”, emphasize Ursus arctos using
the <em> tag.
3. In the paragraph under About Brown Bears, make the words Least Concern strong
using the <strong> tag.
Line Breaks
The spacing between code in an HTML file doesn’t affect the positioning of elements in the
browser. If you are interested in modifying the spacing in the browser, you can use HTML’s
line break element: <br>.
The line break element is unique because it is only composed of a starting tag. You can use
it anywhere within your HTML code and a line break will be shown in the browser.
<p>The Nile River is the longest river <br> in the world, measuring over
6,850 <br> kilometers long (approximately 4,260 <br> miles).</p>
The code in the example above will result in an output that looks like the following:
23
Exercise 2-7
<body>
<h1>The Brown Bear</h1>
<div id="introduction">
<h2>About Brown Bears</h2>
<p>The brown bear (<em>Ursus arctos</em>) is native to parts of
northern Eurasia and North America. Its conservation status is currently
<strong>Least Concern</strong>. There are many subspecies within the
brown bear species, including the Atlas bear and the Himalayan brown
bear.</p>
<h3>Species</h3>
<h3>Features</h3>
<p>Brown bears are not always completely brown. Some can be
reddish or yellowish. They have very large, curved claws and huge paws.
Male brown bears are often 30% larger than female brown bears. They can
range from 5 feet to 9 feet from head to toe.</p>
</div>
<div id="habitat">
<h2>Habitat</h2>
<h3>Countries with Large Brown Bear Populations</h3>
<h3>Countries with Small Brown Bear Populations</h3>
<p>Some countries with smaller brown bear populations include
Armenia, Belarus, Bulgaria, China, Finland, France, Greece, India,
Japan, Nepal, Poland, Romania, Slovenia, Turkmenistan, and
Uzbekistan.</p>
</div>
<div id="media">
<h2>Media</h2>
</div>
</body>
2. Add two line breaks (<br>) after the sentence that ends with Least Concern.
Unordered Lists
In addition to organizing text in paragraph form, you can also display content in an easy-to-
read list.
In HTML, you can use an unordered list tag (<ul>) to create a list of items in no particular
order. An unordered list outlines individual list items with a bullet point.
24
The <ul> element should not hold raw text and won’t automatically format raw text into an
unordered list of items. Individual list items must be added to the unordered list using the
<li> tag. The <li> or list item tag is used to describe an item in a list.
<ul>
<li>Limes</li>
<li>Tortillas</li>
<li>Chicken</li>
</ul>
In the example above, the list was created using the <ul> tag and all individual list items
were added using <li> tags.
Limes
Tortillas
Chicken
Exercise 2-8
<body>
<h1>The Brown Bear</h1>
<div id="introduction">
<h2>About Brown Bears</h2>
<p>The brown bear (<em>Ursus arctos</em>) is native to parts of
northern Eurasia and North America. Its conservation status is currently
<strong>Least Concern</strong>. <br><br> There are many subspecies
within the brown bear species, including the Atlas bear and the
Himalayan brown bear.</p>
<h3>Species</h3>
<h3>Features</h3>
<p>Brown bears are not always completely brown. Some can be reddish
or yellowish. They have very large, curved claws and huge paws. Male
brown bears are often 30% larger than female brown bears. They can range
from 5 feet to 9 feet from head to toe.</p>
</div>
25
<div id="habitat">
<h2>Habitat</h2>
<h3>Countries with Large Brown Bear Populations</h3>
<h3>Countries with Small Brown Bear Populations</h3>
<p>Some countries with smaller brown bear populations include
Armenia, Belarus, Bulgaria, China, Finland, France, Greece, India,
Japan, Nepal, Poland, Romania, Slovenia, Turkmenistan, and
Uzbekistan.</p>
</div>
<div id="media">
<h2>Media</h2>
</div>
</body>
2. Under the heading that says Species, create an unordered list. Do not add any list
items to the list just yet.
Arctos
Collarus
Horribilis
Nelsoni (extinct)
Ordered Lists
Ordered lists (<ol>) are like unordered lists, except that each list item is numbered. They
are useful when you need to list different steps in a process or rank items for first to last.
You can create the ordered list with the <ol> tag and then add individual list items to the
list using <li> tags.
<ol>
<li>Preheat the oven to 350 degrees.</li>
<li>Mix whole wheat flour, baking soda, and salt.</li>
<li>Cream the butter, sugar in separate bowl.</li>
<li>Add eggs and vanilla extract to bowl.</li>
</ol>
26
1. Preheat the oven to 350 degrees.
2. Mix whole wheat flour, baking soda, and salt.
3. Cream the butter, sugar in separate bowl.
4. Add eggs and vanilla extract to bowl.
Exercise 2-9
<body>
<h1>The Brown Bear</h1>
<div id="introduction">
<h2>About Brown Bears</h2>
<p>The brown bear (<em>Ursus arctos</em>) is native to parts of
northern Eurasia and North America. Its conservation status is currently
<strong>Least Concern</strong>.<br /><br /> There are many subspecies
within the brown bear species, including the Atlas bear and the
Himalayan brown bear.</p>
<h3>Species</h3>
<ul>
<li>Arctos</li>
<li>Collarus</li>
<li>Horribilis</li>
<li>Nelsoni (extinct)</li>
</ul>
<h3>Features</h3>
<p>Brown bears are not always completely brown. Some can be reddish
or yellowish. They have very large, curved claws and huge paws. Male
brown bears are often 30% larger than female brown bears. They can range
from 5 feet to 9 feet from head to toe.</p>
</div>
27
<div id="habitat">
<h2>Habitat</h2>
<h3>Countries with Large Brown Bear Populations</h3>
<h3>Countries with Small Brown Bear Populations</h3>
<p>Some countries with smaller brown bear populations include
Armenia, Belarus, Bulgaria, China, Finland, France, Greece, India,
Japan, Nepal, Poland, Romania, Slovenia, Turkmenistan, and
Uzbekistan.</p>
</div>
<div id="media">
<h2>Media</h2>
</div>
</body>
2. Under the heading that says Countries with Large Brown Bear Populations, add an
ordered list. Do not add any list items to the list just yet.
Russia
United States
Canada
Images
All of the elements you’ve learned about so far (headings, paragraphs, lists, and spans)
share one thing in common: they’re composed entirely of text! What if you want to add
content to your web page that isn’t composed of text, like images?
The <img> tag allows you to add an image to a web page. Most elements require both
opening and closing tags, but the <img> tag is a self-closing tag. Note that the end of the
<img> tag has a forward slash /. Self-closing tags may include or omit the final slash — both
will render properly.
The <img> tag has a required attribute called src. The src attribute must be set to the
image’s source, or the location of the image. In this case, the value of src must be the
uniform resource locator (URL) of the image. A URL is the web address or local address
where a file is stored.
28
Exercise 2-10
<body>
<h1>The Brown Bear</h1>
<div id="introduction">
<h2>About Brown Bears</h2>
<p>The brown bear (<em>Ursus arctos</em>) is native to parts of
northern Eurasia and North America. Its conservation status is currently
<strong>Least Concern</strong>.<br /><br /> There are many subspecies
within the brown bear species, including the Atlas bear and the
Himalayan brown bear.</p>
<h3>Species</h3>
<ul>
<li>Arctos</li>
<li>Collarus</li>
<li>Horribilis</li>
<li>Nelsoni (extinct)</li>
</ul>
<h3>Features</h3>
<p>Brown bears are not always completely brown. Some can be reddish
or yellowish. They have very large, curved claws and huge paws. Male
brown bears are often 30% larger than female brown bears. They can range
from 5 feet to 9 feet from head to toe.</p>
</div>
29
<div id="habitat">
<h2>Habitat</h2>
<h3>Countries with Large Brown Bear Populations</h3>
<ol>
<li>Russia</li>
<li>United States</li>
<li>Canada</li>
</ol>
<h3>Countries with Small Brown Bear Populations</h3>
<p>Some countries with smaller brown bear populations include
Armenia, Belarus, Bulgaria, China, Finland, France, Greece, India,
Japan, Nepal, Poland, Romania, Slovenia, Turkmenistan, and
Uzbekistan.</p>
</div>
<div id="media">
<h2>Media</h2>
</div>
</body>
2. Under the Media <h2> heading, add an image. Use the following URL as the source
(src) for the image:
https://201-bear.jpg
Image Alts
Part of being an exceptional web developer is making your site accessible to users of all
backgrounds. In order to make the Web more inclusive, we need to consider what happens
when assistive technologies such as screen readers come across image tags.
The alt attribute, which means alternative text, brings meaning to the images on our sites.
The alt attribute can be added to the image tag just like the src attribute. The value of alt
should be a description of the image.
If an image fails to load on a web page, a user can mouse over the area originally
30
intended for the image and read a brief description of the image. This is made
possible by the description you provide in the alt attribute.
Visually impaired users often browse the web with the aid of screen reading software.
When you include the alt attribute, the screen reading software can read the image’s
description out loud to the visually impaired user.
The alt attribute also plays a role in Search Engine Optimization (SEO), because
search engines cannot “see” the images on websites as they crawl the internet.
Having descriptive alt attributes can improve the ranking of your site.
If the image on the web page is not one that conveys any meaningful information to a user
(visually impaired or otherwise), the alt attribute should be left empty.
Exercise 2-11
<body>
<h1>The Brown Bear</h1>
<div id="introduction">
<h2>About Brown Bears</h2>
<p>The brown bear (<em>Ursus arctos</em>) is native to parts of
northern Eurasia and North America. Its conservation status is currently
<strong>Least Concern</strong>.<br /><br /> There are many subspecies
within the brown bear species, including the Atlas bear and the
Himalayan brown bear.</p>
<h3>Species</h3>
<ul>
<li>Arctos</li>
<li>Collarus</li>
<li>Horribilis</li>
<li>Nelsoni (extinct)</li>
</ul>
<h3>Features</h3>
<p>Brown bears are not always completely brown. Some can be reddish
or yellowish. They have very large, curved claws and huge paws. Male
brown bears are often 30% larger than female brown bears. They can range
from 5 feet to 9 feet from head to toe.</p>
</div>
31
<div id="habitat">
<h2>Habitat</h2>
<h3>Countries with Large Brown Bear Populations</h3>
<ol>
<li>Russia</li>
<li>United States</li>
<li>Canada</li>
</ol>
<h3>Countries with Small Brown Bear Populations</h3>
<p>Some countries with smaller brown bear populations include
Armenia, Belarus, Bulgaria, China, Finland, France, Greece, India,
Japan, Nepal, Poland, Romania, Slovenia, Turkmenistan, and
Uzbekistan.</p>
</div>
<div id="media">
<h2>Media</h2>
<img src="http://201-bear.jpg"/>
</div>
</body>
2. Add the alt attribute to the image and include a description. Make sure the
description accurately describes the image.
32
HTML Tables
There are many websites on the Internet that display information like stock prices, sports
scores, invoice data, and more. This data is tabular in nature, meaning that a table is often
the best way of presenting the data.
In this part of the module, we’ll learn how to use the HTML <table> element to present
information in a two-dimensional table to the users.
Example
Take a look at the code in the body of index.html. What new code do you see?
<!DOCTYPE html>
<html>
<head>
<title>Ship To It - Company Packing List</title>
</head>
<body>
<ul>
<li>Action List</li>
<li>Profiles</li>
<li>Settings</li>
</ul>
<div>Search the table</div>
<table>
<thead>
<tr>
<th>Company Name</th>
<th>Number of Items to Ship</th>
<th>Next Action</th>
</tr>
</thead>
<tbody>
<tr>
<th>Adam's Greenworks</th>
<td>14</td>
<td>Package Items</td>
</tr>
<tr>
<th>Davie's Burgers</th>
<td>2</td>
33
<td>Send Invoice</td>
</tr>
<tr>
<th>Baker's Bike Shop</th>
<td>3</td>
<td>Send Invoice</td>
</tr>
<tr>
<th>Miss Sally's Southern</th>
<td>4</td>
<td>Ship</td>
</tr>
<tr>
<th>Summit Resort Rentals</th>
<td>4</td>
<td>Ship</td>
</tr>
<tr>
<th>Strike Fitness</th>
<td>1</td>
<td>Enter Order</td>
</tr>
</tbody>
</table>
</body>
</html>
Create a Table
Before displaying data, we must first create the table that will contain the data by using the
<table> element.
<table>
</table>
The <table> element will contain all the tabular data we plan on displaying.
Exercise 2-12
34
<!DOCTYPE html>
<html>
<head>
<title>Ship To It - Company Packing List</title>
</head>
<body>
<ul>
<li>Action List</li>
<li>Profiles</li>
<li>Settings</li>
</ul>
</body>
</html>
Table Rows
In many programs that use tables, the table is already predefined for you, meaning that it
contains the rows, columns, and cells that will hold data. In HTML, all of these components
must be created.
The first step in entering data into the table is to add rows using the table row element:
<tr>.
<table>
<tr>
</tr>
<tr>
</tr>
</table>
In the example above, two rows have been added to the table.
Exercise 2-13
35
<!DOCTYPE html>
<html>
<head>
<title>Ship To It - Company Packing List</title>
</head>
<body>
<ul>
<li>Action List</li>
<li>Profiles</li>
<li>Settings</li>
</ul>
<table>
</table>
</body>
</html>
Table Data
Rows aren’t sufficient to add data to a table. Each cell element must also be defined. In
HTML, you can add data using the table data element: <td>.
<table>
<tr>
<td>1</td>
<td>2</td>
</tr>
</table>
In the example above, two data points (1 and 2) were entered in the one row that exists. By
adding two data points, we created two cells of data.
If the table were displayed in the browser, it would show a table with one row and two
columns.
36
Exercise 2-14
1. In the second row, add three cells of data. The cells should contain the following data,
in order:
John Doe
14
Package Items
<!DOCTYPE html>
<html>
<head>
<title>Ship To It - Company Packing List</title>
</head>
<body>
<ul>
<li>Action List</li>
<li>Profiles</li>
<li>Settings</li>
</ul>
<table>
<tr>
</tr>
<tr>
</tr>
</table>
</body>
</html>
Table Headings
Table data doesn’t make much sense without titles to describe what the data represents.
To add titles to rows and columns, you can use the table heading element: <th>.
The table heading element is used just like a table data element, except with a relevant
title. Just like table data, a table heading must be placed within a table row.
37
<table>
<tr>
<th></th>
<th>Saturday</th>
<th>Sunday</th>
</tr>
<tr>
<th>Temperature</th>
<td>73</td>
<td>81</td>
</tr>
</table>
First, a new row was added to hold the three headings: a blank heading, a Saturday
heading, and a Sunday heading. The blank heading creates the extra table cell necessary to
align the table headings correctly over the data they correspond to.
In the second row, one table heading was added as a row title: Temperature.
Exercise 2-15
1. In the first row, add three table headings. The headings should contain the following
data, in order:
Name
Number of Items to Ship
Next Action
These headings will add meaning to the rest of the data in the table.
38
<!DOCTYPE html>
<html>
<head>
<title>Ship To It - Company Packing List</title>
</head>
<body>
<ul>
<li>Action List</li>
<li>Profiles</li>
<li>Settings</li>
</ul>
<table>
<tr>
</tr>
<tr>
<td>John Doe</td>
<td>14</td>
<td>Package Items</td>
</tr>
</table>
</body>
</html>
Table Borders
So far, the tables you’ve created have been a little difficult to read because they have no
borders.
In older versions of HTML, a border could be added to a tableusing the border attribute
and setting it equal to an integer. This integer would represent the thickness of the border.
39
<table border="1">
<tr>
<td>1</td>
<td>2</td>
</tr>
</table>
The code in the example above is deprecated, so please don’t use it. It’s meant to illustrate
older conventions you may come across when reading other developers’ code.
The browser will likely still interpret your code correctly if you use the border attribute, but
that doesn’t mean the attribute should be used.
Exercise 2-16
1. We’re going to need some more data in the table. Add the following data to the table.
Make sure to place it after the second table row.
40
<tr>
<td>Harry Potter</td>
<td>2</td>
<td>Send Invoice</td>
</tr>
<tr>
<td>Lebron James</td>
<td>3</td>
<td>Send Invoice</td>
</tr>
<tr>
<td>Ben & Ben</td>
<td>4</td>
<td>Ship</td>
</tr>
<tr>
<td>Anne Curtis</td>
<td>4</td>
<td>Ship</td>
</tr>
<tr>
<td>Snow White</td>
<td>1</td>
<td>Enter Order</td>
</tr>
41
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<title>Ship To It - Company Packing List</title>
</head>
<body>
<ul>
<li>Action List</li>
<li>Profiles</li>
<li>Settings</li>
</ul>
<table>
<tr>
<th>Name</th>
<th>Number of Items to Ship</th>
<th>Next Action</th>
</tr>
<tr>
<td>John Doe</td>
<td>14</td>
<td>Package Items</td>
</tr>
</table>
</body>
</html>
Spanning Columns
What if the table contains data that spans multiple columns?
For example, a personal calendar could have events that span across multiple hours, or
even multiple days.
Data can span columns using the colspan attribute. The attribute accepts an integer
(greater than or equal to 1) to denote the number of columns it spans across.
42
<table>
<tr>
<th>Monday</th>
<th>Tuesday</th>
<th>Wednesday</th>
</tr>
<tr>
<td colspan="2">Out of Town</td>
<td>Back in Town</td>
</tr>
</table>
In the example above, the data Out of Town spans the Monday and Tuesday table
headings using the value 2 (two columns). The data Back in Town appears only under
the Wednesday heading.
Exercise 2-17
<!DOCTYPE html>
<html>
<head>
<title>Ship To It - Company Packing List</title>
</head>
<body>
<ul>
<li>Action List</li>
<li>Profiles</li>
<li>Settings</li>
</ul>
<table>
<tr>
<th>Name</th>
<th>Number of Items to Ship</th>
<th>Next Action</th>
</tr>
<tr>
<td>John Doe</td>
<td>14</td>
43
<td>Package Items</td>
</tr>
<tr>
<td>Harry Potter</td>
<td>2</td>
<td>Send Invoice</td>
</tr>
<tr>
<td>Lebron James</td>
<td>3</td>
<td>Send Invoice</td>
</tr>
<tr>
<td>Ben & Ben</td>
<td>4</td>
<td>Ship</td>
</tr>
<tr>
<td>Anne Curtis</td>
<td>4</td>
<td>Ship</td>
</tr>
<tr>
<td>Snow White</td>
<td>1</td>
<td>Enter Order</td>
</tr>
</table>
</body>
</html>
2. The formatting doesn’t look so good. Feel free to delete the colspan attribute and
value from the <td> element you added them to.
Spanning Rows
Data can also span multiple rows using the rowspan attribute.
The rowspan attribute is used for data that spans multiple rows (perhaps an event goes on
for multiple hours on a certain day). It accepts an integer (greater than or equal to 1) to
denote the number of rows it spans across.
44
<table>
<tr> <!-- Row 1 -->
<th></th>
<th>Saturday</th>
<th>Sunday</th>
</tr>
<tr> <!-- Row 2 -->
<th>Morning</th>
<td rowspan="2">Work</td>
<td rowspan="3">Relax</td>
</tr>
<tr> <!-- Row 3 -->
<th>Afternoon</th>
</tr>
<tr> <!-- Row 4 -->
<th>Evening</th>
<td>Dinner</td>
</tr>
</table>
1. The first row contains an empty cell and the two column headings.
2. The second row contains the Morning row heading, along with Work, which spans
two rows under the Saturday column. The “Relax” entry spans three rows under the
Sunday column.
3. The third row only contains the Afternoon row heading.
4. The fourth row only contains the Dinner entry, since “Relax” spans into the cell next
to it.
Exercise 2-18
<!DOCTYPE html>
<html>
<head>
<title>Ship To It - Company Packing List</title>
</head>
<body>
<ul>
<li>Action List</li>
<li>Profiles</li>
45
<li>Settings</li>
</ul>
<table>
<tr>
<th>Name</th>
<th>Number of Items to Ship</th>
<th>Next Action</th>
</tr>
<tr>
<td>John Doe</td>
<td>14</td>
<td>Package Items</td>
</tr>
<tr>
<td>Harry Potter</td>
<td>2</td>
<td>Send Invoice</td>
</tr>
<tr>
<td>Lebron James</td>
<td>3</td>
<td>Send Invoice</td>
</tr>
<tr>
<td>Ben & Ben</td>
<td>4</td>
<td>Ship</td>
</tr>
<tr>
<td>Anne Curtis</td>
<td>4</td>
<td>Ship</td>
</tr>
<tr>
<td>Snow White</td>
<td>1</td>
<td>Enter Order</td>
</tr>
</table>
</body>
</html>
46
2. The formatting doesn’t look so good. Feel free to delete the rowspan attribute and
value from the <td> element you added them to.
Table Body
Over time, a table can grow to contain a lot of data and become very long. When this
happens, the table can be sectioned off so that it is easier to manage.
Long tables can be sectioned off using the table body element: <tbody>.
The <tbody> element should contain all the table’s data, excluding the table headings
(more on this in a later exercise).
<table>
<tbody>
<tr>
<th></th>
<th>Saturday</th>
<th>Sunday</th>
</tr>
<tr>
<th>Morning</th>
<td rowspan="2">Work</td>
<td rowspan="3">Relax</td>
</tr>
<tr>
<th>Afternoon</th>
</tr>
<tr>
<th>Evening</th>
<td>Dinner</td>
</tr>
</tbody>
</table>
In the example above, all the table data is contained within a table body element. Note,
however, that the headings were also kept in the table’s body — we’ll change this in the
next exercise.
Exercise 2-19
47
<!DOCTYPE html>
<html>
<head>
<title>Ship To It - Company Packing List</title>
</head>
<body>
<ul>
<li>Action List</li>
<li>Profiles</li>
<li>Settings</li>
</ul>
<table>
<tr>
<th>Name</th>
<th>Number of Items to Ship</th>
<th>Next Action</th>
</tr>
<tr>
<td>John Doe</td>
<td>14</td>
<td>Package Items</td>
</tr>
<tr>
<td>Harry Potter</td>
<td>2</td>
<td>Send Invoice</td>
</tr>
<tr>
<td>Lebron James</td>
<td>3</td>
<td>Send Invoice</td>
</tr>
<tr>
<td>Ben & Ben</td>
<td>4</td>
<td>Ship</td>
</tr>
<tr>
<td>Anne Curtis</td>
<td>4</td>
<td>Ship</td>
48
</tr>
<tr>
<td>Snow White</td>
<td>1</td>
<td>Enter Order</td>
</tr>
</table>
</body>
</html>
Table Head
In the last exercise, the table’s headings were kept inside the table’s body. When a table’s
body is sectioned off, however, it also makes sense to section off the table’s column
headings using the <thead> element.
<table>
<thead>
<tr>
<th></th>
<th scope="col">Saturday</th>
<th scope="col">Sunday</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">Morning</th>
<td rowspan="2">Work</td>
<td rowspan="3">Relax</td>
</tr>
<tr>
<th scope="row">Afternoon</th>
</tr>
<tr>
<th scope="row">Evening</th>
<td>Dinner</td>
</tr>
</tbody>
</table>
In the example above, the only new element is <thead>. The table headings are contained
49
inside of this element. Note that the table’s head still requires a row in order to contain the
table headings.
Additionally, only the column headings go under the <thead> element. We can use the
scope attribute on <th> elements to indicate whether a <th> element is being used as a
row heading or a col heading.
Exercise 2-20
<!DOCTYPE html>
<html>
<head>
<title>Ship To It - Company Packing List</title>
</head>
<body>
<ul>
<li>Action List</li>
<li>Profiles</li>
<li>Settings</li>
</ul>
<table>
<tr>
<th>Name</th>
<th>Number of Items to Ship</th>
<th>Next Action</th>
</tr>
<tbody>
<tr>
<td>John Doe</td>
<td>14</td>
<td>Package Items</td>
</tr>
<tr>
<td>Harry Potter</td>
<td>2</td>
<td>Send Invoice</td>
</tr>
<tr>
<td>Lebron James</td>
<td>3</td>
50
<td>Send Invoice</td>
</tr>
<tr>
<td>Ben & Ben</td>
<td>4</td>
<td>Ship</td>
</tr>
<tr>
<td>Anne Curtis</td>
<td>4</td>
<td>Ship</td>
</tr>
<tr>
<td>Snow White</td>
<td>1</td>
<td>Enter Order</td>
</tr>
</tbody>
</table>
</body>
</html>
Table Footer
The bottom part of a long table can also be sectioned off using the <tfoot> element.
51
<table>
<thead>
<tr>
<th>Quarter</th>
<th>Revenue</th>
<th>Costs</th>
</tr>
</thead>
<tbody>
<tr>
<th>Q1</th>
<td>$10M</td>
<td>$7.5M</td>
</tr>
<tr>
<th>Q2</th>
<td>$12M</td>
<td>$5M</td>
</tr>
</tbody>
<tfoot>
<tr>
<th>Total</th>
<td>$22M</td>
<td>$12.5M</td>
</tr>
</tfoot>
</table>
In the example above, the footer contains the totals of the data in the table. Footers are
often used to contain sums, differences, and other data results.
Exercise 2-21
1. Add a table footer at the bottom of the table using the <tfoot> element. Inside the
footer, add the following data:
<td>Total</td>
<td>28</td>
<!DOCTYPE html>
52
<html>
<head>
<title>Ship To It - Company Packing List</title>
</head>
<body>
<ul>
<li>Action List</li>
<li>Profiles</li>
<li>Settings</li>
</ul>
<table>
<thead>
<tr>
<th>Name</th>
<th>Number of Items to Ship</th>
<th>Next Action</th>
</tr>
</thead>
<tbody>
<tr>
<td>John Doe</td>
<td>14</td>
<td>Package Items</td>
</tr>
<tr>
<td>Harry Potter</td>
<td>2</td>
<td>Send Invoice</td>
</tr>
<tr>
<td>Lebron James</td>
<td>3</td>
<td>Send Invoice</td>
</tr>
<tr>
<td>Ben & Ben</td>
<td>4</td>
<td>Ship</td>
</tr>
<tr>
<td>Anne Curtis</td>
<td>4</td>
53
<td>Ship</td>
</tr>
<tr>
<td>Snow White</td>
<td>1</td>
<td>Enter Order</td>
</tr>
</tbody>
</table>
</body>
</html>
54
HTML Forms
Forms are a part of everyday life. When we use a physical form in real life, we write down
information and give it to someone to process. Think of the times you’ve had to fill out
information for various applications like a job, or a bank account, or dropped off a completed
suggestion card — each instance is a form!
Just like a physical form, an HTML <form> element is responsible for collecting information
to send somewhere else. Every time we browse the internet we come into contact with
many forms, and we might not even realize it. There’s a good chance that if you’re typing
into a text field or providing an input, the field that you’re typing into is part of a <form>!
In this module, we’ll go over the structure and syntax of a <form> and the many elements
that populate it.
The <form> element is a great tool for collecting information, but then we need to send that
information somewhere else for processing. We need to supply the <form> element with
both the location of where the <form>‘s information goes and what HTTP request to make.
Take a look at the sample <form> below:
In the above example, we’ve created the skeleton for a <form> that will send information to
example.html as a POST request:
Note: HTTP verbs like POST do not need to be capitalized for the request to work, but it’s
done so out of convention. In the example above we could have written method="post"
and it would still work.
The <form> element can also contain child elements. For instance, it would be helpful to
provide a header so that users know what this <form> is about. We could also add a
55
paragraph to provide even more detail. Let’s see an example of this in code:
The example above doesn’t collect any user input, but we’ll do that in the next exercise. For
now, let’s practice making the foundation of an HTML <form>!
Exercise 2-22
1. In the <section> element, add a <form> element under the provided comment.
Assign the <form> with:
an action attribute with a value of /practice.html
a method attribute with a value of POST
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>HTML Forms</title>
</head>
<body>
<section id="overlay">
<!--Add your code below-->
</section>
</body>
</html>
2. Right now we have a blank <form> on a burger site, let’s add some context.
Add an <h1> inside the <form> element with text related to the site between
the opening and closing <h1> tags.
3. Add some details to the form by inserting a <p> element below the <h1> element.
Write a relevant description within the <p> element.
Text Input
If we want to create an input field in our <form>, we’ll need the help of the <input>
element.
56
The <input> element has a type attribute which determines how it renders on the web
page and what kind of data it can accept.
The first value for the type attribute we’re going to explore is "text". When we create an
<input> element with type="text", it renders a text field that users can type into. Note
that the default value of type is "text". It’s also important that we include a name attribute
for the <input> — without the name attribute, information in the <input> won’t be sent
when the <form> is submitted. Let’s examine the following code that produces a text input
field:
When initially loaded, it will be an empty box. After users type into the <input> element,
the value of the value attribute becomes what is typed into the text field. The value of the
value attribute is paired with the value of the name attribute and sent as text when the form
is submitted. For instance, if a user typed in “important details” in the text field created
by our <input> element. When the form is submitted, the text: "first-text-
field=important details" is sent to /example.html because the value of the name
attribute is "first-text-field" and the value of value is "important details".
We could also assign a default value for the value attribute so that users have a pre-filled
text field when they first see the rendered form like so:
Exercise 2-23
1. Let’s start with creating a login form for our users. Inside the provided <form>
element, add an <input> element with a type attribute of "text".
57
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>HTML Forms</title>
</head>
<body>
<section id="overlay">
<form>
<h1>Login to start creating a burger!</h1>
<!--Add your code below-->
</form>
</section>
</body>
</html>
2. Even though we’re not submitting the form, let’s develop some good habits by giving
the <input> a name attribute with a value of "username".
3. Let’s see what happens if we add a value attribute with a value of "John"
Adding a Label
In the previous exercise we created an <input> element, but we didn’t include anything to
explain what the <input> is used for. For a user to properly identify an <input> we use
the appropriately named <label> element.
The <label> element has an opening and closing tag and displays text that is written
between the opening and closing tags. To associate a <label> and an <input>, the
<input> needs an id attribute. We then assign the for attribute of the <label> element
with the value of the id attribute of <input>, like so:
58
<form action="/example.html" method="POST">
<label for="meal">What do you want to eat?</label>
<br>
<input type="text" name="food" id="meal">
</form>
Look, now users know what the <input> element is for! Another benefit for using the
<label> element is when this element is clicked, the corresponding <input> is
highlighted/selected.
Exercise 2-24
1. Add a <label> element that is associated with the included <input> element in
index.html. (use the for attribute!) Then add text Username within the <label>
element. After clearing this checkpoint, click on the Username label in the web
browser to see the corresponding <input> field selected.
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Labels</title>
</head>
<body>
<section>
<form>
<h1>Login to start creating a burger!</h1>
<!--Add your code below-->
<input type="text" name="username" id="username">
</form>
</section>
</body>
</html>
Password Input
Think about all those times we have to put sensitive information, like a password or PIN, into
a <form>. We wouldn’t want our information to be seen by anyone peeking over our
shoulder! Luckily, we have the type="password" attribute for <input>!
An <input type ="password"> element will replace input text with another character
59
like an asterisk (*) or a dot (•). The code below provides an example of how to create a
password field:
<form>
<label for="user-password">Password: </label>
<input type="password" id="user-password" name="user-password">
</form>
Even though the password field obscures the text of the password, when the form is
submitted, the value of the text is sent. In other words, if “hunter2” is typed into the
password field, “user-password=hunter2” is sent along with the other information on the
form.
Exercise 2-25
1. To complete our login page in index.html we need a password field. Add an <input>
element under the second <label> element.
Assign the id to the correct value to associate the second <label> with this
new <input>.
Set the newly created <input> element’s type attribute to "password".
Set the name attribute to "user-pw".
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Password Input</title>
</head>
<body>
<section id="overlay">
<form>
<h1>Login to start creating a burger!</h1>
<label for="username">Username:</label>
<input type="text" name="username" id="username">
<br>
<label for="user-pw">Password:</label>
<!--Add your code below-->
</form>
</section>
</body>
</html>
60
Number Input
We’ve now gone over two type attributes for <input> related to text. But, we might want
our users to type in a number — in which case we can set the type attribute to "number"!
By setting type="number" for an <input> we can restrict what users type into the input
field to just numbers (and a few special characters like -, +, and .). We can also provide a
step attribute which creates arrows inside the input field to increase or decrease by the
value of the step attribute. Below is the code needed to render an input field for numbers:
<form>
<label for="years"> Years of experience: </label>
<input id="years" name="years" type="number" step="1">
</form>
Exercise 2-26
1. In index.html we started a <form> for users to make a custom burger. Right now we
have a <label> for patties that needs an associated <input> element. Since we
want users to enter a number, create an <input> and set the attributes:
Associate the <input> to the first <label> by assigning the correct value to id.
type="number"
step="1"
name to "amount".
61
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Range Input</title>
</head>
<body>
<section id="overlay">
<form>
<h1>Create a burger!</h1>
<section class="protein">
<label for="patty">What type of protein would you
like?</label>
<input type="text" name="patty" id="patty" value="beef">
</section>
<hr>
<section class="patties">
<label for="amount">How many patties would you like?</label>
<!--Add your code below-->
</section>
</form>
</section>
</body>
</html>
Range Input
Using an <input type="number"> is great if we want to allow users to type in any
number of their choosing. But, if we wanted to limit what numbers our users could type we
might consider using a different type value. Another option we could use is setting type to
range which creates a slider.
To set the minimum and maximum values of the slider we assign values to the min and max
attribute of the <input>. We could also control how smooth and fluid the slider works by
assigning the step attribute a value. Smaller step values will make the slider move more
fluidly, whereas larger step values will make the slider move more noticeably. Take a look at
the code to create a slider:
62
<form>
<label for="volume"> Volume Control</label>
<input id="volume" name="volume" type="range" min="0" max="100"
step="1">
</form>
In the example above, every time the slider moves by one, the value of the <input>‘s value
attribute changes.
Exercise 2-27
1. Let’s give our users an option for how they want to cook their patties. We can do this
by adding a slider to the existing <form>. In the <section> with class="cooked",
add an <input> element. Set the id and name to doneness. Also, set the type
attribute to range. Since our <form> is getting long, you might have to scroll down to
find the provided <section>.
63
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Range Input</title>
</head>
<body>
<section id="overlay">
<form>
<h1>Create a burger!</h1>
<section class="protein">
<label for="patty">What type of protein would you
like?</label>
<input type="text" name="patty" id="patty">
</section>
<hr>
<section class="patties">
<label for="amount">How many patties would you like?</label>
<input type="number" name="amount" id="amount">
</section>
<hr>
<section class="cooked">
<label for="doneness">How do you want your patty
cooked</label>
<br>
<span>Rare</span>
<!--Add your code below-->
<span>Well-Done</span>
</section>
</form>
</section>
</body>
</html>
Checkbox Input
So far the types of inputs we’ve allowed were all single choices. But, what if we presented
64
multiple options to users and allowed them to select any number of options? Sounds like we
could use checkboxes! In a <form> we would use the <input> element and set
type="checkbox". Examine the code used to create multiple checkboxes:
<form>
<p>Choose your pizza toppings:</p>
<label for="cheese">Extra cheese</label>
<input id="cheese" name="topping" type="checkbox" value="cheese">
<br>
<label for="pepperoni">Pepperoni</label>
<input id="pepperoni" name="topping" type="checkbox"
value="pepperoni">
<br>
<label for="anchovy">Anchovy</label>
<input id="anchovy" name="topping" type="checkbox" value="anchovy">
</form>
there are assigned values to the value attribute of the checkboxes. These values are
not visible on the form itself, that’s why it is important that we use an associated
<label> to identify the checkbox.
each <input> has the same value for the name attribute. Using the same name for
each checkbox groups the <input>s together. However, each <input> has a unique
id to pair with a <label>.
Exercise 2-28
1. Time to add some toppings! In the <section> with class="toppings", there are
two <label>s but no associated <input> elements. Add an <input> element
associated with the first <label>. The created <input> should have:
an id set to lettuce.
a name attribute with a value of topping.
a type set to checkbox
a value of lettuce.
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Checkbox Input</title>
</head>
<body>
<section id="overlay">
65
<form>
<h1>Create a burger!</h1>
<section class="protein">
<label for="patty">What type of protein would you
like?</label>
<input type="text" name="patty" id="patty">
</section>
<hr>
<section class="patties">
<label for="amount">How many patties would you like?</label>
<input type="number" name="amount" id="amount">
</section>
<hr>
<section class="cooked">
<label for="doneness">How do you want your patty
cooked</label>
<br>
<span>Rare</span>
<input type="range" name="doneness" id="doneness" value="3"
min="1" max="5">
<span>Well-Done</span>
</section>
<hr>
<section class="toppings">
<span>What toppings would you like?</span>
<br>
<!--Add your code below for the first checkbox-->
<label for="lettuce">Lettuce</label>
<!--Add your code below for the second checkbox-->
<label for="tomato">Tomato</label>
<!--Add your code below for the third checkbox-->
</section>
</form>
</section>
</body>
</html>
2. Add another <input> element and associate it with the second <label>. The
<input> element should have:
an id set to tomato.
66
a type set to checkbox.
a name attribute with a value of topping.
a value of tomato.
3. Two choices are good, but it would be better to have even more. Add another <input
type="checkbox"> and <label> pair. Assign the name of the <input> to
topping. You’re free to decide the value and id but make sure that your new
<label> and <input> are associated.
<form>
<p>What is sum of 1 + 1?</p>
<input type="radio" id="two" name="answer" value="2">
<label for="two">2</label>
<br>
<input type="radio" id="eleven" name="answer" value="11">
<label for="eleven">11</label>
</form>
Notice from the code snippet, radio buttons (like checkboxes) do not display their value. We
have an associated <label> to represent the value of the radio button. To group radio
buttons together, we assign them the same name and only one radio button from that group
can be selected.
Exercise 2-29
1. We can give our users the option to make the burger into a cheeseburger. Let’s use
radio buttons for that. In <section> element with a class of cheesy there are two
<label>s that don’t have associated <input> elements. Add an <input> element
associated with the first <label>.
an id set to yes.
67
a type set to radio.
a name attribute with a value of cheese.
a value of yes.
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Radio Input</title>
</head>
<body>
<section id="overlay">
<form>
<h1>Create a burger!</h1>
<section class="protein">
<label for="patty">What type of protein would you
like?</label>
<input type="text" name="patty" id="patty">
</section>
<hr>
<section class="patties">
<label for="amount">How many patties would you like?</label>
<input type="number" name="amount" id="amount">
</section>
<hr>
<section class="cooked">
<label for="doneness">How do you want your patty
cooked</label>
<br>
<span>Rare</span>
<input type="range" name="doneness" id="doneness" value="3"
min="1" max="5">
<span>Well-Done</span>
</section>
<hr>
<section class="toppings">
<span>What toppings would you like?</span>
<br>
<input type="checkbox" name="topping" id="lettuce"
value="lettuce">
<label for="lettuce">Lettuce</label>
<input type="checkbox" name="topping" id="tomato"
value="tomato">
<label for="tomato">Tomato</label>
<input type="checkbox" name="topping" id="onion"
68
value="onion">
<label for="onion">Onion</label>
</section>
<hr>
<section class="cheesy">
<span>Would you like to add cheese?</span>
<br>
<!--Add your first radio button below-->
<label for="yes">Yes</label>
<!--Add your second radio button below-->
<label for="no">No</label>
</section>
</form>
</section>
</body>
</html>
2. Awesome, now add another <input> element to give users another choice. The
created <input> should have:
an id set to no.
a type set to radio.
a name attribute with a value of cheese.
a value of no.
Dropdown list
Radio buttons are great if we want our users to pick one option out of a few visible options,
but imagine if we have a whole list of options! This situation could quickly lead to a lot of
radio buttons to keep track of.
An alternative solution is to use a dropdown list to allow our users to choose one option from
an organized list. Here’s the code to create a dropdown menu:
69
<form>
<label for="lunch">What's for lunch?</label>
<select id="lunch" name="lunch">
<option value="pizza">Pizza</option>
<option value="curry">Curry</option>
<option value="salad">Salad</option>
<option value="ramen">Ramen</option>
<option value="tacos">Tacos</option>
</select>
</form>
Notice in the code that we’re using the element <select> to create the dropdown list. To
populate the dropdown list, we add multiple <option> elements, each with a value
attribute. By default, only one of these options can be selected.
The text rendered is the text included between the opening and closing <option> tags.
However, it is the value of the value attribute that is used in <form> submission (notice
the difference in the text and value capitalization). When the <form> is submitted, the
information from this input field will be sent using the name of the <select> and the value
of the chosen <option>. For instance, if a user selected Pizza from the dropdown list, the
information would be sent as lunch=pizza.
Exercise 2-30
1. Let’s now give our users a choice of buns using a dropdown list. In <section>
element with a class of bun-type there is a <label> that we can associate a
<select> element with. Add a <select> element with a name of bun and an id of
bun.
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Dropdown List</title>
</head>
<body>
<section id="overlay">
<form>
<h1>Create a burger!</h1>
<section class="protein">
<label for="patty">What type of protein would you
like?</label>
<input type="text" name="patty" id="patty">
</section>
70
<hr>
<section class="patties">
<label for="amount">How many patties would you like?</label>
<input type="number" name="amount" id="amount">
</section>
<hr>
<section class="cooked">
<label for="doneness">How do you want your patty
cooked</label>
<br>
<span>Rare</span>
<input type="range" name="doneness" id="doneness" value="3"
min="1" max="5">
<span>Well-Done</span>
</section>
<hr>
<section class="toppings">
<span>What toppings would you like?</span>
<br>
<input type="checkbox" name="topping" id="lettuce"
value="lettuce">
<label for="lettuce">Lettuce</label>
<input type="checkbox" name="topping" id="tomato"
value="tomato">
<label for="tomato">Tomato</label>
<input type="checkbox" name="topping" id="onion"
value="onion">
<label for="onion">Onion</label>
</section>
<hr>
<section class="cheesy">
<span>Would you like to add cheese?</span>
<br>
<input type="radio" name="cheese" id="yes" value="yes">
<label for="yes">Yes</label>
<input type="radio" name="cheese" id="no" value="no">
<label for="no">No</label>
</section>
<hr>
<section class="bun-type">
<label for="bun">What type of bun would you like?</label>
<!--Add your code below-->
</section>
</form>
</section>
71
</body>
</html>
72
Module 3 - Introduction to CSS
(Cascading Style Sheets)
While HTML is the fundamental structure of every web page, it can be visually unappealing
on its own. Cascading Style Sheets or CSS is a language web developers use to style the
HTML content on a web page. If you’re interested in modifying colors, font, types, font sizes,
images, element positioning, and more, CSS is the tool for the job!
73
CSS Anatomy
The diagram on the right shows two different methods, or syntaxes, for writing CSS code.
The first syntax shows CSS applied as a ruleset, while the second shows it written as an
inline style. Two different methods of writing CSS may seem a bit intimidating at first, but
it’s not as bad as it looks!
Both methods contain common features in their anatomy. Notice how both syntaxes contain
a declaration. Declarations are the core of CSS. They apply a style to the selected element.
Here, the <p> element has been selected in both syntaxes and will be styled to display the
text in blue.
Understanding that a declaration is used to style a selected element is key to learning how
to style HTML documents with CSS! The terms below explain each of the labels in the
diagram on the right.
Ruleset Terms:
Selector — The beginning of the ruleset used to target the element that will be
styled.
Declaration Block — The code in-between (and including) the curly braces ({ })
that contains the CSS declaration(s).
Declaration — The group name for a property and value pair that applies a style to
the selected element.
Property — The first part of the declaration that signifies what visual characteristic of
the element is to be modified.
Value — The second part of the declaration that signifies the value of the property.
Opening Tag — The start of an HTML element. This is the element that will be styled.
Attribute — The style attribute is used to add CSS inline styles to an HTML element.
Declaration — The group name for a property and value pair that applies a style to
the selected element.
Property — The first part of the declaration that signifies what visual characteristic of
the element is to be modified.
Value — The second part of the declaration that signifies the value of the property.
74
Figure 3-1: CSS Anatomy
Don’t worry about memorizing all of these—you will get acquainted with them more and
more as the module progresses! Feel free to come back and use this exercise as a reference
later on.
75
Inline Styles
Although CSS is a different language than HTML, it’s possible to write CSS code directly
within HTML code using inline styles.
To style an HTML element, you can add the style attribute directly to the opening tag.
After you add the attribute, you can set it equal to the CSS style(s) you’d like applied to that
element.
The code in the example above demonstrates how to use inline styling. The paragraph
element has a style attribute within its opening tag. Next, the style attribute is set equal
to color: red;, which will set the color of the paragraph text to red within the browser.
If you’d like to add more than one style with inline styles, simply keep adding to the style
attribute. Make sure to end the styles with a semicolon (;).
It’s important to know that inline styles are a quick way of directly styling an HTML element,
but are rarely used when creating websites. But you may encounter circumstances where
inline styling is necessary, so understanding how it works, and recognizing it in HTML code is
good knowledge to have. Soon you’ll learn the proper way to add CSS code!
Exercise 3-1
1. In index.html, use inline styling to set the color of the first paragraph (the first
<p> element) to green.
<!DOCTYPE html>
<html>
<head>
<title>Vacation World</title>
</head>
<body>
76
<h1 class='title'>Top Vacation Spots</h1>
<h5>By: Stacy Gray</h5>
<h6>Published: 2 Days Ago</h6>
77
Fourteenth-century city gates squat in the shadow of 21st-century
skyscrapers, while the broad Han River is back-dropped by granite
mountains rising in the city center complete with alpine highways
speeding around their contours and temples nestling among their crags.
Fashionable, gadget-laden youths battle for sidewalk space with fortune-
tellers and peddlers, while tiny neighborhoods of traditional cottages
contrast with endless ranks of identical apartments.
<a
href='https://www.nationalgeographic.com/travel/destination/seoul'
target='_blank'>Learn More</a>.
<h5>Top Attractions</h5>
<ul>
<li>Parasailing</li>
<li>Segway Tours</li>
<li>Spas and Resorts</li>
</ul>
</div>
78
Internal Stylesheet (Embedded Stylesheet)
As previously stated, inline styles are not the best way to style HTML elements. If you
wanted to style, for example, multiple <h1> elements, you would have to add inline styling
to each element manually. In addition, you would also have to maintain the HTML code when
additional <h1> elements are added.
Fortunately, HTML allows you to write CSS code in its own dedicated section with a <style>
element nested inside the <head> element. The CSS code inside the <style> element is
often referred to as an internal stylesheet.
An internal stylesheet has certain benefits and use cases over inlines styles, but once again,
it’s not best practice (we’ll get there, we promise). Understanding how to use internal
stylesheets is nonetheless helpful knowledge to have.
To create an internal stylesheet, a <style> element must be placed inside the <head>
element.
<head>
<style>
</style>
</head>
After adding opening and closing <style> tags in the head section, you can begin writing
CSS code.
<head>
<style>
p {
color: red;
font-size: 20px;
}
</style>
</head>
The CSS code in the example above changes the color of all paragraph text to red and also
changes the size of the text to 20 pixels. Note how the syntax of the CSS code matches (for
the most part) the syntax you used for inline styling. The main difference is that you can
79
specify which elements to apply the styling.
Exercise 3-2
1. Let’s move the inline style that was added to the paragraph into an internal
stylesheet. Start by adding an empty <style> element in the head of index.html.`
<!DOCTYPE html>
<html>
<head>
<title>Vacation World</title>
</head>
<body>
<h1 class='title'>Top Vacation Spots</h1>
<h5>By: Stacy Gray</h5>
<h6>Published: 2 Days Ago</h6>
80
of the Peoples Republic of China remains an epicenter of tradition, with
the treasures of nearly 2,000 years as the imperial capital still on
view in the famed Forbidden City and in the luxuriant pavilions and
gardens of the Summer Palace.
<a
href='https://www.nationalgeographic.com/travel/destination/beijing'
target='_blank'>Learn More</a>.
<h5>Top Attractions</h5>
<ul>
<li>Biking</li>
<li>Historical Sites</li>
<li>Restaurants and Dining</li>
</ul>
</div>
</body>
81
</html>
2. Inside the <style> element, add a CSS ruleset targeting the paragraph (the <p>
element). You can leave the declaration block empty for now.
3. Next, place just the declaration from the inline style into the empty declaration block
in the inline stylesheet.
4. Finally, delete the inline style from the <p> element. Notice how the styling works the
same in the stylesheet as it did in the inline style!
82
External Stylesheet
Developers avoid mixing code by storing HTML and CSS code in separate files (HTML files
contain only HTML code, and CSS files contain only CSS code).
You can create an external stylesheet by using the .css file name extension, like so:
style.css
With an external stylesheet, you can write all the CSS code needed to style a page without
sacrificing the readability and maintainability of your HTML file.
You can use the <link> element to link HTML and CSS files together. The <link> element
must be placed within the head of the HTML file. It is a self-closing tag and requires the
following attributes:
1. href — like the anchor element, the value of this attribute must be the address, or
path, to the CSS file.
2. rel — this attribute describes the relationship between the HTML file and the CSS file.
Because you are linking to a stylesheet, the value should be set to stylesheet.
When linking an HTML file and a CSS file together, the <link> element will look like the
following:
<link href='https://www.example.com/stylesheets/style.css'
rel='stylesheet'>
Note that in the example above, the path to the stylesheet is a URL:
https://www.example.com/stylesheets/style.css
Specifying the path to the stylesheet using a URL is one way of linking a stylesheet.
If the CSS file is stored in the same directory as your HTML file, then you can specify a
relative path instead of a URL, like so:
83
<link href='./style.css' rel='stylesheet'>
84
Selectors
Type
Remember that declarations are a fundamental part of CSS because they apply a style to a
selected element. But how do you decide which elements will get the style? With a
selector.
A selector is used to target the specific HTML element(s) to be styled by the declaration. One
selector you may already be familiar with is the type selector. Just like its name suggests,
the type selector matches the type of the element in the HTML document.
p {
color: green;
}
This is an instance of using the type selector! The element type is p, which comes from the
HTML <p> element.
Universal
You learned how the type selector selects all elements of a given type. Well, the universal
selector selects all elements of any type.
Targeting all the elements on the page has a few specific use cases, such as resetting
default browser styling or selecting all children of a parent element. Don’t worry if you
don’t understand the use cases right now; we will get to them later on in our Learn CSS
journey.
The universal selector uses the * character in the same place where you specified the type
selector in a ruleset, like so:
85
* {
font-family: Verdana;
}
In the code above, every text element on the page will have its font changed to Verdana.
Class
CSS is not limited to selecting elements by their type. As you know, HTML elements can also
have attributes. When working with HTML and CSS a class attribute is one of the most
common ways to select an element.
The paragraph element in the example above has a class attribute within the opening tag
of the <p> element. The class attribute is set to brand. To select this element using CSS,
we can create a ruleset with a class selector of .brand.
.brand {
To select an HTML element by its class using CSS, a period (.) must be prepended to the
class’s name. In the example above, the class is brand, so the CSS selector for it is .brand.
Multiple Classes
We can use CSS to select an HTML element’s class attribute by name. And so far, we’ve
selected elements using only one class name per element. If every HTML element had a
single class, all the style information for each element would require a new class.
Luckily, it’s possible to add more than one class name to an HTML element’s class
attribute.
For instance, perhaps there’s a heading element that needs to be green and bold. You could
write two CSS rulesets like so:
86
.green {
color: green;
}
.bold {
font-weight: bold;
}
Then, you could include both of these classes on one HTML element like this:
We can add multiple classes to an HTML element’s class attribute by separating them with
a space. This enables us to mix and match CSS classes to create many unique styles without
writing a custom class for every style combination needed.
ID
Oftentimes it’s important to select a single element with CSS to give it its own unique style.
If an HTML element needs to be styled uniquely, we can give it an ID using the id attribute.
In contrast to class which accepts multiple values, and can be used broadly throughout an
HTML document, an element’s id can only have a single value, and only be used once per
page.
To select an element’s ID with CSS, we prepend the id name with a number sign (#). For
instance, if we wanted to select the HTML element in the example above, it would look like
this:
#large-title {
87
Attribute
You may remember that some HTML elements use attributes to add extra detail or
functionality to the element. Some familiar attributes may be href and src, but there are
many more—including class and id!
The attribute selector can be used to target HTML elements that already contain attributes.
Elements of the same type can be targeted differently by their attribute or attribute value.
This alleviates the need to add new code, like the class or id attributes.
[href]{
color: magenta;
}
The most basic syntax is an attribute surrounded by square brackets. In the above example:
[href] would target all elements with an href attribute and set the color to magenta.
And it can get more granular from there by adding type and/or attribute values. One way
is by using type[attribute*=value]. In short, this code selects an element where the
attribute contains any instance of the specified value. Let’s take a look at an example.
<img src='/images/seasons/cold/winter.jpg'>
<img src='/images/seasons/warm/summer.jpg'>
The HTML code above renders two <img> elements, each containing a src attribute with a
value equaling a link to an image file.
img[src*='winter'] {
height: 50px;
}
img[src*='summer'] {
height: 100px;
}
Now take a look at the above CSS code. The attribute selector is used to target each image
individually.
88
The first ruleset looks for an img element with an attribute of src that contains the
string winter, and sets the height to 50px.
The second ruleset looks for an img element with an attribute of src that contains the
string summer, and sets the height to 100px.
Notice how no new HTML markup (like a class or id) needed to be added, and we were still
able to modify the styles of each image independently. This is one advantage to using the
attribute selector!
Pseudo-class
You may have observed how the appearance of certain elements can change, or be in a
different state, after certain user interactions. For instance:
When you click on an <input> element, and a blue border is added showing that it is
in focus.
When you click on a blue <a> link to visit to another page, but when you return the
link’s text is purple.
When you’re filling out a form and the submit button is grayed out and disabled. But
when all the fields have been filled out, the button has color showing that it’s active.
These are all examples of pseudo-class selectors in action! In fact, :focus, :visited,
:disabled, and :active are all pseudo-classes. Factors such as user interaction, site
navigation, and position in the document tree can all give elements a different state with
pseudo-class.
p:hover {
background-color: lime;
}
In the above code, whenever the mouse hovers over a paragraph element, that paragraph
will have a lime-colored background.
CSS classes are meant to be reused over many elements. By writing CSS classes, you can
89
style elements in a variety of ways by mixing classes. For instance, imagine a page with two
headlines. One headline needs to be bold and blue, and the other needs to be bold and
green. Instead of writing separate CSS rules for each headline that repeat each other’s code,
it’s better to write a .bold CSS rule, a .green CSS rule, and a .blue CSS rule. Then you
can give one headline the bold green classes, and the other the bold blue classes.
While classes are meant to be used many times, an ID is meant to style only one element.
As you’ll learn in the next exercise, IDs override the styles of types and classes. Since IDs
override these styles, they should be used sparingly and only on elements that need to
always appear the same.
Specificity
Specificity is the order by which the browser decides which CSS styles will be displayed. A
best practice in CSS is to style elements while using the lowest degree of specificity so that
if an element needs a new style, it is easy to override.
IDs are the most specific selector in CSS, followed by classes, and finally, type. For example,
consider the following HTML and CSS:
h1 {
color: red;
}
.headline {
color: firebrick;
}
In the example code above, the color of the heading would be set to firebrick, as the
class selector is more specific than the type selector. If an ID attribute (and selector) were
added to the code above, the styles within the ID selector’s body would override all other
styles for the heading.
Over time, as files grow with code, many elements may have IDs, which can make CSS
difficult to edit since a new, more specific style must be created to change the style of an
element.
To make styles easy to edit, it’s best to style with a type selector, if possible. If not, add a
class selector. If that is not specific enough, then consider using an ID selector.
90
Chaining
When writing CSS rules, it’s possible to require an HTML element to have two or more CSS
selectors at the same time.
This is done by combining multiple selectors, which we will refer to as chaining. For instance,
if there was a special class for <h1> elements, the CSS would look like below:
h1.special {
The code above would select only the <h1> elements with a class of special. If a <p>
element also had a class of special, the rule in the example would not style the paragraph.
Descendant combinator
The descendant combinator — typically represented by a single space ( ) character —
combines two selectors such that elements matched by the second selector are selected if
they have an ancestor (parent, parent's parent, parent's parent's parent, etc.) element
matching the first selector. Selectors that utilize a descendant combinator are called
descendant selectors.
body article p
Child combinator
The child combinator (>) is placed between two CSS selectors. It matches only those
elements matched by the second selector that are the direct children of elements matched
by the first. Descendant elements further down the hierarchy don't match. For example, to
select only <p> elements that are direct children of <article> elements:
article > p
91
Next-sibling combinator
The next-sibling combinator (+) is placed between two CSS selectors. It matches only those
elements matched by the second selector that are the next sibling element of the first
selector. For example, to select all <img> elements that are immediately preceded by a <p>
element:
p + img
Subsequent-sibling combinator
If you want to select siblings of an element even if they are not directly adjacent, then you
can use the subsequent-sibling combinator (~). To select all <img> elements that come
anywhere after <p> elements, we'd do this:
p ~ img
92
Module 4 - Introduction to
Javascript
Initially, JavaScript had a few different names. It was first called Mocha, then LiveScript,
and finally JavaScript in December 1995.
Standardizing Javascript
JavaScript has two standards:
The language defined by these standards is called ECMAScript, not JavaScript. This name
was chosen because Sun (now Oracle) had a trademark on the name JavaScript. The original
name of that organization was ECMA, an acronym for European Computer
Manufacturers Association. It was later changed to Ecma International (with “Ecma”
being a proper name, not an acronym) because the organization’s activities had expanded
beyond Europe. The initial all-caps acronym explains the spelling of ECMAScript.
In principle, JavaScript and ECMAScript mean the same thing. However, some people make
the following distinction:
JavaScript refers to the language and its implementations. ECMAScript refers to the
language standard and language versions. Therefore, ECMAScript 6 is a version of the
language (its 6th edition).
93
New JavaScript features
Private slot checks (“ergonomic brand checks for private fields”): The following
expression checks if obj has a private slot #privateSlot:
# privateSlot in obj
Top-level await in modules: We can now use await at the top levels of modules and
don’t have to enter async functions or methods anymore.
error.cause: Error and its subclasses now let us specify which error caused the current
one:
Method .at() of indexable values lets us read an element at a given index (like the
bracket operator []) and supports negative indices (unlike the bracket operator).
The following “indexable” types have method .at(): – string – Array – All Typed Array
94
classes: Uint8Array etc.
Object.hasOwn(obj, propKey) provides a safe way to check if an object obj has an own
property with the key propKey. In contrast to Object.prototype.hasOwnProperty, it
works with all objects.
We use Promise.any() when we are only interested in the first fulfilled Promise among
several.
a ||= b
a &&= b
a ??= b
95
Bigint literals: 6_000_000_000_000_000_000_000_000n
Dynamic imports via import(): The normal import statement is static: We can
only use it at the top levels of modules and its module specifier is a fixed string.
import() changes that. It can be used anywhere (including conditional
statements) and we can compute its argument.
import.meta contains metadata for the current module. Its first widely
supported property is import.meta.url which contains a string with the URL of
the current module’s file.
Optional chaining for property accesses and method calls. One example of optional
chaining is:
value.?prop
value ?? defaultValue
This expression is defaultValue if value is either undefined or null and value otherwise.
This operator lets us use a default value whenever something is missing. Previously
the Logical Or operator (||) was used in this case but it has downsides here because it
returns the default value whenever the left-hand side is falsy (which isn’t always
correct).
96
Bigints – arbitrary-precision integers: Bigints are a new primitive type. It supports
integer numbers that can be arbitrarily large (storage for them grows as necessary).
globalThis provides a way to access the global object that works both on browsers and
server-side platforms such as Node.js and Deno
Array method .flatMap() works like .map() but lets the callback return Arrays of zero or
more values instead of single values. The returned Arrays are then concatenated and
become the result of .flatMap(). Use cases include:
Filtering and mapping at the same time
Mapping single input values to multiple output values
Array method .flat() converts nested Arrays into flat Arrays. Optionally, we can tell it
at which depth of nesting it should stop flattening.
Object.fromEntries() creates an object from an iterable over entries. Each entry is a
two-element Array with a property key and a property value.
String methods: .trimStart() and .trimEnd() work like .trim() but remove whitespace
only at the start or only at the end of a string.
Optional catch binding: We can now omit the parameter of a catch clause if we don’t
use it.
Symbol.prototype.description is a getter for reading the description of a symbol.
Previously, the description was included in the result of .toString() but couldn’t be
accessed individually.
97
Asynchronous iteration is the asynchronous version of synchronous iteration. It is
based on Promises:
Spreading into object literals: By using spreading (...) inside an object literal, we can
copy the properties of another object into the current one. One use case is to create a
shallow copy of an object obj: const shallowCopy = {...obj};
RegExp Unicode property escapes give us more power when matching sets of Unicode
code points – for example:
98
> /^\p{Lowercase_Letter}+$/u.test('aüπ')
true
> /^\p{White_Space}+$/u.test('\n \t')
true
> /^\p{Script=Greek}+$/u.test('ΩΔΨ')
true
Template literal revision allows text with backslashes in tagged templates that is
illegal in string literals – for example:
windowsPath`C:\uuu\xxx\111`
latex`\unicode`
Object.entries() returns an Array with the key-value pairs of all enumerable string-
keyed properties of a given object. Each pair is encoded as a two-element Array.
String padding: The string methods .padStart() and .padEnd() insert padding text until
the receivers are long enough:
99
Trailing commas in function parameter lists and calls: Trailing commas have been
allowed in Arrays literals since ES3 and in Object literals since ES5. They are now also
allowed in function calls and method calls.
> 4 ** 2
16
100
Using Javascript
101
An overview of JavaScript’s syntax
Basic constructs
Comments
// single-line comment
/*
Comment with
multiple lines
*/
Booleans:
true
false
Numbers:
1.141
-123
The basic number type is used for both floating point numbers (doubles) and integers.
Bigints:
17n
-49n
The basic number type can only properly represent integers within a range of 53 bits plus
sign. Bigints can grow arbitrarily large in size.
Strings:
102
'abc'
"abc"
`String with interpolated values: ${256} and ${true}`
JavaScript has no extra type for characters. It uses strings to represent them.
Operators
103
Declaring variables
const creates immutable variable bindings: Each variable must be initialized immediately
and we can’t assign a different value later. However, the value itself may be mutable and we
may be able to change its contents. In other words: const does not make values immutable.
Arrow function expressions are used especially as arguments of function calls and method
calls:
104
const add2 = (a, b) => { return a + b };
// Calling function add2()
assert.equal(add2(5, 2), 7);
// Equivalent to add2:
const add3 = (a, b) => a + b;
// An arrow function whose body is a code block
(a, b) => { return a + b }
// An arrow function whose body is an expression
(a, b) => a + b
Plain objects
Arrays
105
Control flow statements
Conditional statement:
if (x < 0) {
x = -x;
}
for-of loop:
The grammatical category of variable names and property names is called identifier.
Identifiers are allowed to have the following characters:
Some words have special meaning in JavaScript and are called reserved. Examples include:
if, true, const. Reserved words can’t be used as variable names:
const if = 123;
// SyntaxError: Unexpected token if
106
> const obj = { if: 123 };
> obj.if
123
Casing styles
Capitalization of names
Uppercase:
Classes: MyClass
Constants: MY_CONSTANT
Constants are also often written in camel case: myConstant
The following naming conventions are popular in JavaScript. If the name of a parameter
starts with an underscore (or is an underscore) it means that this parameter is not used – for
example:
arr.map((_x, i) => i)
If the name of a property of an object starts with an underscore then that property is
considered private:
107
class ValueWrapper {
constructor(value) {
this._value = value;
}
}
108
Identifiers
Subsequent characters:
Examples:
const ε = 0.0001;
const строка = '';
let _tmp = 0;
const $foo2 = true;
Reserved words
Reserved words can’t be variable names, but they can be property names. All JavaScript
keywords are reserved words:
await break case catch class const continue debugger default delete
do else export extends finally for function if import in instanceof
let new return static super switch this throw try typeof var void
while with yield
The following tokens are also keywords, but currently not used in the language:
109
enum implements package protected interface private public
Technically, these words are not reserved, but you should avoid them, too, because they
effectively are keywords:
You shouldn’t use the names of global variables (String, Math, etc.) for your own variables
and parameters, either.
110
Statement vs. expression
This section will explain how JavaScript tells the difference between two types of code:
statements and expressions. After that, we'll see how this can cause problems because the
same code can be used for two different things, depending on where it is used.
Statements
A statement is a piece of code that can be executed and performs some kind of action. For
example, if is a statement:
let myStr;
if (myBool) {
myStr = 'Yes';
} else {
myStr = 'No';
}
function twice(x) {
return x + x;
}
Expressions
An expression is a piece of code that can be evaluated to produce a value. For example, the
code between the parentheses is an expression:
The operator ?:_ used between the parentheses is called the ternary operator. It is the
expression version of the if statement. Let’s look at more examples of expressions. We enter
expressions and the REPL evaluates them for us:
111
> 'ab' + 'cd'
'abcd'
> Number('123')
123
> true || false
true
function max(x, y) {
if (x > y) {
return x;
} else {
return y;
}
}
However, expressions can be used as statements. Then they are called expression
statements. The opposite is not true: when the context requires an expression, you can’t use
a statement. The following code demonstrates that any expression bar() can be either
expression or statement – it depends on the context:
function f() {
console.log(bar()); // bar() is expression
bar(); // bar(); is (expression) statement
}
112
Ambiguous syntax
JavaScript has several programming constructs that are syntactically ambiguous: the same
syntax is interpreted differently, depending on whether it is used in statement context or in
expression context. This section explores the phenomenon and the pitfalls it causes.
function id(x) {
return x;
}
{}
Disambiguation
The ambiguities are only a problem in statement context: If the JavaScript parser encounters
ambiguous syntax, it doesn’t know if it’s a plain statement or an expression statement. For
example:
113
expression?
If a statement starts with {: Is it an object literal or a code block?
To resolve the ambiguity, statements starting with function or { are never interpreted as
expressions. If you want an expression statement to start with either one of these tokens,
you must wrap it in parentheses:
In this code:
The code fragment shown in (1) is only interpreted as an expression because we wrap it in
parentheses. If we didn’t, we would get a syntax error because then JavaScript expects a
function declaration and complains about the missing function name. Additionally, you can’t
put a function call immediately after a function declaration.
114
Semicolons
const x = 3;
someFunction('abc');
i++;
function foo() {
// ···
}
if (y > 0) {
// ···
}
The whole const declaration (a statement) ends with a semicolon, but inside it, there is an
arrow function expression. That is, it’s not the statement per se that ends with a curly brace;
it’s the embedded arrow function expression. That’s why there is a semicolon at the end.
115
while (condition)
statement
But blocks are also statements and therefore legal bodies of control statements:
while (a > 0) {
a--;
}
If you want a loop to have an empty body, your first option is an empty statement (which is
just a semicolon):
116
Automatic semicolon insertion (ASI)
While I recommend to always write semicolons, most of them are optional in JavaScript. The
mechanism that makes this possible is called automatic semicolon insertion (ASI). In a way,
it corrects syntax errors. ASI works as follows. Parsing of a statement continues until there is
either:
A semicolon
A line terminator followed by an illegal token
In other words, ASI can be seen as inserting semicolons at line breaks. The next subsections
cover the pitfalls of ASI.
return
{
first: 'jane'
};
return;
{
first: 'jane';
};
That is:
117
Why does JavaScript do this? It protects against accidentally returning a value in a line after
a return.
a = b + c
(d + e).print()
Parsed as:
a = b + c(d + e).print();
a = b
/hi/g.exec(c).map(d)
Parsed as:
a = b / hi / g.exec(c).map(d);
someFunction()
['ul', 'ol'].map(x => x + x)
Executed as:
118
const propKey = ('ul','ol'); // comma operator
assert.equal(propKey, 'ol');
119
Introducing Nodes
<h1>My Slideshow</h1>
In the Document Object Model, nodes are organized into a hierarchical structure called a
node tree. Figure 3-1 shows the representation of the node tree for a sample HTML.
Nodes in the node tree have a familial relationship—each node can be a parent, child, and/or
sibling of other nodes. In the node tree shown in Figure 3-1, the parent of the body node is
the html node, and the parent node at the top of the node tree is known as the root node.
The body element has two child nodes: an h1 element and a paragraph (p) element. The h1
element and the paragraph element are siblings of each other because they share a
common parent.
120
Each of these familial relationships can be referenced using the JavaScript properties
For example, the following expression references the parent of a node within the node tree.
node.parentNode
Expression Description
node.childNodes A node list of all nodes which are direct children of node
node.previousSibling The sibling listed before node on the same level in the node tree
node.nextSibling The sibling listed after node on the same level in the node tree
To go two levels up (to the “grandparent”) add another parentNode property to the
expression:
node.parentNode.parentNode
and to go to an “aunt or uncle” node, go up to the parent node and move to either sibling:
node.parentNode.previousSibing
node.parentNode.nextSibling
document.querySelectorAll(css)
where css is the text of CSS selector. For example, the following expression creates a node
list by selecting all paragraph element nodes belonging to the review class:
document.querySelectorAll("p.review");
The querySelectorAll() method gives the programmer more options selecting elements than
121
could be achieved by the getElementsByClassName() or getElementsByTagName() methods.
However, the querySelectorAll() method creates a node list, not an HTML collection, and
there are some important differences. JavaScript also provides the querySelector() method,
which returns the first element node that matches the CSS selector rather than the complete
node list.
Expression Description
For example, the following code creates an element node for an h1 heading and a text node
containing the text string “My Slideshow”:
Nodes can be combined to create a document fragment. The document fragment resides
only within computer memory and is not yet part of the web page.
Expression Description
122
The following code appends the headingTxt node as a child of the mainHeading node:
mainHeading.appendChild(headingTxt);
<h1>My Slideshow</h1>
To place mainHeading into the web document it must be attached to a node already present
in that document’s node tree. If the document had a div element with the id “intro”, the
mainHeading node could be attached to that element using the following code:
and the web page would then include the following content:
<div id="intro">
<h1>My Slideshow</h1>
</div>
However, you can also define individual styles by appending the style property and a style
value to the object. For example, you can set values of the font-size and color properties
123
using the following:
mainH1.style.fontSize = "1.5em";
mainH1.style.color = "blue";
Notice that because JavaScript does not support hyphens in property names, the CSS font-
size style is written in camel case as fontSize. Similarly, the background-color style would be
written as backgroundColor, the font-family style would be entered as fontFamily, and so
forth. Any styles defined using the style property are treated as inline styles and thus will
have precedence over styles defined in an embedded or external style sheet.
Cloning a Node
In some of your applications you may need to create and move a copy of a node rather than
the node itself. To create a node copy, apply the command:
node.cloneNode(deep)
where node is the node to be copied and deep is a Boolean value that is true to create a
deep copy that copies the node and all of its descendants or false to copy only the node and
not any descendants. In the following code, the mainCopy node is a copy of all the content
of the mainElem node, including any nested headings, paragraphs, text, inline image tags,
etc.
The cloneNode() method will copy all of the node’s DOM content, but it will not copy any
JavaScript properties attached to the node. For example, it will not copy event handlers, so
those will have to added individually to any node copies.
Exercise
1. HTML Setup: Create an HTML file with the following structure:
124
<!DOCTYPE html>
<html>
<head>
<title>DOM Manipulation Example</title>
</head>
<body>
<div id="item-list"></div>
<script src="script.js"></script>
</body>
</html>
This HTML file creates a container element with the ID item-list where the dynamic list will
be added.
2. JavaScript Code: Create a JavaScript file named script.js and add the following code:
This JavaScript code creates two new list item elements, newItem and anotherItem, and
appends them to the itemList container. The appendChild method adds the element to the
end of the container. The insertBefore method inserts the element before the specified child
element or at the beginning of the container if no child is specified.
3. Run the Code: Open the HTML file in your web browser. The dynamic list should now
display two items: "Item 2" and "Item 1".
125
Module 5 - Application
Programming Interface
Application Programming Interfaces (APIs) have become indispensable tools for software
development and integration. APIs provide a structured and standardized way for different
applications to communicate and exchange data, enabling seamless integration and
innovation across the digital landscape. This module delves into the fundamentals of APIs,
exploring their concepts, functionalities, and real-world applications.
126
What is API?
An API (Application Programming Interface) is a set of rules and specifications that define
how two software applications can communicate with each other. It acts as an intermediary,
translating requests from one application into understandable instructions for the other,
allowing them to exchange data and functionality. APIs are the backbone of modern
software development, facilitating data sharing, integration, and innovation.
Types of APIs
Public APIs: Public APIs are freely accessible and documented, allowing anyone to
build applications that interact with the API's provided services or data.
Private APIs: Private APIs are restricted to authorized users or applications within an
organization or ecosystem.
Partner APIs: Partner APIs are designed for specific partners or collaborators,
enabling them to integrate their applications or services with the API provider's
platform.
API Lifecycle
The API lifecycle encompasses the entire process of creating, maintaining, and evolving an
API to ensure its effectiveness and relevance.
Design and Planning: Defining the API's purpose, target audience, and functional
scope.
Development and Implementation: Creating the API's code, documentation, and
testing infrastructure.
Deployment and Access: Publishing the API for public or restricted access.
Maintenance and Evolution: Monitoring API usage, addressing bugs, and
implementing new features or enhancements.
127
Benefits of Utilizing APIs
Accelerated Development: APIs provide pre-built functionalities, reducing
development time and effort.
Enhanced Integration: APIs enable seamless integration between different
applications and systems.
Innovation and Collaboration: APIs foster innovation by enabling developers to
build upon existing services and data.
Scalability and Flexibility: APIs facilitate scalable and flexible solutions that can
adapt to changing requirements.
128
Using public API
JSONPlaceholder is a free online REST API that provides a vast collection of fake data for
testing and prototyping purposes. It offers a variety of resources, including posts,
comments, albums, photos, todos, and users, making it an ideal tool for practicing API
interactions and data manipulation in JavaScript. This is the url
https://jsonplaceholder.typicode.com/
fetch('https://jsonplaceholder.typicode.com/posts')
.then(response => response.json())
.then(data =>
console.log(data))
.catch(error =>
console.error(error)
);
This code snippet initiates a GET request to the /posts endpoint of the JSONPlaceholder API.
The response is then parsed as JSON data, and the resulting data object is logged to the
console.
129
const newPost = {
title: 'My New Post',
body: 'This is the content of my new post.',
};
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
body: JSON.stringify(newPost),
headers: {
'Content-Type': 'application/json',
},
})
.then(response => response.json())
.then(data =>
console.log(data))
.catch(error =>
console.error(error));
Similarly, to update an existing post, you would use the PUT method and specify the ID of
the post to update:
const updatedPost = {
id: 1, // ID of the post to update
title: 'Updated Title',
body: 'Updated post content.',
};
fetch(`https://jsonplaceholder.typicode.com/posts/${updatedPost.id}`, {
method: 'PUT',
body: JSON.stringify(updatedPost),
headers: {
'Content-Type': 'application/json',
},
})
.then(response => response.json())
.then(data =>
console.log(data))
.catch(error =>
console.error(error)
);
Finally, to delete a post, you can use the DELETE method and specify the ID of the post to
130
delete:
fetch(`https://jsonplaceholder.typicode.com/posts/${postId}`, {
method: 'DELETE',
})
.then(response => console.log(response.status))
.catch(error => console.error(error));
131