Javascript
Javascript
Javascript
Welcome To Programming!
Up until now, we have built the structure of a web page (HTML) and
designed it (CSS). However, web sites are much more than that.
An important part of web development is making the web pages
interactive.
That is the role of JavaScript. So during this Super Skill, we are going to:
Since their invention in the 1950s, computers have revolutionized our daily
lives. Calculating a route from a website or via GPS, booking a train or an
airplane ticket, or video calling and chatting with friends on the other side
of the world are all actions we can do with the click of a button. All of that
is possible thanks to computers.
Let’s take the term “computer” in its broadest sense. It is a machine that
can perform arithmetic and logical operations. It could mean either a
desktop or a laptop computer (PC, Mac), a computing server, or a mobile
device like a tablet or a smartphone.
They cannot learn, judge, or improvise (if you have watched Terminator,
you might disagree with this.). They simply do what they’re told to ! Their
value comes from how they can quickly compute and process huge
amounts of information.
A computer often requires human intervention. That’s where programmers
and developers come in!
They write programs that give instructions to a computer.
Would you:
Pick up every book on the shelf until you find what you need?
Pick up books randomly until you find the right one?
Try to find it by alphabetical order?
Use the library’s search guide as a reference?
Bear in mind that these are all ways to eventually achieve the goal. Also,
each method highlighted above can be broken down into smaller steps
that cumulatively achieve the task at hand. For starters, you would have
to:
Walk up to the shelf.
Pick up the first book.
Check if it matches what you’re looking for.
If it does, yayyyyy!!! (that was quick).
If it doesn't, you drop the book.
pick up another one and check again.
This process is continuously repeated until you find the desired book. This
step by step break down of the whole process into actionable steps is what
we call pseudocode in computer programming.
Introduction To Algorithms
The four ways we considered, however, can be examined carefully to
determine the most efficient way. Specifically, by calculating/estimating
the time and energy spent in the course of searching through each
method. The most optimal solution will therefore be the one that
consumes the least amount of time and energy.
Assessment: Quiz
An algorithm doesn't have to be supplied with external inputs.
True False
Not every single step of the algorithm has to generate a correct output as long as the
main output is correct.
True False
The efficiency of an algorithm is defined by how much time is spent and how much
energy & resources are consumed in solving a given problem.
True False
Introduction To JavaScript
Introduction To JavaScript
JavaScript is the most widely used scripting language on Earth. It has the
largest library ecosystem of any programming language.
JavaScript is the core language of the web and the only programming
language that can run in all major web browsers.
The programs in JS are called scripts. They can be written right into a web
page’s HTML and run automatically as the page loads.
Add new HTML to the page, change the existing content, modify
styles.
React to user actions, run on mouse clicks, pointer movements, key
presses.
Send requests over the network to remote servers, download and
upload files (so-called AJAX and COMET technologies).
Get and set cookies, ask questions to the visitor, show messages.
JavaScript was standardized in 1997 under the name ECMAScript.
Since then, the language has undergone several rounds of
improvements to fix awkwardness and support new features.
This course uses the ES2015 standardized version of JavaScript, also
called ES6.
This version brings a lot of interesting novelties to the table. It is
now well-supported by most environments and platforms, starting
with web browsers (more details in this compatibility table).
Let’s print the “Hello World!” line in the console using JavaScript with this
one line of code.
Go to this link (It's a code editor online.) In JavaScript window, delete all
the code and copy-paste the following code.
Solution
Reorder the steps you'll take to create your first JavaScript:
In your favorite text editor, open the file as an .html file.
Click in the empty line just before the closing </body> tag and type <script>.
Press the return key to create a new blank line, and type: alert('I promise not to hack
the planet with the new skills I’m about to acquire');
Launch a web browser and open the .html file to preview it.
PS : It’s highly recommended that they are inserted right before the
</body> tag, so that the page can load all the other HTML elements
before the JS.
<script language="javascript">
</script>
Solution
Reorder to indicate the ideal script tag position:
<head>
</head>
<body>
</body>
External JavaScript
We can also place scripts in external files, this is practical when the same
code is meant to be used by different web pages, and most importantly,
for respecting the “Separation of Concerns” design principle.
Thus, we will keep our HTML files for structures, and our logic part will be
kept in files of their own. In our case, they will be JavaScript files that will
have the extension .js.
To be able to use these external scripts, we’ll put the name of the script
file in the src (source) attribute of a <script> tag like this:
PS: The script will behave as if it was located exactly where
the <script> tag is located.
<script src="myScriptFile.js"></script>
Assessment: Quiz
Placing scripts in external files:
True False
The script tag must be placed in the head tag.
True False
console.log(visitorName)
console.log
Behold the console.log()!
What we’ve studied is all fine and dandy, but remember that
mighty console.log()? Well that’s going to be your best ally and companion
during your upcoming journey in the valley of JavaScript.
variable content
The console.log method is used to display a message to the window screen.
True False
The principal role of console.log method is to help developers in the debugging
process.
True False
Comments in JavaScript
Commenting allows us to write stuff that will be ignored by the interpreter
and won’t be run as code.
To achieve this we use:
“//” to comment anything on the same line after the double slash.
“/*” & “*/” to comment multiple lines.
var a = 2 + 2 // I’m a single line comment
/*
And I’m a multi-lines comment,
Anything in here will be ignored by the Javascript
Interpreter.
var b = 3 + 3
*/
Assessment: Quiz
In JavaScript, we can write comments using: (Select only one answer)
True False
Comment can be written only in one line.
True False
PS: Notice how typeofnull incorrectly prints “object”? Well that’s a bug in
JS. Which brings us to the second kind of data types in JavaScript:
We’ll be covering objects (& arrays) in more detail later on in this course.
For now, let’s simply keep in mind that Object literals can encapsulate a
multitude of data, enclosing it in a tidy package, and having the structure
shown in the Code Box.
var person1 = {
name: “foulan”,
age: 9000,
isStudent: true
Assessment: Quiz
The following code will print to the console: number
1
console.log(typeof('Hello'))
True False
The string in JavaScript is only represented between single quotation mark ( ‘ ).
True False
The boolean data type can have only true or false.
True False
Arithmetic Operators
Dealing with integers is straightforward. You have the four arithmetic
operations ( +, -,*, /*) available
for addition, subtraction, multiplication, and division respectively.
// 7
console.log(7%5);
// 2
console.log(5**2);
// 25
NaN:
The division 0 / 0 or using mismatching types creates a special number
called not a number or NaN.
Infinity Type:
JavaScript registers very large numbers as infinity. For instance, ten to the
power of 309 is represented as infinity. Division by zero also yields infinity.
// NaN
console.log(0 / 0);
// Infinity
console.log(1 / 0);
console.log(Infinity * Infinity);
console.log(1e+309);
console.log(num)
num ++
console.log(num)
num --
console.log(num)
Assessment: Quiz
What should be the initial value of num for the result to end up equal to 64:
var num
var num2 = 5
num++
num2--
var sum = num + num2
var result = sum ** 2
console.log(result)
0 1 2 3
The modulo operator is represented by:
% $ mod
NaN refers to Not a Number.
True False
Assignment Operators
An assignment operator assigns a value to its left operand based on the
value of its right operand. The first operand must be a variable and basic
assignment operator is equal (=), which assigns the value of its right
operand to its left operand. That is, a = b assigns the value of b to a.
var a = 5 // assigned a value of 5 to a
console.log(c) // prints 5
Assignment Operators
We can combine arithmetic operators with the regular assignment
operator "=" and create shorthand annotations for standard operations:
a +=b a=a+b Adds 2 numbers and assigns the result to the first.
a *=b a=a*b Multiplies 2 numbers and assigns the result to the first.
a /=b a=a/b Divides 2 numbers and assigns the result to the first.
a %=b a=a%b Computes the modulus of 2 numbers and assigns the result to
the first.
var a = 5
var b = 7
a += b
console.log(a) // prints 12
Assessment: Quiz
What does result evaluate to?
var a = 3;
a += 2;
a -= 1;
a **= 2;
a /= 4;
a %= 3;
var result = a;
0 1 Infinity NaN
An assignment operator assigns a value of left operand to the right operand:
True False
5 1 0
Comparison Operators
Remember booleans values? Booleans are either true or false.
We can compare two numbers with >, >=, ==, ===, <=, <.
(we will discuss the difference between == and === in the next slide.).
For the rest of the operators, the result of the comparison is a boolean.
The ! operator:
The ! operator negates its operand. True becomes false, and false
becomes true.
console.log(5 <= 5); // true
Not equal (!=) x != y Returns true if the operands are not equal.
Strict equal (===) x === y Returns true if the operands are equal and of the
same type.
Strict not equal (! x !== y Returns true if the operands are not equal and/or
==) not of the same type
Greater than (>) x>y Returns true if the left operand is greater than the
right operand..
Greater than or x >= y Returns true if the left operand is greater than or
equal (>=) equal to the right operand
Less than (<) x<y Returns true if the left operand is less than the right
operand
Less than or equal x <= y Returns true if the left operand is less than or equal
(<=) to the right operand
Before we continue, let’s explore in detail the notions of truthy and falsy.
console.log(Boolean(null));
console.log(Boolean(NaN));
console.log(Boolean(""));
console.log(Boolean(0));
console.log(Boolean(false));
Assessment: Quiz
What does the following code print out?
var x;
console.log(Boolean(x));
true false
var x = 5;
var y = "5";
console.log(x != y);
true false
true false
Logical AND a && Returns the first value if falsy, otherwise returns the second
(&&) b value whatever it may be.
Logical OR a || b Returns the first value if truthy, otherwise returns the second
(||) value whatever it may be.
var x = 1 // x is truthy
var y = 0 // y is falsey
console.log(z || x) // prints 1
var y = 10;
var z = 5;
Assessment: Quiz
What does the following code print out ?
true false
The && operator returns the first operand if it is true or the second operand if the
first is false.
True False
The || operator returns the first operand if it is true or the second operand
if the first is false.
True False
String Operators
When working with JavaScript strings, oftentimes we need to join two or
more strings together into a single string. Joining multiple strings together
is known as concatenation.
This, however, can get tedious at times. Luckily for us and thanks to ES6,
there’s a new way to concatenate strings.
Template Strings:
Template Strings use backticks (`` ) rather than the single or double
quotes we're used to with regular strings.
Assessment: Quiz
What does the following code print out?
var x = "Hello"
var y = "World"
console.log(x + y)
True False
The template string can give us the same result as the + operator.
True False
The return statement returns the value of the function. When calling
the add function with arguments a and b, it computes the value a+b and
returns it.
Example:
function add(a, b) {
return a + b;
Solution
Rearrange the segments to create a function that takes 2 arguments and returns
their sum:
function sum(a,b){
var sum = 0;
sum = a + b;
return sum
User-Defined Functions
Function declarations:
In most programming and scripting languages, there are some built-in
functions that are kept in a library. The real interesting part is that we can
write our own functions, (also called 'User Defined Functions' or 'UDF'.) to
perform specialized tasks.
}
return a - b;
To sum it up, we can declare a function in two ways. Let’s say we want to
define a function that calculates the cube of argument passed to it, you
can do it in one of two ways:
PS: In arithmetic and algebra, the cube of a number n is its third power
the result of the number multiplied by itself twice: n3 = n × n × n.
The function "cube" takes one argument, called n. There is only one
JavaScript statement in function body which instructs to return the
argument (n) of the function after multiplying it by itself twice. Here, the
return statement returns the calculated value.
// Example 1: (Classic Function Declaration)
function cube(n){
return n*n*n;
Function Parameters
Parameters are variables listed as a part of the function definition.
Arguments are values passed to the function when it is invoked.
return a + b;
console.log(add(0,1)) // prints 1
return a + b;
console.log(add())
Note: When a function does not return anything, its return value
becomes undefined
// 1_Defining some functions
function add( a, b ){
return a+b;
var subtract=function( a, b ) {
return a-b;
var multiply=function( a, b ) {
add(2, 3) // returns 5
subtract(2, 3) // returns -1
True False
A function is invoked by calling its name followed by parentheses. If arguments are
passed, they should be added inside the parentheses..
True False
The If Statement
The most basic structure of a conditional execution is:
if(condition){
Instruction 1;
Instruction 2;
Etc..;
}
Let’s write a function that checks if the argument that’s being passed to it
is a number:
// 1_Defining the function
function checkIfNumber( x ){
Assessment: Quiz
if(EarthIsRound){ return truth; } // truth is :
Earth is flat, i’m woke There’s no Earth, we live in a simulation Yep, this is
how you write conditions in JS
The code inside an if block will be executed only if the condition is truthy
True False
Inside an if block we can write only one instruction
True False
Notice that the else branch is only executed if the original condition is not
true.
// 1_Defining the function
function checkIfNumber( x ){
} else {
Solution
Order this code:
if (condition) {
else {
So, if the first condition fails, it will test the next else if condition, if that
fails too, then the next one will be tested and it will continue sequentially
until all the else if fails and it will finally execute the else statement.
The following function (decodeColor) uses this logic to print out a color
depending on the code (number) being passed to it as an argument.
// 1_Defining the function
if ( code === 1 ) {
console.log( 'Red' );
console.log( 'Yellow' );
console.log( 'Green' );
} else {
Solution
Order this code:
if (condition1) {
lines of code to be executed if the secondary condition is true AND initial condition is
false}
else {
We have a variable inside the switch. This variable may have values. We
jump to the case label for which the passed argument is equal to the label
value. Then we start executing the code.
Otherwise there’s always our default which will handle any other scenario
that is not covered by our cases.
// 1_Defining the function
switch( code) {
case 1:
console.log( 'Red' );
break;
case 2:
console.log( 'Yellow' );
break;
case "x":
console.log( 'Green' );
break;
default:
Ahaa! You must’ve noticed that we used a break there. Now why is the
break so important?
Simply put, if there was no break at the end of the code segment
belonging to a label, execution would continue on to the next code line. It
does not matter that it is now under another label. Code just continues
executing everything after the first valid scenario. Let’s try it in the code
box, we will execute the same function as before but without the break(s)
now.
This is why we have a break statement at the end of each code segment
belonging to a label. The break statement jumps out of the
closest switch statement, and our program continues execution after
the switch statement.
// 1_Defining the function
switch( code) {
case 1:
console.log( 'Red' );
case 2:
console.log( 'Yellow' );
case "x":
console.log( 'Green' );
default:
// Green
// Unknown code
That being said, we can still omit the break if we’re going to use
the return statement instead.
The return statement will only execute what’s valid for a given
scenario/case and then exists the switch statement without executing the
rest of the lines inside of it (the switch statement and the rest of its cases).
// 1_Defining the function
switch( code) {
case 1:
return 'Red';
case 2:
return 'Yellow';
case "x":
return 'Green';
default:
/*
*/
Assessment: Quiz
Is this code correct?
var a= 3
switch (a) {
case 4:
alert( 'Exactly!' );
break;
default:
alert( "I don't know such values" );
break;
case 3:
alert( 'Too small' );
break;
case 5:
alert( 'Too large' );
break;
}
True False
The switch statement can replace the if else statement.
True False
The break keyword is used to break from the switch statement.
True False
while (condition){
Statement(s)
}
The variable i keeps track of how many times the loop is executed.
First the JavaScript interpreter examines the condition in the while loop.
As i is 0 and numbers.length is 10, we conclude the condition to
be true.
If the condition is true, we execute the body of the while loop. So we
iterate through the array and sum up all elements inside, while
incrementing the loop variable ‘i’ with 1.
Then we compare 1 against the length of the array, 10. As 1 is smaller
than 10, we execute the loop body again. The sum variable now stores 19
+ 65 = 84. The value of i becomes 2.
We continue this until i becomes 10. Then we realize the condition i <
numbers.length becomes false. Once the condition of the while loop
becomes false, we continue with the code after the while loop.
// Let’s sum the values of a small array
var sum = 0;
var i = 0;
sum += numbers[i];
i += 1;
}
console.log(sum);
// prints 115
Assessment: Quiz
"while" iterates until the specified condition is false ?
True False
The while loop should execute the statement inside its body at least once.
true false
Is the following code correct?
var i = 0;
while (i < 5) loop {
console.log(i)
}
i++
true false
var sum = 0;
var i = 0;
do {
sum += numbers[i];
i += 1;
console.log(sum);
// prints 115
PS: We mainly use do-while loops for input validation. The user inputs a
value, then we check its validity. Try to keep this in mind for when we
reach the DOM part of JS.
This is where the do-while loop makes sense, because we can be sure we
need to enter data at least once. In the example summing-up array
members, using the do-while loop is technically possible, but it does not
make sense, because the simple while loop is easier.
Even Though do while loop and While loop look similar, they differ in their execution:
The while loop tests the condition at the beginning of the loop, and if the condition is
True, statements inside the loop will execute. It means that this loop executes the
code block only if the condition is True At the end of the loop, the do-while loop tests
the condition. So, it executes the statements in the code block at least once even if
the condition Fails.
True False
A for loop's third statement has to always be with the ++ increment operator.
True False
How many times does the following loop run?
var i = 5;
for (; i < 5; i++) {
console.log(i);
}
var sum = 0;
sum += numbers[i];
}
console.log(sum)
// prints 115
var sum = 0;
sum += value;
}
console.log(sum)
// prints 115
break exits the closest loop it is in, and continues with the next command.
continue skips and jumps out from the loop body, and jumps back to the
condition of the loop.
// Let’s sum every second element of the numbers array:
var sum = 0;
if ( i % 2 == 0 ) continue;
sum += numbers[i]
}
console.log(sum);
// prints 78
/*
We’re using continue here just for the sake of the example.
*/
/*
*/
var sum = 0;
sum += numbers[i];
if ( sum >= 100 ) {
break;
}
}
console.log(sum)
// prints 103
Introduction To Arrays
Arrays provide us with a way to create and maintain a list of data.
An array is an ordered list of items. Even better, these items don’t have to
be the same type.
// Declaring an array called storage containing 3 items of different
types:
// Accessing elements
console.log(storage[0]); // prints 1
// Array length
console.log(storage.length) // prints 3
Accessing elements
Each element of the array can be accessed using an index starting from
zero. The syntax for indexing is shown in the Code Box.
In the second example, we indexed out of the array. As we indexed
beyond the length of the array, the program returned undefined for
storage[6].
Array length
Arrays have lengths reflecting how many items they contain. Just keep in
mind that to access the last element of an array we will have to use
arrayName.length -1 as the index, (remember array indexes start counting
from 0). And anything beyond that will return undefined.
Assessment: Quiz
Use the console.log() method to display the rooster from the following array:
True False
The array start index is 1.
True False
console.log(days);
days.push( 'Saturday' );
console.log(days);
days.unshift( 'Sunday' );
console.log(days);
days.pop();
console.log(days);
days.shift();
console.log(days);
We can delete any element from the array.The value undefined will be
placed instead of this element.
Also, the values of an array can be set using their indices, and equating
them to a new value. We can overwrite existing values, or add new values
to the array. The indices of the added values do not have to be
continuous.
var days=['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'];
console.log(days);
delete days[2];
console.log(days);
days[2] = 'Wednesday';
console.log(days);
delete days[7];
console.log(days);
Assessment: Quiz
In the given array, determine the output printed to the Javascript console, by:
console.log( array[3] ); (All questions are part of the same program. Each instruction
in every question is in sequence with the previous instructions.)
32 9
In the given array, determine the output printed to the Javascript console, by:
console.log( array[7] ); (All questions are part of the same program. Each
instruction in every question is in sequence with the previous instructions.)
Undefined 2
Introduction To Objects
Objects in JavaScript are standalone entities that can be likened to objects
in real life. For example, a book can be represented as an object in JS,
which you would describe by its title, author, number of pages, and genre.
Similarly, a car might be an object that you would describe by
its color, manufacturer, model, and horsepower.
Objects are an integral and crucial part of most JavaScript programs. For
example, a user account object may contain data such as usernames,
passwords, and e-mail addresses. Another common useful case is a web
shopping platform’s shopping cart that could consist of an array of many
objects containing all the pertinent information for each item, such as
name, price, and weight and shipping information. A to-do list is another
common application that might consist of objects.
Fill in the blanks Solution
The object is a complex data type that allows you to store collections of data. An
object contains properties, defined as a key-value pair. A property key (name) is
always a string, but the value can be any data type, like strings, numbers, booleans,
or complex data types like arrays, function and other objects.
Creating an Object
There are two ways to construct an object in JavaScript:
Creating an Object
Let’s create an example object, contained in the variable gimli, to describe
a character.
Our new object is gimli, which has three properties. Each property
consists of a name:value pair, also known as key:value pair. Weapon is
one of the property names, which is linked to the property value "axe", a
string. It has one method, with a method name of greet and its value
consists of the function’s contents.
PS: Within greet, you may notice the this keyword. When using this inside
of an object, it refers to the current object, in this case gimli.
// Initializing a gimli object
var gimli = {
name: "Gimli",
race: "dwarf",
weapon: "axe",
greet: function() {
},
};
console.log(gimli)
// PS: This output may render differently depending on what console you
are using, but you should notice that all of the values passed to the
object are shown in the output.
Assessment: Quiz
Remember the adam object from the last assessment? lets add to it a method greet
that returns the string “Hi, my name is Adam”:
var adam = {
name: "Adam",
age: 18,
wasExpelledFromHeaven: true,
//...your answer here...
}
True False
An object method is a function that objects can perform.
True False
var gimli = {
name: "Gimli",
race: "dwarf",
weapon: "axe",
greet: function() {
},
};
// Retrieving the value of the weapon property using the dot notation
In order to retrieve an object method, you simply call it in the same way
you would call a regular function, just by attaching it to the object
variable.
// Initializing a gimli object
var gimli = {
name: "Gimli",
race: "dwarf",
weapon: "axe",
greet: function() {
},
};
console.log(gimli.greet());
We can also add a new method to the object by using the same
process. We can then call the newly created method the same way we did
before.
// Initializing a gimli object
var gimli = {
name: "Gimli",
race: "dwarf",
weapon: "axe",
greet: function() {
};
gimli.age = 139;
gimli["age"] = 139;
gimli.fight = function() {
console.log(gimli)
console.log(gimli.fight());
What you should keep in mind at this point, is that through the assignment
operator =, we can also modify the properties and methods of a JavaScript
object.
// Updating weapon from axe to battle axe
console.log(gimli.fight());
// prints "Gimli attacks with an epic battle axe."
Assessment: Quiz
The value of an object property can’t be modified.
True False
After creating an object, we can add a new property to it.
True False
Is the following code correct?
var gimli = {
name: "Gimli",
race: "dwarf",
weapon: "axe",
greet: function() {
return `Hi, my name is ${this.name}!`;
},
};
gimli.age = 200;
True False
The delete operation returns true if the property was successfully removed
or if it was used on a property that doesn't exist or else it will return false.
/!\ In the output below, the weapon name and its associated value (“axe”)
are no longer available, confirming that we have successfully deleted the
property.
// Initializing a gimli object
var gimli = {
name: "Gimli",
race: "dwarf",
weapon: "axe",
greet: function() {
},
};
console.log(gimli);
Conclusion
JavaScript RECAP
Time to do a victory dance! We have made amazing progress in our
journey through web development.
Buckle up and wear your seatbelts for this next part! The adventure is still
in its beginnings!
DOM
What is DOM?
What is DOM?
In the last skill, we have learned the basics of JavaScript. But, we have
never explored the relationship between JavaScript and the web page.
Therefore, in this Super Skill we’ll be answering these questions:
What is DOM?
How to access DOM elements?
How to manipulate the DOM elements? What are events and how to treat
them in JavaScript?
How to treat form in JavaScript?
As a matter of fact, the web browser creates a DOM of the webpage when
the page is loaded.
DOM Selectors
DOM representation
JavaScript is most commonly used to get or modify the content or value of
the HTML elements on the page. As well as applying different effects like
show, hide, animations etc... But, before you can perform any action we
need to find or select the targeted HTML element.
Here is a definition before we dive any deeper into the course:
Document interface represents any loaded web page in the browser and
serves as an entry point into the web page's content and that exactly is
the DOM tree. The DOM tree includes elements such as <body> and <table>,
among many others. It provides general functionality to the document, like
how to obtain the page's URL and create new elements in the document.
<!DOCTYPE html>
<html lang="en">
<head>
<script>
console.log(document);
</script>
<title>Document</title>
</head>
<body>
</body>
</html>
Document
querySelector():
The Document method querySelector() returns the first element within the
document that matches the specified selector or group of selectors. If no
matches are found, null is returned.
Syntax: element = document.querySelector(selectors)
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
<script>
var el = document.querySelector('h1');
console.log('el:', el);
</script>
</body>
</html>
Output
getElementById()
The Document method getElementById() returns an object representing
the element whose id property matches the specified string. Since
element IDs are required to be unique if specified, they're a useful way to
get access to a specific element quickly.
Syntax: element = document.getElementById(id)
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
<span
eveniet.
</span>
<span id="middleSpan">
Quisquam veritatis, quam velit quos eligendi perferendis fugiat
eveniet
</span>
<span>
Voluptatibus, error?
</span>
<script>
var el = document.getElementById('middleSpan');
console.log('el:', el);
</script>
</body>
</html>
Output:
querySelectorall()
The Document method querySelectorAll() returns a static (not live)
NodeList representing a list of the document's elements that match the
specified group of selectors.
Syntax: elementList = parentNode.querySelectorAll(selectors);
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
<span
>Lorem ipsum dolor sit amet consectetur adipisicing elit. Tempore,
quos
eveniet.
</span>
<span id="middleSpan">
</span>
<span>
Voluptatibus, error?
</span>
<script>
var el = document.querySelectorAll('span');
console.log('el:', el);
</script>
</body>
</html>
Output
getElementsByClassName()
The getElementsByClassName method of Document interface returns an
array-like object of all child elements which have all of their assigned class
name(s).
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
<span class="text-desc">
eveniet.
</span>
<span class="text-desc">
</span>
<span>
Voluptatibus, error?
</span>
<script>
var el = document.getElementsByClassName('text-desc');
console.log('el:', el);
</script>
</body>
</html>
Output
getElementsByTagName()
The getElementsByTagName method of Document interface returns an
HTMLCollection of elements with the assigned tag name. The complete
document is searched, including the root node. The returned
HTMLCollection is live, meaning that it updates itself automatically to stay
in sync with the DOM tree without having to call
document.getElementsByTagName() again.
Syntax: elementList = document.getElementsByTagName(name);
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
<span class="text-desc">
eveniet.
</span>
<span class="text-desc">
</span>
<span>
Voluptatibus, error?
</span>
<script>
var el = document.getElementsByTagName('span');
console.log('el:', el);
</script>
</body>
</html>
Output:
Assessment: Quiz
How can you retrieve an element with the id #first?
DOM Attribute
What are DOM Attributes?
The attributes are special words used inside the start tag of an
HTML element to control the tag's behavior or provide
additional information about the tag.
JavaScript provides several methods for adding, removing or
changing an HTML element's attribute. In the following sections
we will learn about these methods in detail.
Get the attribute value of an element
The getAttribute() method is used to get the current value of an element’s
attribute.
If the specified attribute does not exist on the element, it will return null.
Here's an example:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
eveniet.
</span>
<span class="text-desc">
</span>
<span id="without-style">
Voluptatibus, error?
</span>
<script>
console.log('el:', mainEl);
console.log('elClassName:', elClassName);
var withoutStyleEl = document.getElementById('without-style');
console.log('el:', withoutStyleEl);
var withoutStyleElClassName =
withoutStyleEl.getAttribute('class');
console.log('withoutStyleElClassName:', withoutStyleElClassName);
</script>
</body>
</html>
<script>
btn.setAttribute('class', 'click-btn');
btn.setAttribute('disabled', '');
</script>
</body>
<script>
btn.removeAttribute('class');
console.log('btn:', btn);
</script>
True False
The getAttribute method returns null when it does not find any attribute with the
specified name.
True False
The setAttribute method accepts only one parameter.
True False
DOM Manipulation
Styling DOM éléments
We can also apply style on HTML elements to change the visual
presentation of HTML with the dynamic use of JavaScript.
We can set all the styles for the elements including fonts, colors, margins,
borders, background images, text alignment, width and height, position,
and so on.
<body>
<script>
// Selecting element
elem.style.color = 'blue';
elem.style.fontSize = '18px';
elem.style.fontWeight = 'bold';
console.log('elem:', elem);
</script>
</body>
Adding element
We can explicitly create new elements in an HTML document, using the
document.createElement() method.
This method creates a new element but it doesn't add it to the DOM.
We will be doing that in a separate step, as shown in the following
example:
<body>
<div id="main">
</div>
<script>
newDiv.appendChild(newContent);
// Adding the newly created element and its content into the DOM
document.body.appendChild(newDiv, currentDiv);
</script>
</body>
<div id="main">
</div>
<script>
console.log('contents', contents);
</script>
</body>
Remove element
Similarly, we can use the removeChild() method to remove a child node
from the DOM.
This method also returns the removed node. Here's an example:
<body>
<div id="main">
</div>
<script>
parentElem.removeChild(childElem);
console.log("parentElem", parentElem)
</script>
</body>
The output would be :
Solution
Reorder the code in order for it to properly function:
<script>
document.body.appendChild(newDiv, currentDiv);
</script>
DOM events
Add Events
Events are actions that occur as a result of the user’s action or as result of
state change of the elements of a DOM tree. For
example: click, load, focusin, focusout. These are all events that help us
react with JavaScript.
We can assign JS functions to listen for these events in elements and react
or respond when the event occurs.
Here is a list of events. There are three ways you can assign a function to
a certain event.
If foo() is a custom function, you can register it as a click event listener (it
will be called when the button element is clicked) in three ways:
// first way
<button onclick=foo>Alert</button>
<div id="main">
<button>Alert</button>
</div>
<script>
btn.onclick=foo;
</script>
<div id="main">
<button >Alert</button>
</div>
<script>
btn.addEventListener('click', foo);
</script>
Remove Events
The removeEventListener() method detaches an event listener that
was previously added with the addEventListener() method from the
event it is listening to.
<div id="main">
<button onclick="foo">Alert</button>
</div>
<script>
btn.removeEventListener('click',foo);
</script>
Event types
The browser triggers many events. A full list is available in MDN, but here
are some of the most common event types and event names:
mouse
events (MouseEvent): mousedown, mouseup, click, dblclick, mousemo
ve, mouseover, mousewheel, mouseout, contextmenu
keyboard events (KeyboardEvent): keydown, keypress, keyup
form events: focus, blur, change, submit
window events: scroll, resize, hashchange, load, unload
Expamle:
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="">
<title></title>
</head>
<body>
<p id="log"></p>
</div>
<script>
document.addEventListener('keydown', logKey);
function logKey(event) {
</script>
</body>
</html>
Output:
When pressing the key a, this function display the following:
Solution
Reorder the code in order for it to properly function:
<button id="myBtn">Click Me</button>
<script>
function firstFunction() {
function secondFunction() {
btn.onclick = firstFunction;
btn.onclick = secondFunction;
</script>
Form validation
The form validation process typically consists of two parts: the required
fields validation which is performed to make sure that all the mandatory
fields are filled in, and the data format validation which is performed to
ensure that the type and format of the data entered in the form are valid.
Well, let's get straight to it and see how this actually works.
HTML
<form name="loginForm" onsubmit="return validateForm(event) ">
<label for="Name">Name:</label>
<label for="password">Password:</label>
<button type="submit">Login</button>
<button type="reset">cancel</button>
</form>
</body>
JavaScript
function validateForm(e) {
e.preventDefault()
if (name.length==0)
if (password.length<5)
Solution
Reorder the code in order for it to properly function:
function validateEmail() {
document.myForm.EMail.focus()
return false
return true
Conclusion
DOM RECAP
Do a little victory dance because we’re making amazing progress!
Stick around for the next course cause it just keeps on getting more
interesting!
What is VCS?
A version control system is a software tool that helps developer teams
track and manage source code changes over time.
As you edit and add to your code, you tell the version control system to
take a snapshot of your files or save a checkpoint of your progress.
The version control system saves that snapshot permanently so you can
recall it later on if you need it.
Version control systems solves that problem by presenting you with all
versions of your code with a clear history of the changes made. This allows
you to go back to older versions of the code and try a different approach.
What is Git?
Git is a free and open source distributed VCS designed to handle
everything from small to very large projects with speed and efficiency.
For example, if you are coding and you accidentally break or crash the
app, you’ve just lost all your progress and you’re forced to start from
scratch. However, it’s easier and safer if you're using Git where you can
simply roll back to a previous version of the code.
Fill in the blanks Solution
Having a distributed architecture, Git is an example of a DVCS (hence Distributed
Version Control System). Rather than have only one single place for the full version
history of the software as is common in once-popular version control systems like
CVS or Subversion (also known as SVN), in Git, every developer's working copy of the
code is also a repository that can contain the full history of all changes. In addition to
being distributed, Git has been designed with performance, security and flexibility in
mind.
Windows
Download and install Git for Windows. Once installed, you’ll be able to use
Git from the command prompt or PowerShell. We recommend that you
stick with the defaults selected during the installation unless you have a
good reason to change them.
Linux
On the terminal, just run sudo apt install git-all.
Mac
The best thing to do is to install Homebrew, and then from the terminal
run the command brew install git.
git init
P.S : This command just created a hidden folder called .git, where all the magic
happens.
git status
Solution
Reorder the following commands:
git init
git add .
git status
Configuring Git
Files status
Git sees every file in your working copy as one of three things:
Tracked
A file which has been previously staged or committed.
Untracked
A file which has not been staged or committed.
Ignored
A file which Git has been explicitly told to ignore.
Ignored files are usually built artifacts and machine generated files that
can be derived from your repository source or should otherwise not be
committed.
Configuration settings
The .gitconfig file contains a list of configurations that affects the
behaviour of git commands, so in order to manipulate it, we use the
command git config <configuration>. Therefore, to change the name and
email used by Git to identify the user, we run the following command (PS.
change YOUR.NAME and YOUR.EMAIL with your own values.)
git config --global user.name "YOUR NAME"
Git aliases
Oftentimes, you’ll be finding yourself typing git commands over and over
again. For example, git add, git init and git status are commands you
will be repeatedly using.
The smart thing thing to do then is to use a shortcut and that’s an alias.
Aliases help make your Git experience simpler, easier and more familiar.
To create a temporary alias, which will last as long as your terminal
session is open, you can type:
git config alias.KEYBOARD_SHORTCUT COMMAND
If you would like your alias to be a part of your global configuration, add
the --global command after git config. For example, to alias git i to git
init globally, you would type git config --global alias.i init.
Assessment: Quiz
The .gitignore is a file containing a list of files that git will not track:
True False
What does the following command do?
Initialize a git repo. Set an alias for email Set the user email to whatever you want
GitHub Introduction
What is GitHub?
GitHub is a web-based Git repository hosting service.
Simply put, it is a tool that enables collaboration by hosting shared Git
repositories that teams of developers can all contribute to.
While GitHub uses Git, the functionality it provides is entirely
different from Git. So try make it stick in your mind that Git and GitHub
are not the same thing.
Many large open source projects are hosted on GitHub, which makes it
very easy to examine the code both on GitHub and on local machines.
In the next couple of chapters, we will learn how to move code from our
local repository to a remote repository on GitHub using the push command,
as well as retrieve code from a remote repository on GitHub using
the pull command.
We'll also learn about GitHub specific concepts like forking and pull
requests.
Angular
React
Ruby on Rails
Twitter Bootstrap
Node.js
JQuery
Homebrew
Be sure to use whatever email address is in your . gitconfig when you sign
up on GitHub.
If you'd rather sign up with a different email address, change
your .gitconfig accordingly. You'll run into some minor annoyances if
there's a mismatch between the email address in your GitHub profile and
the email address in your .gitconfig.
After you've created the repository, GitHub will give you a few instructions
to get started. The instructions should look something like this (the url
towards the end will depend on your GitHub username):
Solution
Reorder the following commands:
git init
git add .
git status
GitHub Workflow
Fork
Now that we know how to push code to GitHub, let's explore one of
GitHub’s important features: forking.
To practice forking, head over to any repo on github and on the top right
you will see a button with the text Fork. Click on this button and you will
have a copy of the repository under your name!
Clone
Once you have applied “forking” on the repository, you need to select it
(the remote one you just made) and download the code on your local
computer (i.e. make a local repository). Instead of making a folder and
going through the whole git init process and adding a remote, you can
conveniently use the git clone command, which accepts a link to the
repository and downloads it into a folder (with everything already set up!).
In order to do that, first click on the button clone and that will provide us
with a remote URL. Finally, just copy the URL.
In the terminal, just run git clone THE_COPYED_ADDRESS.
git clone https://github.com/facebook/react.git
Pull Request
Now let's say you are collaborating with an organization on GitHub (where
you forked the repository from) and you would like to merge your changes
with the original repo that you forked (remember you can't just push to it,
because you do not have permission to do so). You can issue a pull
request and the one who can grant permission can either merge or reject
it.
To do this, click on the "New pull request button" and then click on the
"Create pull request". You should then be able to go to the original
repository and see your pull request or "PR".
Fill in the blanks Solution
A fork is a copy of a repository. Forking a repository allows you to freely experiment
without affecting the original project. If you have made changes and you want to add
them and contribute to the project, all you have to do is issue a pull request. This is
where you send the proposed changes to the owner of the project. After reviewing
your request, he either can merge it to the master repository or reject your request.
Conclusion
Kudos to you for making it this far!
We can fairly say we have mastered Git & GitHub!
We can now work with remote repositories and keep track of the differents
versions of our code. We can also work and collaborate with teams in
order to build large projects.