This week, you'll lay the foundations... of the foundations. Everyone has seen some web technologies before -- whether it's just as someone who's used websites, or built some of your own. These technologies are ubiquitous.
Whatever your prior expereince, this week you'll touch on HTML, CSS, and JavaScript, three core languages at the heart of the internet. As you get your first taste of reading and writing each language, you'll focus on how they are connected.
You'll also start practising learning and working together. The internet is social, and technologists build it together. So, that's what you'll learn to do too.
Web Development is everything that’s involved in building websites. Websites as different as Youtube, Wikipedia, Twitter, and Google all use the same building blocks under the hood. Under the hood, all of those websites use HTML, CSS, and JavaScript.
All the familiar features like text, images, colors, input boxes, forms, and videos are made out of these technologies. There’s some features like chat or purchases that require learning more than what we’ll cover in this course, but everything you see on the web is based on these foundational languages.
In this course, you’ll learn the basics of building websites with HTML, CSS, and JavaScript.
HTML makes up the content and structure of the webpage. It’s what a page is made of.
Here’s an example.
<p>
This is a paragraph. It has an
<a href="https://example.com">
Example Link
</a>
inside the paragraph.
</p>
<img src="valley-waterfall.png" alt="this is an example image" />
HTML is text! The syntax uses the angle brackets <> to identify elements that make up a page. You'll learn lots of different elements.
JavaScript (often abbreviated JS) is a programming language that runs within the browser. It has many of the same features as other programming languages like Python, Ruby, or Java, but lots of quirks and specific details to learn about the language itself.
Here's a small example program in JavaScript that adds a list of names to the page:
let names = ["Lola", "Wasiu", "Rob"]
for (let name in names) {
document.querySelector('.container') += name
}
CSS has rules that control the appearance of selected elements, like
p {
color: red;
}
JS is a programming language like Python, but with some differences in syntax and what it can do
For the rest of the course, you'll dive deeper into these three languages, and get lots of practice reading and writing these languages to build webpages.
Even though we tend to use "the web" and "the internet" interchangably, they're actually two different things. While
the focus of this course is on the web and web development, it's good to have some foundational understanding of the
internet.
Starting in the 1960s, university and government researchers created a system to share files
between computers. That system, called ARPANET, established protocols for file sharing, routing, and messaging that
grew into the public internet.
Since then, the internet has grown to become a global network of cables, cell towers, satellites, phones, and computers, all connected by networking protocols descended from those of ARPANET.
You may have seen protocols like http (it's in the address bar, or at the beginning of a URL). Protocols like HTTP (the hypertext transfer protocol)
are sets of rules that software programs follow so that they understand each other.
Connecting billions of different devices requires a lot of rules! There are a
lot of protocols that make up the modern Internet -- HTTP, TCP/IP, Ethernet,
DNS, Websockets... Even Bluetooth is a protocol that carries internet traffic!
You don't need to know what those acronyms stand for yet. You should
know that the Internet is made of a lot of devices, connected by protocols.
If the Internet is the connections between the computers plus the protocols they
use to communicate, the Web is the most visible way that people interact with
the internet in their daily lives.
The Web was originally conceived as a collection of files and documents,
shared and linked together using the internet.
Web pages are documents, created using HTML, CSS and other web technologies. Web
pages can be accessed using a web browser, like Chrome or Edge. Pages contain text,
images, links, and other elements.
A combination of multiple web pages makes up a website.
Your browser turns those files into the page that you see.
Further Exploration: Clients and Servers
Computers connected to the web are called clients and servers. A simplified diagram of how they interact might look like this:
Clients are internet-connected devices. For example, your computer connected to your Wi-Fi, or your phone connected to your mobile network, using software available on those devices — usually a web browser like Firefox or Chrome.
Servers are computers that store webpages, sites, or apps. When a client device wants to access a webpage, a copy of the webpage is downloaded from the server onto the client machine to be displayed in the user's web browser.
A website is made up of many different files. These files come in two main types:
Code files: Websites are built primarily from HTML, CSS, and JavaScript, though you'll meet other technologies a bit later.
Assets: This is a collective name for all the other stuff that makes up a website, such as images, music, video, or PDFs.
🔍 Further Exploration: How does the browser put the files together?
When browsers send requests to servers for HTML files, those HTML files often contain <link> elements referencing external CSS stylesheets and <script> elements referencing external JavaScript scripts.
The browser reads the HTML file first.
The browser looks for any <link>elements to external CSS stylesheets and any <script>elements that reference JavaScript files.
The browser sends requests back to the server for the CSS files it has found from <link> elements and the JavaScript files from <script> elements.
The browser builds the page from the HTML, applies the styles from the CSS, and executes the JavaScript. It shows the resulting page on the screen.
Then you see the page content, and can interact with it!
In this class, we won’t worry too much about how the other computer decides which files to send, or how to write other kinds of programs. If you continue to learn more about programming and web development, you’ll learn more about how that part of the system works.
Here’s an example. On the left is HTML. On the right is the same code, rendered as a webpage.
<p>
This is a paragraph. It has an
<a href="https://example.com">
Example Link
</a>
inside the paragraph.
</p>
<img src="https://web-foundations.vercel.app/lessons/foundations/html-elements-and-attributes/valley-waterfall.png" alt="this is an example image" />
This tool is called CodePen, and we'll use it to demonstrate snippets of HTML, CSS, and JS. You can use it as a small playground for experimenting.
HTML is made of text you can type on your keyboard. In addition to normal words, there are special words in angle brackets, like <p>, <a>, and <img> that add structure to the content.
The building blocks of HTML are called elements. A webpage is made up of elements.
There are lots of types of elements. In the snippet above, the elements are:
<a> stands for ‘anchor’, but means link
<p> for paragraph
<img> for images
There are many many elements in addition to these three. You’ll learn about 20 to 30 elements in the course. You can always look them up if you forget.
HTML elements can go inside of each other. Everything that’s in between the opening tag and the closing tag is ‘inside’ an element. It can be text, like the paragraph above, or other HTML elements, or both. The element inside another element is called the child element while the one outside is the parent. Here's an example showing a <p> element inside an <a> element.
There’s more than 200 HTML elements, you can see them all on MDN. You don’t need to memorize all of them. There are tons of them you’ll never ever use!
Inside a <p>, an <a>, or lots of other tags, you’ll see regular text. Text placed inside many elements shows up on the page. Sometimes, depending on the element, the text will show up differently.
There are two kinds of lists. Unordered Lists <ul> have dots before each item. Ordered Lists <ol> have increasing numbers before each item. Both lists use <li> for list items.
Selectors pick all the elements that match, and the style rule applies to all those elements.
There are lots of kinds of selectors. We’ll focus on the three most common selectors (Element Selectors, Class selectors, and id selectors) and how to combine selectors. Then, you can practice with more advanced selectors too!
The selector .cool-paragraph selected the second paragraph, because it had a matching class attribute. The syntax is . plus the name of the class, in this case cool-paragraph.
You can have lots of elements with the same class. There can be lots of cool-paragraphs.
#paragraph-6 picks the paragraph with the id paragraph-6. The syntax is a # plus the id (like paragraph-6). There’s only supposed to be one element with any particular id.
If you put two selectors together, you select elements that match both selectors. You can select “the paragraphs that also have the class cool-paragraph” by combining the p and .cool-paragraph selectors like p.cool-paragraph.
There are other CSScombinators that let you pick elements that have relations like “all the links inside of list items” or “paragraphs right after second-level headings”.
Combinator is a fancy word for “thing that combines things”.
Here’s some examples:
.cool-paragraph strong selects all the <strong>elements inside elements with the cool-paragraph class.
h2 + p selects the paragraphs that immediately follow a level 2 header
We write our JavaScript in separate files, which in this course we’ll name script.js. To connect the JavaScript to the HTML page, we’ll use a <script> tag.
<script src="script.js"></script>
We use the src attribute to say where to find the JavaScript file.
Note: It’s called src for <script> tags. link and a tags have href, which is similar. If you mix them up, try switching to the other one.
We usually place the script tag at the end of the <body> tag, so that the rest of the page has loaded before the script is run.
#gross, .reaction, and #yum are all CSS Selectors! When you learn to use JavaScript to create interactions, you’ll still use concepts from HTML and CSS.
The same CSS selectors that you use for styles will also let you pick HTML elements in your JS code.
In week 6, we’ll talk more about how the rest of the code works.
Web developers frequently need to see what's happening 'under the hood' on a website. The Browser Developer Tools (also called the “DevTools”, the “Inspector”, or the “Console”) give you that power.
The DevTools are awesome for seeing how a webpage is working, and testing out code. 👍🏿
The Devtools are safe
It’s impossible to do any permanent damage to a website from the DevTools.
None of the changes you make in the DevTools are permanent. It’s a safe space to experiment. If something goes wrong, you can refresh 🔁 the page and get back to the original.
In this Scavenger Hunt, you’ll use the DevTools to view and edit properties of a webpage. You’ll get to explore for yourself what a webpage is made of, and practice using the tools that real web developers use to debug websites.
In this week, there are several exercises for you to engage with. Some of which are optional and others mandatory. This will be the pattern throughout the course. You are encouraged to attempt all the exercises, however, you are expected to submit the mandatory exercises to Gradescope.
Chicken Peanut Stew: In this exercise, you'll take a recipe that's written in text and turn it into an HTML page. You'll practice choosing the
appropriate elements for different pieces of information and writing the HTML from scratch.
Shirt City: Here, your task is to identify and fix errors in a given html file to obtain the desired result, as specified.
This week, you'll learn and practice more HTML tags.
There are more tags than you'll ever need to memorize. However, it's helpful to be familiar with lots of the common tags, so that you know which to reach for when building websites.
You'll also learn about Semantic HTML: using HTML tags that have the right meaning. Semantic HTML helps create well-structured, accessible, and search engine-friendly web pages while providing a better experience for users.
Did you know you can create table structures, using HTML tags? This lesson discusses how to do this.
A table in HTML consists of table cells inside rows and columns. A table in HTML can contain other tables. It can also contain other types of elements such as text, images, links, lists, etc.
Watch Video
Summary
use the <table> </table> tags to create your table structure.
Use the <tr> </tr> tags to add rows to your tables.
Use the <th> </th> tags to add table header.
Use the <td> </td> tags to add table data (content) or cell
The table shown in example has three rows, which is why there are 4 pairs of <tr> ... </tr> tags in total. Each of the rows has three columns or data cells. The first row is the table header, therefore the <td> ..</td> tags were used. On the other hand, the last three rows are regular data cells, therefore the <td> ... </td> tags were used.
Activity
Create the table shown in the image below.
Extra: You can also style your table by adding text colours, background colours and other styles possible.
Further Reading
Although we have covered the basics of a table, there are additional attributes and tags that can be used to create more complex tables.
A lot of the new interactive elements work similarly to how images work.
<img src="valley-waterfall.png" />
The src attribute tells the browser where to find the image file, and the browser inserts the image at that spot in your site.
When styling images, you have to think about the width and height carefully so that you don’t break the aspect ratio. If an image is normally 100px by 100px, and you make it 50px by 200px in CSS, that will stretch out the image, and it will look bad.
When styling the new interactive elements, you’ll have to think about the same ideas: where’s the source url, and how do I style the element so that it looks right on the page.
Inline frames allow you to embed content from another site into your site. You can use them to embed tons of different kinds of content. In this curriculum, we use tons of embedded content — YouTube and Loom videos, forms, and interactive coding exercises.
A typical iframe might look something like this, which embeds a video from youtube.
The src, width and height attributes are familiar from the <img> element.
src is the url where the browser should find the content
width and height control the width and height of the element
The other attributes are new:
title sets the title of the iframe
frameborder controls the border of the iframe. It’s often good to set it to 0
allow and allowfullscreen control the permissions that the iframe has. Since the content is coming from another website, you can decide what it is allowed to do.
src and width work the same way they do for img and iframe.
The new attribute is controls. With controls added, the audio or video player will show the controls: play, pause, and volume.
It’s usually good to show the controls, since otherwise the user won’t be able to control the video or audio on the page. Usually, if they can’t control the audio or video, they’ll close the page instead of letting things autoplay.
Specifying multiple sources lets browser choose which kind of content to support. There’s fancy new formats like .webm that only some browsers can use, so if you write your code using <source>, users who have those browsers get the fancy new formats, and other users still get something that works for them.
Semantics refers to the meaning of a piece of code. It’s about "what purpose or role does that HTML element have", rather than "what does it look like?".
When approaching which markup to use, ask yourself, "What element(s) best describe/represent the data that I'm going to populate?”
MDN
HTML elements mean something. A <p> isn’t just styled like a paragraph, it tells other programs that the text inside really is a paragraph. We saw some semantic elements in the previous lesson, for example the <audio> and <video> tags that allow us to add audio and video content into a web page.
The <div> element is a commonly used tag, however, it is not a semantic HTML element. The <div> tag can be used to contain any type of information. On the other hand, the <header> tag can be used instead of a <div> to contain header information. In like manner, the <footer> element can be used to contain page's footer element at the end of the page. This way, we know exactly what type of information is contained in the element.
Other commonly used semantic HTML elements include the <nav> which is used to hold nagivational links and the <main>, used to encapsulate the main content of a page.
There are lots of kinds of “things” that go on webpages. For many of them, there’s a matching HTML element. Here’s some examples (there’s more than 100!)
In this week, there are several exercises for you to engage with. Some of which are optional and others mandatory. You are encouraged to attempt all the exercises, however, you are expected to submit the mandatory exercises to Gradescope.
Both Numbers are Even: In this exercise, you will implement a function to determine if two given numbers are even or not.
Fizz Buzz: In this exercise, you will write a program to determine if a given number is divisible by 3 or 5.
Count Characters in String: In this exercise, you will write a program to count the number of characters in a string.
Can I Drive and Vote: In this exercise you will write a program to help determine if a person can either drive or vote, based on the person's age and country of residence.
Can I Order Item: In this exercise, you will implement a function that checks if a specified dish is available in stock.
This week, we are going to continue exploring the fundamentals of the JavaScript language. Last week, we explored functions and arrays briefly. This week, we'll be going deeper and exploring more of their capabilities.
If you are yet to review the lessons from last week, or yet to fully grasp the concepts covered last week, it is advisable to go through the content again.
Finally, in programming, we always have errors. This week we'll also learn more about how to debug code and fix errors that we will inevitably have.
Previously, we touched on arrays, in this lesson, we'll take a depper dive into arrays in JavaScript. You'll learn more about how to handle arrays and different array functions that exist.
There is a for..of construct in JavaScript that helps to quickly navigate through every element in an array. The for...of statement executes a loop that operates on a sequence of values sourced from an iterable object such as Array, and String. This construct is similar to the for loop syntax in Python.
Arrays are objects, therefore they have properties and methods. We already saw one property of the array, length, which returns the size of an array, that is the number of elements in the array. Next, we'll review some array methods.
From the previous example, we see that the typeof function cannot help us to confirm precisely whether a data type is actually an Array object. However, the Array object itself has a static method that can be used to determine if the value passed to it is actually an Array object.
If you need to modify every element in an array in a similar manner, you can use the map function. The map function itself takes in a function. For example, let's assume we have an array of numbers, and we want to multiply every element of the array by a certain number.
The push() method is used add items into an array. It adds items to the end of an array. It takes in the value you want to add to the array.
Try it!
const shoppingList = ["Rice", "Bread", "Fish", "Beans"];
//Let's add a new item to our shopping list
shoppingList.push("Gaari");
console.log(shoppingList)
The unshift() method is used to add an item to the start of the array. It takes in the value you want to add to the array.
Try it!
const shoppingList = ["Rice", "Bread", "Fish", "Beans"];
//Let's add a new item to our shopping list
shoppingList.unshift("Gaari");
console.log(shoppingList)
The splice() method is used to remove an item from a particular position, using its index. In last week's lesson, we saw the use of the indexOf() method, it simply returns the index of an item if it is present in the array. We want to remove the Bread item from our shoppingList, but Bread is neither at the beginning nor at the end of our array - the splice() method comes to the rescue.
The JavaScript Math object comprises of several functions and constants that can be used to perform mathematical operations. It should be noted that the Math object doesn't have a constructor.
The syntax for using properties of the Math object is Math.property. A few of the properties available are listed next. Try them out in the console to see how they operate.
Math functions make it possible to carryout different computations. The syntax for using a Math function is Math.functionName(value). Example of Math functions includes Math.random(value), Math.round(value), Math.ceil(value), and Math.abs(value).
The JavaScript String functions are used to manipulate strings. They can be used to retrieve a subset of string from a specific string. They can also be used to modify a copy of string data. It should be noted when retrieving subset data, the functions use zero as a starting index.
It returns the position of a char value present in the given string. It will return -1 if the position couldn't be determined, i.e. if the character is not present in the string.
It is similar to indexOf function, however it returns the position of a char value present in the given string by searching a character from the last position.
search() - It searches a specified regular expression in a given string and returns its position if a match occurs.
match() - It searches a specified regular expression in a given string and returns that regular expression if a match occurs.
replace() - It replaces a given string with the specified replacement.
substr() - It is used to fetch the part of the given string on the basis of the specified starting position and length.
substring() - It is used to fetch the part of the given string on the basis of the specified index.
slice() - It is used to fetch a part of the given string.
toLowerCase() - It converts the given string into lowercase letters.
toLocaleLowerCase() - It converts the given string into lowercase letter on the basis of host's current locale.
toUpperCase() - It converts the given string into uppercase letters.
toLocaleUpperCase() - It converts the given string into uppercase letter on the basis of host's current locale.
toString() - It returns a string representing the particular object.
valueOf() - It returns the primitive value of a string object.
split() - It splits a string into an array of substrings based on a specified separator. It takes the separator as an argument and returns an array containing the substrings.
trim() - It trims off whitespace from the left and right side of the string.
Variables defined within the scope of a function has a lifespan within that specific function alone and not available outside of the function in which it was defined. Step through the code snippet and watch the demonstration to see how the scopes of the functions and variables change.
1 function first(val){
2 var name = val
3 console.log(name)
4
5 var addr = "residence"
6
7 function second(val){
8 var name = val
9 console.log(name)
10 }
11
12 second(addr)
13 }
We talked a little bit about arrow functions last week, now let's see an example. Instead of the function keyword, we use an arrow => (the equal sign, followed by the greater than symbol). The arrow comes after the list of parameters, and is followed by the function body.
let power = (base, exponent) => {
return base ** exponent;
}
Higher-order functions are functions that operate on other functions, either by taking a function as an argument or by returning a function. In JavaScript, there are a number of built-in higher order functions, that take in functions as arguments.
We saw the map() function in the previous lesson. The map function takes in a function. You might also have a need to build your own higher-order function.
Let's look at an example of a function that is passed as a parameter to another function.
The function console.log(<value>) can be used to display JavaScript values in the Console tab of our Devtools. This method is quite helpful, but it's not the most efficient approach. Notwithstanding, there are different ways to use the console for debugging.
Watch this Video on ways to use the console for debugging
A single or multiple breakpoints can be set in a debugger window. At each breakpoint, code execution will be paused, making it possible to examine available JavaScript values.
Watch this Video on how to set different breakpoints
The debugger keyword can be used to temporarily pause the execution of JavaScript code. This is similar to setting a breakpoint, however it has no effect on browsers that don't have support for it.
In this week, there are several exercises for you to engage with. Some of which are optional and others mandatory. You are encouraged to attempt all the exercises, however, you are expected to submit the mandatory exercises to Gradescope.
Prime Checker: In this exercise, you will write a program to determine if a given number is a prime number. You will also need to check if the given input is a number.
Palindrome Checker: In this exercise, you will write a program to determine if a given input is a palindrome.
Three-digit Armstrong: In this exercise, you will write a program to determine if a given number is an Armstrong number. You will also need to check if the given input is a three-digit number in the first place.
Math Helper: In this exercise you will write a program to help calculate different math functions. This exercise combines the other three exercises in this week, namely, the Prime Checker, Palindrome Checker and the Three-digit Armstrong. Given a single interface, a user can specify which of the three math functions to be computed and the appropriate answer will be generated.
In the first half of the class, you learned how to build websites with HTML and CSS. The last few weeks have focused on the basics of the JavaScript language.
Finally, it's time to connect JavaScript to the HTML page.
JavaScript can change the HTML elements on the page, in response to events. In order to use JavaScript to change the HTML, you'll need to learn about the DOM: The Document Object Model. The DOM is how HTML elements are represented and accessed from JavaScript.
Once you can find, edit, and create elements from JavaScript, you'll learn how to react to events. Clicks, page loads, scroll, keyboard input, movement of the mouse – the browser knows about lots of events! You can listen for those events happening in JavaScript, and trigger an action to happen in response.
When a web browser opens an HTML page, the browser builds up a model of the document structure of the HTML file, this model is used to draw up the HTML page on the screen. This model is called the Document Object Model, commonly referred to as DOM. This DOM is available to every JavaScript program, and with it, you can make live changes to your web page. It is an object that can be used to manipulate the structure, style and content of every web page. It is represented in JavaScript by the document object. The HTML DOM document object is the owner of all other objects in your web page.
You can picture an entire HTML document as a nested set of boxes. The boxes in this analogy represents the tags.
For example, consider the HTML document below:
<html>
<head>
<title>My DOM Tree</title>
</head>
<body>
<h1>H1 in body</h1>
<p> P in body <h1>H1 in P tag</h1></p>
<p>Another p tag</p>
</body>
</html>
Given the HTML page, the browser represents the page with a data structure similar to the set of boxes shown. Each box is represented by an object which can be used to find out which html tag it represents, which other boxes and text it contains, amongst other things.
The document object gives access to all the objects on an HTML page. Its documentElement property refers to the object representing the <html> tag. The document object also has head and body properties which points to the head and body tags respectively.
The DOM is organized like a tree, in which elements are arranged hierarchically according to the structure of the document.
In Computer Science, a tree is similar to a real-life tree except that in this case, it is an upside down tree with the root above and branches beneath. The branches in a tree are referred to as nodes. Each node can have children nodes, parent nodes and sibling nodes. A tree also has leaves nodes. A leave node is a node which does not have children nodes.
The DOM object can be traversed as a tree and in this case, the document.documentElement property is the root. Nodes for elements, which represent HTML tags can have child nodes. An example of such a node is document.body.
In the DOM tree, text and comment nodes are leaves nodes beacuse they cannot have children nodes (for instance, you cannot have a tag inside a comment node).
Now, let's visualize our previous HTML example with a Tree structure.
Document
└── html
├── head
│ └── title
│ └── "My DOM Tree"
└── body
├── h1
│ └── "H1 in body"
├── p
│ ├── "P in body"
│ └── h1
│ └── "H1 in P tag"
└── p
└── "Another p tag"
As seen in the tree, the body node is a parent to an h1 node and two p nodes. These h1 and two p nodes nodes are siblings. The first p node has a text node and an h1 node as children. The last p node has a text node as a child and this is a leaf node, because it has no children nodes.
Which node is the parent node for the text node with the text "H1 in P tag"?
In this lesson, we'll review how to navigate and access different elements in the DOM. As mentioned, in JavaScript, you can access the DOM through the document object. It represents the entry point to the DOM hierarchy and provides methods and properties to navigate and manipulate the document. There are lots of DOM methods and properties available, in this lesson, we will cover a few and then give reference to the full list.
Watch Video on DOM Traversal
We'll be using the html snippet from the previous lesson for our examples.
<html>
<head>
<title>My DOM Tree</title>
</head>
<body>
<h1>H1 in body</h1>
<p> P in body <h1>H1 in P tag</h1></p>
<p>Another p tag</p>
</body>
</html>
Each element in the DOM has properties to access its parent and child nodes. The parentNode property is used to get the parent of a particular node. The general syntax for this is: element.parentNode. element here is a reference to the element for which you want to get its parent. Let's see an example:
const html = document.documentElement;
//this displays the #document node as the parent
console.log(html.parentNode)
In this example, we get the object representing the <html> tag via document.documentElement, we then query its parent node which is the document object. Try this code snippet in your console.
In this example, we get the first h1 element by using the querySelector() method , we then query its parent node, which is the body element.
We learnt previously how to use the querySelector() method. The querySelector() method allows you to select elements from the DOM using the CSS selector syntax. It returns the first element that matches the specified selector or null if no matching element is found. A closely related method querySelectorAll(), returns all the elements that match the given CSS selector.
Child nodes refer to the elements or nodes that are directly nested within another element. They are the immediate descendants of a particular parent element. Child nodes can include elements, text nodes, comments, and other types of nodes. To access the child nodes of an HTML element, you can use the childNodes property. Note that text nodes are created for whitespace between nodes, and are also seen as child nodes.
Run the given code snippet to see how the childNodes property operates. For the h1 node, it's only child is a text node, while the html node has multiple child nodes. The childNodes property returns a collection of child nodes.
const html = document.documentElement;
const h1 = document.querySelector("h1");
console.log(h1.childNodes);
console.log(html.childNodes);
To find a specific element, you can use it's unique id attribute in the html file with the document.getElementById method. The basic syntax to use it is shown.
The getElementsByTagName method is another built-in method in JavaScript's DOM API that allows you to retrieve a collection of elements based on their tag name such as <div>, <p>, or <span>. It searches for elements with a specific tag name within a given parent element or the entire document. The method returns a live HTMLCollection or NodeList that contains all the elements matching the specified tag name. You can iterate over this collection to access or manipulate the selected elements.
Let's see an example.
//Gets all paragraph elements
let paragraphs = document.body.getElementsByTagName("p");
//Get the first paragraph element
firstParagraph = paragraphs[0]
The getElementsByClassName method like getElementsByTagName, searches through the contents of an element node and retrieves all elements that have the given string in their class attribute. The method allows you to retrieve a collection of elements that have a specific class name.
Here's the basic syntax of getElementsByClassName.
const elements = parentElement.getElementsByClassName(className);
className is the name of the class to search for. It is case-sensitive. elements is usually an HTMLCollection or NodeList containing the elements that match the specified class name.
In the previous lesson, we looked at different ways we can navigate through the DOM object, document. Beyond navigating the document, we can also change or modify its structure.
The replaceChild() method is used to replace a child node with another one.
It takes as arguments two nodes: a new node and the node to be replaced. The
replaced node must be a child of the element the method is called on.
To get all the paragraph elements in the page, we can use the getElementsByTagName method.
let paragraphs = document.body.getElementsByTagName("p");
paragraphs[0].remove() will remove the first paragraph with the text One. Try this example on your VScode to see that the first paragraph gets removed.
Running the code console.log(paragraphs[0]), will show you that the first paragraph is no longer a child to the body element.
We can insert paragraph three before paragraph two by the following code: document.body.insertBefore(paragraphs[1], paragraphs[0]);
If you are inserting an already existing node, note that the node will be removed from its previous position to a new position. This is because a node can exist only in a single location in a document. Try these on your own to see how the code works.
You can also create new nodes in the HTML DOM via JavaScript code. You can create both text nodes and element nodes. Text nodes represent the textual content within an HTML document. They contain the actual text that appears between HTML tags or within an element. For example, consider the HTML snippet <p>Hello, <em>world</em>!</p>. Here, "Hello, " and "!" are text nodes. Element nodes on the other hand, represent the HTML elements themselves, such as <div> or <p>. They represent the structure and hierarchy of the HTML document. Element nodes can have attributes and child nodes.
Text nodes are created with the document.createTextNode() method. Given a string, createTextNode() gives us a text node that we can insert into the document to make it show up on the HTML page.
First, we created a new text node using the createTextNode method. Next, we added it to the body node using the appendChild() method. Try this on VScode to see your new text on the browser.
To create an element node, use the document.createElement() method. This method takes a tag name and returns a new empty node of the given type. You can then append the new node to another element node to add it to the DOM hierarchy.
// Create a new element
var newDiv = document.createElement("div");
// Set attributes, properties, or styles of the new element
newDiv.textContent = "Hello, World!";
newDiv.className = "myClass";
newDiv.style.color = "red";
newDiv.setAttribute('id', 'myid');
// Append the new element to an existing element in the document
document.body.appendChild(newDiv);
In the code snippet above, we created a new <div> element. We also set the element's textContent, className and color properties. Finally, we append the new element to the body of the html. Run this code to see the <div> element added. Additionally, navigate to the Elements pane of your DevTool to see the new <div> element and its properties.
See the example on CodePen below. As you would observe, the HTML does not have any element containing 'Hello World', but we have created this new element using JavaScript.
Events are things that happen on your web application, which the system tells you about so your code can react to them. Usually, the system produces (or "fires") a signal of some kind when an event occurs, and provides a mechanism by which an action can be automatically taken when the event occurs.
For example, if the user clicks a button on a webpage, you might want to react to that action by displaying a form to be filled in. Other examples of events include when the user chooses a key on a keyboard, when the user closes a browser window, or submits a form, when an error occurs or when a page finishes loading.
JavaScript allows you to respond to these events by attaching event handlers to specific elements or the document itself. An event handler is a block of code or function that is executed in response to an event. There are different ways to handle events.
Inline Event Handling: Event handlers can be directly attached to HTML elements using the on attribute (e.g., onclick, onmouseover). This is not recommended for larger applications due to code mixing concerns.
Traditional Event Handling: Use the DOM Level 0 event properties (e.g., element.onclick = function() {}). This approach however, only supports one handler per event per element.
Modern Event Handling: This approach uses the addEventListener method to attach event listeners. This approach supports multiple listeners for the same event on the same element, and it is the recommended approach.
The addEventListener method allows you to add any number of handlers on an element. Objects that can fire events have an addEventListener() method. Some events, such as click, are available on nearly any element. Other events are more specific, for example, the play event is only available on some elements, such as <video>.
event is a string representing the event type (e.g., "click", "mouseover").
listenerFunction is the function to be executed when the event occurs.
Let us see an example. Assume you have a button in your HTML file, and you want to configure an event listener to respond when that button is clicked.
<button>Button 1</button>
First you need to get the button:
const btn = document.querySelector("button");
Next you need to write the event handler function:
function alertBtn(){
alert("I love JS");
}
An event handler function is a callback function that defines the actions to be taken when the event occurs. It receives an event object as a parameter, which provides information about the event and its properties. To get the event object, you can modify the function as shown below.
function alertBtn(event){
alert("I love JS");
alert(event.target.tagName);
}
Finally, add the event listener to that button element.
btn.addEventListener("click", alertBtn);
Let's put all these together using CodePen:
Click the button to see what happens!
As a recap, the steps required are:
Get the element required. The target element to which you want to add the event listener.
Write your event handler function.
Use the addEventListener() method to attach the event listener to the target element.
To remove an event listener, use the removeEventListener method. The same function used to add the listener must be passed as a parameter to remove it.
Let us assume we want a particular button to only act once. A user is only expected to click the button once. Therefore, we need to remove the event listener so that no action is performed when the button is clicked more than once.
<button>Act-once button</button>
<script>
let button = document.querySelector("button");
function once() {
console.log("Done.");
button.removeEventListener("click", once);
}
button.addEventListener("click", once);
</script>
The function given to removeEventListener has to be the same function
value that was given to addEventListener. So, to unregister a handler, you’ll
want to give the function a name (once, in the example) to be able to pass the
same function value to both methods, rather than using an anonymous function.
See this example on CodePen. Unlike the previous example, here if you click the button after the first click, nothing happens. This is because the event listener has been removed.
As seen from the previous examples, we can get the event object that was fired from the event handler function.
The information stored in an event object differs per type of event. The event’s type property always holds a string identifying the event (such as "click" or "mousedown"). In the alertBtn function, insert the code: alert(event.type);. This will display click indicating that a click event occurred.
The target property of the event object refers to the element on which the event was originally triggered.
In this week, there are several exercises for you to engage with. Some of which are optional and others mandatory. You are encouraged to attempt all the exercises, however, you are expected to submit the mandatory exercises to Gradescope.
Your final project will be a website you design and create with a team.
You’ve learned a ton about HTML, CSS, and JavaScript in this course. The final
project is your chance to build a website of your own design from scratch.
There are few requirements. You must use the knowledge you learned in the
course, as outlined in the rubric below.
- valid HTML, CSS, JS - no errors - nothing on the site appears incomplete
10 pts
Site uses appropriate HTML elements
- Should use at least 10 different elements - Elements should be used for their intended purposes
10 pts
Site is styled effectively
- Color palette creates contrast - Appropriate spacing between elements - Text is styled for readability
20 pts
Site uses JavaScript for interactions
- Event listeners trigger actions on the page - Trigger at least 10 different actions. Examples: - Change the displayed text of an element - Change an element's colour - Change an element's background colour - Create a new element - Delete an existing element - Hide an element - Display an element
Your team gets to decide the topic for your final project. The challenge is to
choose a design that is exciting to you, but is not so big that it’s
overwhelming or impossible to complete.
Here’s some guidelines that can help you pick an exciting project you’ll be
able to complete.
Your final project should be more advanced than the exercises you've done. It should be a complete website that achieves a goal.
Don’t plan to learn a whole new technology for the final project. Plan to use
mostly what you’ve already learned (with a little bit more Googling for the
things you run into along the way).
You’ll should figure out what works best for your team. The best teams communicate clearly up front, so that there isn’t confusion about what is going on. Try to agree on how you’ll communicate (Discord, Whatsapp, email, or something else), and when you’ll get together to work on the project.
It may be helpful to create a design doc. Using Google docs or a text file in Repl.it, write down your ideas. You might include links, images, drawings, and text that helps to explain what you are planning to build.
A design doc can also help you track what work you’ve done, and what work is left to do.
You've seen JavaScript basics, and how to use JavaScript to make changes on webpages in response to events. But, JavaScript is much bigger than what you can write on your own in a webpage!
JavaScript can run outside the browser. The most used outside-of-browser JavaScript runtime is called Node. It can be used much like Python -- from the terminal, as a scripting language, or on a server.
JavaScript also has libraries of code that you can use, called modules. You'll learn how to load code from modules into your own projects. You'll also see how you can use HTML and CSS libraries and frameworks.
Finally, you'll get a glimpse of how the practice exercises have worked all this course, with a look at testing.
Did you know that JavaScript can run outside of a browser? Well, yes. Although JavaScript began as a simple scripting language that only runs behind web pages on browsers, it has grown to become a versatile programming language that can be run outside of a browser environment.
In the world of web applications, JavaScript can also run on the server-side, to program the back-end of web applications. With the help of independent JavaScript runtime environments, it is possible to run JavaScript outside of a browser, on the server. Such runtime environments include Node.js, Deno, and Bun. Node.js is the most popular at the moment (early 2023).
Node.js is an open-source, cross-platform JavaScript runtime environment. It was originally written in 2009 by Ryan Dahl. It is very popular and quite easy to use.
Next, we'll have a sneak peek of how to run JavaScript on the command prompt using Node.js.
Note: You may have already installed node as part of your laptop setup. Read through the installation below to see the steps, then check if you have node installed by running node -v in a command prompt or terminal.
Download and install Node.js. Visit the download page to download the relevant installer for your operating sysytem. It is usually preferred to download the long-term support (LTS) version, as they are more stable. To check if you already have it installed, type in node -v into your terminal/command prompt. If you have it installed, it should display the version you currently have installed. For example v18.16.1. Note that you might have a different version installed.
Get your script, the JavaScript file you want to run. It should be a standalone file, without referencing anything related to the window or browser.
Run it! To do this, open up the terminal, navigate to the directory your file is located and use the node command.
NPM stands for Node Package Manager. It is the default package manager for the Node.js runtime environment. It consists of both a command line client, called npm CLI and an online database of packages, known as the npm Registry.
The online database hosts thousands of free and proprietary packages that you can download and use.
The command line tool, npm is installed on your computer when you install Node.js. It can be used to download, install and manage packages.
npm installs packages in a folder called node_modules. Because there are so many dependencies, the folder can get really big. It's also usually not something you want to store in git, or upload with the rest of your code. Instead, you can tell git to ignore the node_modules folder, and when you share your code, someone else will install the dependencies using npm.
npm keeps track of which libraries your code depends on in the dependencies key within the package.json file.
So that the version of each dependency is the same, npm stores a lock file with all the versions of each dependency. For npm, this is called package-lock.json.
In this class, we use an alternative to npm called pnpm ("performant npm"). It has all the same features of npm, with a few exceptions:
instead of downloading packages directly to the node_modules folder, it downloads them to a central folder that it manages
it puts a link to the version of the package in the central folder into node_modules, so that there's still a copy of the package for your code to use
that means that it doesn't need to download any package that is already installed on your computer. npm would download a copy (and use lots of data) every time you install the same library in a different project.
it calls the lock file pnpm-lock.yaml.
Since we have lots of projects that use the same packages, pnpm can save you a lot of data. It can also work when you don't have a solid internet connection or are offline.
Note: Replacing npm with pnpm
Any command that you see online that uses npm, you can use pnpm instead. You might see other package managers mentioned online, like yarn. You can typically use pnpm instead when you see another package manager mentioned.
To download and install a package, open your command prompt. Type in pnpm install followed by the name of the package to be installed. install is the pnpm command used to install packages.
When it installs a package, pnpm creates a folder called node_modules, where it stores the installed package. If this folder already exists, it simply adds the newly installed package to the folder.
Next, let's install a package called is-lower-case. To find out about this package and how to use it, search for it on the npm Registry.
To install it, type the following command on your command prompt: pnpm install to-lower-case
Once you have the package installed, you can then use it. To use the to-lower-case package in your JavaScript file, type in the following line of code:
var packageAlias = require('to-lower-case')
The line of code imports the to-lower-case package and assigns it to a variable called packageAlias. Feel free to replace the variable name to any name you want, and the package name to whatever package you want to use.
The require() function used is a built in function in Node.js that is used to import modules or packages into a JavaScript file. The argument given to the function is simply the package to be imported.
After importing the package, we then use the variable name, packageAlias in this case to access the functions exposed by the package.
In the to-lower-case package, there is a function called isLowerCase which we can use.
var packageAlias = require('is-lower-case')
console.log(packageAlias.isLowerCase("PascalCase"))
Note: import and es modules
require has been the keyword to load a node module since the introduction of node. Now, there is a new keyword import that loads modules slightly differently. Usually, you can use require without any trouble, but you may see import in other people's code, and the ecosystem is gradually moving to use import instead.
👉🏿 Try it:
Create a file with the code snippet above and run it using node. false should be printed to the console because the string PascalCase passed to the function is not in lower case.
You can install, import and use any of the packages that are available in the npm Registry.
In programming, a module is a self-contained unit of code which encapsulates related variables, functions, or classes.
When you have a large project, it is usually great to split up the code into smaller modules which can be reused throughout the project. Each module will focus on a specific functionality or aspect of the larger program. This ensures code organization, encapsulation of related code within a single unit, reusability and modularity. Modularity ensures that you can isolate and test individual components of a program independently.
In JavaScript, a module can be exported, and then imported in another file for reuasbility. It is important to note that in JavaScript, there are two different module systems used. They are the ES modules (ECMAScript modules) and the CommonJS. ES modules are native to modern browsers and can be used directly in broswer environments that support ES6 or later. CommonJs modules on the other hand are not natively supported in browsers. This is because they were primarily designed for server-side environments such as Node.js.
In a future lesson on testing, you will see how to export and import modules using the CommonJS syntax. CommonJS uses module.exports to export a module and require() to import a module. You might have notices this syntax in your weekly practice exercises. It is good to note that Node.js supports both CommonJS and ES modules.
In this lesson, our focus will be on ES Modules. ES modules are the standardized module system for JavaScript.
ES Modules use import and export statements to import and export functionality between modules. This is closer to the syntax you will find in other programming languages.
To get access to a module in another script, the module has to be exported. This is done using the export statement. There are two ways to use the export statement.
Use the export statement in front of any items you want exported. You can export functions, var, let and const variables. Using this approach, you can only export top-level items. You cannot use export inside a function.
export const name = "Olaperi";
export function hello(name){
console.log("Hello " + name);
}
The second approach is to use a single export statetement to export all the items you want to export at once. This is done at the end of the module file. To do this, you specify your export statement, then a pair of curly brackets that contains a comma-separated list of features to export.
Once you have exported some features from a module, to use them in your script, you need to import them. The import statement is used to do this.
import {name, hello} from "./modules/module1.js"
The code snippet shows how we will import the exported name and hello features. In this example, we are assuming the module is in a file called module1.js and the file is inside a folder called modules. The script and the modules folder are both in the same folder.
Libraries and frameworks are tools that provide pre-built features and functionalities that can be used to simplify and speed up the process of developing web applications. Libraries are collections of reusable code snippets, functions and components. Frameworks are sets of tools and components that offer a complete structure for building applications. Frameworks often follow specific design patterns and architectural principles, and they usually provide a foundation for organizing and managing your application. In web application development, libraries and frameworks help to handle common tasks, such as layout, responsiveness, form validation, and DOM manipulation. They make it possible for developers to focus more on application-specific logic and functionality.
There are different HTML, CSS and JavaScript libraries and frameworks that exist. Most times, these frameworks are not limited to either of HTML or CSS, they often include components from the different technologies, since they are all interconnected in web development.
Examples of libraries used in web application development include jQuery, D3.js, React, Vue.js. You can visit these websites to find out more about them and how to use them. In this lesson, we'll review an example using jQuery.
jQuery is a fast, lightweight, and feature-rich JavaScript library that simplifies HTML document traversal, event handling, DOM manipulation, and animation. It was introduced in 2006 and has since gained widespread popularity and usage in web development.
To use jQuery in your project, you can either download the library and include it in your HTML file or reference it from a CDN (Content Delivery Network). Once included, you can begin using jQuery's functions and methods by writing JavaScript code that interacts with the jQuery object ($) and the DOM elements selected using jQuery selectors. It makes DOM manipulation and event handling simpler and faster.
Watch Video on jQuery
The code pen below shows an example of how to use jQuery.
The goal of the example is to hide the header element when you click the Toggle button. To do this, we are using a jQuery function called toggle().
To use any function from jQuery, you have to make the jQuery library available in your HTML document. In this example, we did that with the <script> tag, as in <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>, making the jQueryCDN as the source.
The $(document).ready() function is used to ensure that the jQuery code is executed once the document is fully loaded. Inside the click event handler, the $('#myHeading') selector is used to target the heading element with the id myHeading. The .toggle() method is then used to toggle the visibility of the selected element.
Feel free to explore the jQuery Library for many more ready to use functionalities for your application.
Bootstrap is a popular CSS framework that provides a responsive grid system, a collection of pre-styled components, CSS and JavaScript utilities. Bootstrap includes HTML and CSS based design templates for typography, forms, buttons, tables, navigation, modals, image carousels and many others. Basically, it makes the job of designing your application faster and simpler, minimizing the amount of CSS code that you have to write. With Bootstrap, you can build fast and responsive sites.
A responsive website is one that automatically adjusts to look good on all devices, from small phones to large desktops.
To use Bootstrap, just like any other framework or library, you need to include the Bootstrap CSS and JavaScript files in your HTML document. You can either download Bootstrap and host the files locally or include them from a CDN (Content Delivery Network). All these details and options are right on the Bootstrap home page.
Throughout this course, you've had sets of weekly exercises to work on, and you have had to run some tests on your exercises. Well, in this lesson, you'll have an idea of how those tests are written, and how to write your own tests.
But first, what is testing? Although we have used testing in this course to evaluate your work, testing goes beyond that. Testing of any code refers to the process of evauating the functionality, correctness and performance of your code, through the execution of tests. After writing any software code, it is important to check that your code behaves as expected.Testing helps you to catch bugs that exist in your code and verify that your code actually performs as expected.
There are different approaches to testing, one of these is called Unit Testing. Unit Testing refers to the practice of testing individual units of code in isolation. In JavaScript, units of code can be functions or modules. Unit tests verify the behavior of specific units to ensure they produce the expected output for a given set of inputs.
In JavaScript, there are different testing libraries and frameworks, that help to simplify the process of writing and running tests. Some of these include Jest, Mocha, Jasmine and QUnit.
In this course, the tests for your weekly exercises have been written using Jest. Next, let's have a look at the Jest framework.
Type in pnpm init -y. This gives us a new project folder with a package.json file to get started.
Next type in pnpm i --save-dev jest to install Jest.
In the package.json file created, locate the code snippet below:
"test": "echo \"Error: no test specified\" && exit 1"
Change the value of "test" to become "jest", as shown below:
"test": "jest"
Create a file called sum.js. Copy and paste the code snippet into that file. This is the module we want to test. It contains a function that sums two numbers. We'll test the sum functionality if it performs as expected.
function sum(a,b){
return a + b
}
//this line of code exports our sum function using the CommonJS module syntax.
module.exports = sum
Create a file in the same folder as sum.js. Name this file sum.test.js. Copy and paste the code snippet into the file.
//this line of code imports the sum function from the sum.js file
// so that we can test the function
const sum = require('./sum')
test('testing the sum function', () => {
expect(sum(1,2)).toBe(3)
})
The test function is used to write tests in Jest. The first argument is a string describing the test. The second argument is a function that gets called to run this test. This is what helps to check our expected result. We use the expect jest test function to check the expected values. .toBe() checks that what the function returns equals to 3.
To run your tests, type in pnpm test on your terminal. Jest will automatically detect and execute the test files matching the pattern *.test.js in your project directory. It will provide a summary of the test results, indicating whether each test passed or failed.
We do not expect you to become a test guru just yet, but this is just to give an idea of what testing is about.