Skip to content

A JavaScript tutorials for beginners, An introduction to JavaScript programming languages building blocks, step-by-step guide to JavaScript

Notifications You must be signed in to change notification settings

neilabenlakhal/javascript-beginners-tutorial

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

45 Commits
 
 
 
 

Repository files navigation

JavaScript logo

JavaScript basics and fundamentals for all

Description

JavaScript is a scripting language of the web that allows you to do/add Interactivity with User-Events, implement Conditions and Validations, Dynamic updates in a Web Page, etc.. In this practical course will learn JavaScript basics-programming fundamentals from scratch. We Will start with what is JavaScript? its uses, history, how to write JavaScript, etc. It will also cover various programming building blocks like variable, functions, array, conditionals, objects, and many more.

Prerequisites for current course / What you need to know

To move forward with JavaScript you just need basic knowledge of XHTML/HTML. Here, you will learn how easy it is to add interactivity to a web page using JavaScript. But, before we begin, make sure that you have some working knowledge and/or general understanding of:

Topics include

  1. Introducing JavaScript
  2. JavaScript Getting Started
  3. JavaScript Language Fundamentals
  4. Variables
  5. Data types
  6. Operators
  7. Functions
  8. Loops | Loops and Iterations
  9. Conditions - Control Flow
  10. Array
  11. Objects
  12. Events
  13. DOM (Document Object Model)

Section 02. Introducing JavaScript

02.02. What is JavaScript?

  • JavaScript is 1 of the 3 core language/layers of web...(HTML, CSS & JavaScript)
  • JavaScript is a dynamic computer programming language. It is an interpreted (translated) programming language with object-oriented capabilities
  • JavaScript is case sensitive language

Note:
Now-a-days with the help of Node (Node.js) JavaScript is used for Back-end (Server-side) API development. JavaScript is not compiled language, but it is a translated language (JavaScript Translator (embedded in the browser engine) is responsible for translating the JavaScript code for the web browser.

02.03. What is a scripting language?

  • A high-level programming language that is interpreted by another program at runtime rather than compiled by the computer's processor as other programming languages
  • C program needs to be compiled before running whereas normally, a scripting language like JavaScript or PHP need not be compiled

What is a script?

  • A script is nothing but sets of instructions

02.04. What can you do with JavaScript?

  • JavaScript gives HTML designers a programming tool
  • JavaScript can react to events (mouse click, hover (rollover, rollout), focus, blur)
  • JavaScript can be used to validate data (Client-side validation)
  • JavaScript can manipulate HTML content and CSS styles
  • Displaying live/current/dynamic date and time (clocks)
  • Displaying pop-up windows and dialog boxes (an alert, confirm and prompt dialog box)
  • Change the website's behavior and make it more dynamic with advanced web designs

However, there are more serious uses for javascript:

  • Browser Detection - Detecting the browser used by a visitor
  • Control Browsers - Opening pages in customized windows
  • Validate Forms - Validating inputs to fields before submitting a form

02.05. Where does the JavaScript code run?

JavaScript was originally designed and developed to run only in browsers.

  1. Text Editor/HTML Editor/Code Editor/Visual Code Editor -

    • A JavaScript file (.js) is a text file itself consists of JavaScript code/statements, so to create/modify a JavaScript file we can use any text editors (like Visual Studio Code = https://code.visualstudio.com)
  2. Browsers - To view output of .html pages with .js files - Google Chrome, Mozilla Firefox, Internet Explorer, Safari etc.

    • Once the .html/.htm file created and saved, we can create a .js file and link within HTML and then we can see its output in any latest web browser
  3. JavaScript Output / Debugging Tool (Developer console) -

    • alert() or window.alert()
    • Google Chrome / Safari – Developer Tools Inspect / Inpsect element (in browser -> Right Click on page -> choose Inspect / Inspect Element -> Console Tab
    • Mozilla FireFox – Firebug

Section 03. JavaScript Getting Started

03.01. How to write Javascript?

03.01. JavaScript in HTML

  • The HTML <script>.....</script> tag is used to embed/insert/implement a JavaScript programs/code into any part of an HTML document/page
  • The <script>.....</script> tag specifies that we are using JavaScript
  • The <script>.....</script> element can be placed in the <head>, or <body> section of an HTML document
  • Each <script>.....</script> tag blocks the page rendering process until it has fully downloaded and executed the JavaScript code
    • So the best practice is to place/add the <script>.....</script> at the bottom/end of body tag/section ie. just before the closing </body> tag

Note:
JavaScript is the default scripting language in HTML. The old HTML standard attributes like type="text/javascript" and language="javascript" no longer required in modern browser

<head>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>03.01.js.script.tag.html</title>

    <!-- internal style -->
    <style>
      /* css selector: { property:value; } */
      body {
        font-family: arial;
      }
    </style>

    <!-- internal JavaScript - head section -->
    <script>
      // Write all JavaScript code here
      alert('welcome to JavaScript');

    </script>
    
</head>

<body>
    
    <p id="para">Content</p>

    <!-- internal JavaScript - body section -->
    <script>
      /* Write all JavaScript code here */
      document.write('This is dyanamic content. Hello All, Lets write something on web page');
      document.getElementById("para").innerHTML="This is dyanamic content. Hello All, Lets write something on web page";
      
    </script>
    
</body>

03.02. Where to write JavaScript in HTML?

03.02. Where to embed include write put JavaScript in HTML?

JavaScript provides 3 places to write the JavaScript code in our webpage:

  1. Inside the HEAD section
  2. Inside the BODY section
  3. External JavaScript .js file (separation of concern)

03.02.01. Inside the HEAD section (code between the head tag)

  • JavaScript programs/code/statements can be placed in the <head> section of an HTML page
  • As each <script>.....</script> tag blocks the page rendering process until it has fully downloaded and executed the JavaScript code so placing them in the head section (<head> element of the document without any valid reason will significantly impact your website performance

Syntax & Example: 03.02.01.js.head.html

<head>

    <!-- internal JavaScript - head section -->
    <script>
        // Write all JavaScript code here
        alert('welcome to JavaScript written in head section');

    </script>

</head>

03.02.02. Inside the BODY section (code between the body tag)

  • JavaScript code/statements can be placed in the <body> section of an HTML page
  • As blocking nature of <script>.....</script> tag ideally, scripts should be placed at the end of the body section, just before the closing </body> tag, it will make your web pages load faster
<body>

    <p>page content</p>

    <!-- internal JavaScript - body section -->
    <script>
        // Write all JavaScript code here
        alert('welcome to JavaScript written in body section');
        document.write('<h2>welcome to JavaScript written in body section</h2>');

    </script>

</body>

03.02.03. External JavaScript .js file (separation of concern)

  • We can easily write JavaScript code in between the script element. In a real-world application, we have 1000+ lines of code, we don't want to write all that code inline here
  • We must have to extract and separate our JavaScript behavior code from our HTML markup code
  • We can use/add/attach an external JavaScript file by using <script> tag with src (source) attribute:
    • <script src="scriptfile.js"></script>
  • We can create a single external JavaScript file and embed it in many/any HTML page which provide code re-usability

Syntax & Example - .html file: 03.02.03.js.external.html

<body>

    page content

    <!-- include external JavaScript - body section -->
    <script src="./03.script.js"></script>
    
</body>

Syntax & Example - .js file: 03.02.03.script.js

// external js file
// Write all JavaScript code here

alert('welcome to JavaScript written in external file');
document.write('<h2>welcome to JavaScript written in external file</h2>');

03.03. JavaScript Code structure

The syntax of JavaScript is the set of rules that define a correctly structured JavaScript program. Let's study some of the building blocks of JavaScript code:

03.03.01. JavaScript Statements

  • One line of JavaScript Code is one JavaScript Statement / Instruction / Command
  • JavaScript code/program (or just JavaScript) is a sequence of statements
  • Statements are written in-between <script>.....</script> tag

03.03.03. Semicolons

  • JavaScript statements are generally followed by a semicolon; character
  • JavaScript interprets the line break as an implicit semicolon, called an automatic semicolon insertion

Note:
It is a good programming practice to use semicolons; after every statement

03.03.04. Case Sensitivity

  • JavaScript is a case-sensitive language
  • in Javascript variables, language keywords, function names, and other identifiers must always be typed with a consistent capitalization of letters
  • Example: var firstName='a'; and var FirstName='b'; here firstName & FirstName are different ie. two different variable

Note:
Take care/precautions while writing variable and function names in JavaScript

03.03.05. JavaScript Code Blocks

  • JavaScript commands/statements/code can be grouped together in code blocks, inside curly brackets {...}
  • An often occurrence of a code block in JavaScript is a JavaScript function

Syntax & Example: 03.03.05.script.js

// external js file
// Write all JavaScript code here

// define function - block of code to show welcome message
function sayHello() {
  alert('Hello All! Welcome to JavaScript!!');
}

// define function - block of code to show total of two numbers
function showTotal() {
  var num1 = 10;
  var num2 = 20;
  var total = num1 + num2;
  alert('Total is : ' + total);
}

// invoke / run  / call a function
sayHello();
showTotal();

03.05.01.01. Single-line Comments

  • Single-line JavaScript comments are used for one line of comment only
  • Single-line comments starts with two forward slash: // is single comment

Syntax & Example: 03.05.script.js

// external js file
// Write all JavaScript code here

// show alert box
alert('Welcome to JavaScript!');

var firstName = 'Alia'; // variable to store firstName
var lastName = 'Ali'; // variable to store lastName

03.05.01.02. Multi-line Comments

  • Multiline comments start with forward slash and an asterisk, /* and also end with an asterisk and a forward slash */: /* multi-line comment */

Syntax & Example: 03.05.script.js

/* show alert box */
alert('Welcome to JavaScript!');

/* This is a multiline comment.
A code block can be commented on. */

Section 04. JavaScript Language Fundamentals

04.01. Generating Output

  • JavaScript does not have any display or built-in print functions

Different ways to show output/display data

  1. Writing into an alert box with alert() or window.alert()
  2. Writing into the HTML / Browser Window with document.write()
  3. Write into an element of HTML / Inserting Output Inside an HTML Element with innerHTML

04.01.01. Displaying Output in Alert Dialog Boxes: alert() or window.alert()

  • One can use alert dialog boxes to display the message or output data to the user
  • An alert dialog box is created using the alert() or window.alert() method
  • A small pop-up box appears with a closing button to close alert-box
  • This method is great for short and rapid informative messages which can be instantly closed

Syntax & Example: 04.01.01.script.js

// external js file
// Write all JavaScript code here

alert('I am Javascript course');
window.alert('We are learning JavaScript');

04.01.03. Writing Output into the HTML / Browser Window: document.write()

  • document.write() method is used to write the content to the current document while document is being parsed
  • Programmers do ues document.write() for testing purposes

Syntax & Example: 04.01.03.script.js

// external js file
// Write all JavaScript code here

document.write('We are learning JavaScript');

04.01.04. Inserting Output Inside an HTML Element: innerHTML

  • We can write or insert output inside an HTML element using the element's innerHTML property
  • First we need to select the element using a method such as document.getElementById(id)

Note:
HTML element manipulating is fully dependent on JavaScript DOM manipulation concepts

Syntax & Example: 04.01.04.script.js

/// external js file
// Write all JavaScript code here

// Writing text string inside an element
document.getElementById('mainHeadingText').innerHTML = 'Heading Text change dynamically on run-time';

var paraText = document.getElementById('mainParaText');
paraText.innerHTML = '<strong>This Paragraphic text inserted dynamically through innerHTML method.</strong>';

Section 05. Variables

  • A JavaScript variable is simply a name of the storage location (named containers/named storage) for data
  • Variables are declared using the keyword var keyword
  • The assignment operator (=) is used to assign value to a variable, like this: var varName = value; or var firstName = 'JavaScript';
  • By default value of variable defined in JavaScript is undefined (variable is defined but value not assigned)

Note:
As a best practice of newer JS versions, variables can be be defined with let keyword: let techName = 'JavaScript' ;


Syntax & Example: 05.01.script.js

// variables defined to hold different types of data
var techName = 'JavaScript'; // String literal 
var version = 6; // Number literal
var isDone = true; // Boolean literal

05.02. Creating a variable without a value

Variables can also be declared without having any initial values assigned to them.

Syntax & Example: 05.01.script.js

// Declaring Variables
var techName;
var version;
var isDone;

// Assigning value
techName = 'JavaScript';
version = 6;
isDone = true;


// ------------------------------

// Declaring Variable
var userName;

// Assigning value
userName = 'Sarra';

05.03. Declaring multiple variables at once

We can also declare multiple variables and set their initial values in a single statement, each variable is separated by comma.

Syntax & Example: 05.01.script.js

// Declaring multiple variables
var techName = 'JavaScript', version = 6, isDone = true;

05.04. Variable Naming Conventions (Identifiers)

The basic rules for defining/assigning names for variables (unique identifiers) are:

  • A variable name must start with a letter, underscore (_), or dollar sign ($)
    • Example: var firstName, var _firstName, var $firstName;
  • Names can contain letters, digits, underscores, and dollar signs
    • Example: var $num_total1;
  • A variable name cannot start with a number or special characters
    • Example: var 1num_total, var .num_total
  • A variable name cannot contain spaces
    • Example: var num total;
  • A variable Names are case sensitive
    • Example: var firstName='Sarra'; and var FirstName='Sarra'; here firstName & FirstName are different ie. two different variable
  • A variable name cannot be a JavaScript keyword or a JavaScript reserved word
    • Example: var var; var switch; var for; var true;

Syntax & Example: 05.04.script.js

// variables defined to hold different types of data
var firstName = 'JavaScript';
var _version = 6;
var $num_total1 = 10;

window.alert('variables details: ' +  _firstName + ' ' + _version + ' ' + $num_total1);

// wrong identifiers
// var #name;

05.06.02. The const Keyword

  • Use const to declare a constant (read-only / unchanging) variable
  • Constants are read-only, you cannot reassign new values to them

Syntax & Example: 05.06.02.script.js

// traditional var syntax
const PI1 = 3.14;
PI1 = 100; // error

Section 06. Data types

06.01. Data types

A variable in JavaScript can contain any type of data. Data types specify what kind of data can be stored and manipulated within the variable in a program. In JavaScript, different data types are available to hold different types of values/data. There are two main categories/types of data types in JavaScript:

  1. Primitive (Primary or Value) data type
    • String
    • Number
    • Boolean
    • Undefined
    • Null
  2. Non-primitive (Reference or Composite) data type
    • Array
    • Object
    • Function

06.02. Primitive data type

06.02. Primitive, Primary or Value data type

There are different types of primitive data types in JavaScript. They are as follows:

Data Type Description
String represent textual data. e.g. "welcome" or 'to javascript'
Number represents numeric values e.g. 10, 100.29
Boolean represents boolean value either false or true
Undefined represents an undefined value (a variable declared but value not assigned)
Null represents null i.e. no value at all

06.02.01. String

  • The string data type is used to represent textual data (i.e. sequences of characters)
  • Strings hold information in words/text
  • A string in JavaScript must be surrounded by "double" or 'single' quotes
  • Example: 06.02.script.js
var firstName = "Java"; 
var lastName = 'Script';

06.02.02. Number

  • The number data type simply defined without quotes is used to represent positive or negative numbers with or without a decimal place
  • Many mathematical operations can be done on numbers, e.g. multiplication *, division /, addition +, subtraction, and so on
  • Example:
var age = 25; 
var id = 1;

06.02.03. Boolean

  • The Boolean data type can hold only two values: true or false
  • true = ON / yes / correct / 1, false = OFF / no, incorrect / 0
  • Boolean data types is often used in conditional testing of code
  • Example:
var isDone = true; 
var isMarried = false;

06.02.04. Undefined

  • The meaning of undefined is “value is not assigned”
  • The undefined data type can only have one value-the special value undefined
  • A Variable has been declared, but not assigned a value
  • A variable without a value, The type is also undefined
  • Example:
var firstName;
var country;

06.05. The typeof Operator

  • The typeof operator returns the type of the argument
  • It can be used with or without parentheses (typeof(x) or typeof x

Syntax & Example: 06.05.script.js

// use typeof to find data type of variables
// Strings
alert(typeof "Hello"); // "string"
alert(typeof '12'); // "string"


// Booleans
alert(typeof true); // "boolean"
alert(typeof(1 == 2)); // "boolean"

// Arrays
var techArray = [];
alert(typeof ['JavaScript', 'jQuery', 'Angular']);  // "object"

// Functions
alert(typeof window.alert); // "function"

06.06. Type conversion

06.06. typeof parseInt parseFloat

  • Type conversion is nothing but taking a variable and changing its data type as per needs requirements and logic

Syntax & Example:

// parseInt() method

let curNumber = parseInt('100');
let curNumber = parseFloat('100.41');

06.07. Type automatic conversion

  • JavaScript ability to convert type automatically :

Syntax & Example:

const num1 = '20';
const num1 = 10;

const sum = num1 + num2;
alert(sum);

Section 07. Operators

07.02. Arithmetic Operators

JavaScript supports the following Arithmetic operators (List of Arithmetic operators):

Operators Description Example / Result
+ Addition 10 + 20 = 30 (Sum of num1 and num2)
- Subtraction 20 - 10 = 10 (Difference of num1 and num2)
* Multiplication 10 * 20 = 200 (Product of num1 and num2)
/ Division 20 / 10 = 2 (Quotient of num1 and num2)
% Modulus (Division Remainder) 20 % 10 = 0 (Remainder of num1 divided by num2)
++ Increment var num1 = 100; num1++; Now num1 = 11
-- Decrement var num1 = 100; num1--; Now num1 = 9
** Exponentiation (ES2016 / ES6) 2 ** 2 = 4 ; 2 ** 3 = 8 (Multiply num1 for num2 times)

Syntax & Example: 07.02.script.js

// Arithmetic operators
var num1 = 10;
var num2 = 4;

alert('Addition ' + (num1 + num2)); // 14
alert('Subtraction ' + (num1 - num2)); // 6
alert('Multiplication ' + num1 * num2); // 40
alert('Division ' + num1 / num2); // 2.5
alert('Modulus reminder ' + num1 % num2); // 2
num1++
alert('after Increment ' + num1); // 11
num2--; 
alert('after Decrement ' + num2); // 3

num1 = 10;
num2 = 4;
alert('Exponentiation ' + (num1 ** num2)); // (10 ** 4) = 10* 10 * 10 * 10 = 10000

07.03. Assignment Operators

  • The Assignment operators are used to assign particular values to variables

JavaScript supports the following Assignment operators (List of Assignment operators):

Operators Description Example / Result
= Simple Assignment 10 + 20 = 30; / var total = num1 + num2; (assigns a value to the variable)
+= Add and assign var num1 = 10; num1 += 20; Now num1 = 30 (assigns and adds value to the variable, num1 += 20; is equivalent to num1 = num1 + 20;)
-= Subtract and assign var num1 = 10; num1 -= 5; Now num1 = 5 (assigns and subtract value to the variable, num1 -= 5; is equivalent to num1 = num1 - 5;)
*= Multiply and assign var num1 = 10; num1 *= 5; Now num1 = 50 (assigns and multiply value to variable, num1 *= 5; is equivalent to num1 = num1 * 5;)
/= Divide and assign var num1 = 10; num1 /= 5; Now num1 = 2 (assigns and divide value to the variable, num1 /= 5; is equivalent to num1 = num1 / 5;)
%= Modulus and assign var num1 = 10; num1 %= 5; Now num1 = 0 (assigns and Modulus value to the variable, num1 %= 5; is equivalent to num1 = num1 % 5;)

Syntax & Example: 07.03.script.js

// Assignment operators
var num1 = 10;
var num2 = 20

// old methodology
// num1 = num1 + num2;
//alert(num1); // 30

// new techniques
num1 += num2; 
alert(num1); // 30

// num2 -= num1; 
// alert(num2); // 10

// num1 *= num2; 
// alert(num1); // 200

// num2 /= num1; 
// alert(num2); // 2

07.04. Logical Operators

  • The Logical operators are used to make decisions based on multiple conditions
  • The logical operators are typically used to combine multiple conditional statements and evaluate

JavaScript supports the following Logical operators (List of Logical operators):

Operators Description Example / Result
&& Logical AND x && y; (True if both operands like x and y are true)
|| Logical OR x || y; (True if either x or y is true)
! Logical NOT !x; (True if x is not true)

07.05. Comparison (or Relational) Operators

07.05. Comparison Operators

07.05. Relational Operators

  • The JavaScript comparison operator compares the two operands
  • It compares two values in a Boolean fashion
  • The comparison operators are used to determine the similarity and difference between different variables

JavaScript supports the following Comparison (or Relational) operators (List of Comparison (or Relational) operators):

Operators Description Example / Result
==
(Loose Equality Operator)
Is equal to / identical x == y (True if x is equal to y)
!= Not equal to / different x != y (True if x is not equal to y)
!== Not identical / different value or different type x !== y )True if x is not equal to y, or they are not of the same type)
< Less than x < y (True if x is less than y)
> Greater than x > y (True if x is greater than y)
<= Less than or equal to x <= y (True if x is less than or equal to y)
>= Greater than or equal to x >= y (True if x is greater than or equal to y)

Syntax & Example: 07.05.script.js

// Comparison (or Relational) operators
var num1 = 25;
var num2 = 35;
var num3 = 250;
 
alert(num1 == num3);  // false
alert(num1 != num2);  // true

07.07. String Operators

Variables can also have string values, + operator can be used to concatenate strings as well as numbers.

There are two operators which can also be used be for strings:

Operators Description Example / Result
+ Concatenation string1 + string2 (Concatenation of string1 and string2)
+= Concatenation assignment string1 += string2 (Appends the str2 to the str1)

Syntax & Example: 07.07.script.js

// String Operators
var message1 = "Hello";
var message2 = " World!";
 
alert(message1 + message2); // Outputs: Hello World!
 
message1 += message2;
alert(message1); // Outputs: Hello World!

Section 08. Functions

08.01.02. Function Definition / Function Declaration / Creating Function

  • The function declaration starts by using the function keyword,
  • followed by a unique function name,
  • a list of parameters in parentheses i.e. () (that might be empty),
  • and a statement block surrounded by curly braces { }

Syntax & Example: 08.01.script.js

//1. define / declare / create function

function showMessage () {
  //Body of function 
  //code to be executed
  alert('welcome to JavaScript function');    
}

08.01.03. Function Invocation / Calling a Function / Run a Function

  • Defined function can be invoked/called/run from anywhere in the document, by typing function name followed by a set of parentheses, like functionName()

Syntax & Example: 08.01.script.js

//2. invoke / call the function

showMessage();

Examples of function names:

  • getSum();
  • createFields();
  • calcAge();
  • checkUserType();

08.02. Types of Function

  • Regular Function
  • Parameterized Function
  • Return Type Function (Function returning values)

08.02.01. Regular Function

  • Simple/Normal function which we use daily to perform some action/task

Syntax & Example: 08.02.01.script.js

var course = 'Javascript';

//1. define / declare / create function
function sayHello () {
  //Body of function 
  //code to be executed
  alert('Hello ' + name);    
}

//2. invoke / call the function
sayHello();

08.02.02.01. Parameterized Function

  • One can pass data to functions using parameters (function arguments)
  • You can specify parameters when you define your function to accept input values at run time

Syntax & Example: 08.02.02.01.script.js

// Parameterized function
//1. define / declare / create function
function sayHello (name) {
  //Body of function 
  //code to be executed
  alert('Hello ' + name);    
}

//2. invoke / call the function
sayHello('Javascript');

sayHello('JS');

// ------------------------------

var total;

function calculateSum (num1, num2) {
  total = num1 + num2;
  alert(total);
}

calculateSum(10, 20);
calculateSum(100, 200);

08.02.03. Return Type Function (Function returning values)

  • A function can return a value back to the script that called the function, as a result, using the return statement
  • We can call a function that returns a value and use it in our program
  • The return statement usually placed as the last line of the function

Syntax & Example: 08.02.03.script.js

// Return type function
//1. define / declare / create function
function getSum (num1, num2) {
  //Body of function 
  //code to be executed
  var sum = num1 + num2;
  return(sum);
}

//2. invoke / call the function
alert(getSum(10,20));
alert(getSum(100,200));

var total = getSum(50,50);
alert(total);

08.03. Different ways to define Function

The syntax that we've used before to create functions is called function declaration. There is another syntax for creating a function that is called a function expression and Immediately invoked function expression (IIFE)

08.03.01. function declaration (Regular/Normal function)

08.03.02. function expression

  • Variables contain the expressions of a function
    • Anonymous function expression
    • Named function expression

Syntax & Example: 08.03.02.01.script.js

// function declaration (Regular / normal function)
function getSum1(num1, num2) {
  var total = num1 + num2;
  return total;
}

// ------------------------------

// function expression - Anonymus
var getSum2 = function(num1, num2) {
    var total = num1 + num2;
    return total;
};

alert(getSum2(10,20));

// ------------------------------

// assign function to another variable
var sum1 = getSum2;
alert(sum1(100,200));

Syntax & Example:

// function expression - named
var getSum2 = function getTotal(num1, num2) {
  var total = num1 + num2;
  return total;
};

alert(getSum2(10,20));

// ------------------------------

// assign function to another variable
var sum1 = getSum2;
alert(sum1(5,10));

08.04. String Methods

Syntax & Example:

const firstName = 'Sarra';
const lastName = 'BA'

const fullName = (firstName) + (lastName);

// concatenation
alert(firstName + ' ' + lastName);

// length
alert(firstName.length);

// change case
alert(firstName.toLowercase());
alertfirstName.toUppercase());


// indexOf
alert(firstName.indexOf('i'));
alert(firstName.lastIndexOf('a'));

// charAt()
alert(firstName.charAt(2));

// substring();
alert(firstName.substring(0,4));

Section 09. Loops

Section 09. Loops and Iterations

  • Loops are used to execute the same block of code again, with a different value, until a certain condition is met

Different Types of Loops in JavaScript:

  1. for loop
  2. while loop
  3. do...while loop
  4. for...in loop
  5. for...each

09.01. The for loop

  • The For loop is used to run a piece of code a set amount of times
  • Loops through a block of code until the counter reach a specified number
  • The for loop repeats a block of code until a certain condition is met
  • The for loop is the most simple/compact form of looping
  • For loop consists of 3 statements (), mostly i = index is used for loop initialization

Syntax & Example: 09.01.01.script.js

// for loop

/* for (statement 1; statement 2; statement 3) {
  // Code to be executed
} */


/* for(variable definition/index/initialization; condition checking; increment/decrement expression) {
  // Code to be executed
} */

for (let i=1; i<=5; i++) {
  alert('Hello, The current index/num is: ' + i);
  document.write('<li>Hello, The current index/num is: ' + i + '</li>');
  document.write('Hello, The current index/num is: ' + i);
}

09.01.02. The for loop - Find Even or Odd number

Syntax & Example: 09.01.03.script.js

// for loop - to find out odd even number

for (let i = 1; i <= 10; i++) {
  if (i % 2 == 0) {
    alert('The current index/num is EVEN : ' + i);
  } /* else {
    alert('The current index/num is ODD : ' + i);
  } */
}

09.02. The while loop

  • Loops through a block of code until the specified condition evaluates to true
  • In For loop, a variable is part of a loop, but in While loop, we need to declare variable externally

Syntax & Example: 09.02.01.script.js

// while loop

/*while(condition) {
  // Code to be executed
}*/

let i = 1;

while (i <= 5) {
  alert('Hello, The current index/num is: ' + i);
  document.write('<li>Hello, The current index/num is: ' + i + '</li>');
  i++;
}

09.03. The do while loop

09.03. The do...while loop

  • The do...while loop is similar to the while loop except that the condition check happens at the end of the loop
  • The do...while loop will always be executed at least once (before checking if the condition is true), even if the condition is false

Syntax & Example: 09.03.01.script.js

// do...while loop

/*do {
    // Code to be executed
}
while(condition);*/

let i = 1;

do {
  alert('Hello, The current index/num is: ' + i);
  document.write('<li>Hello, The current index/num is: ' + i + '</li>');
  alert('Hello, The current index/num is: ' + i);
  i++;
}
while (i <= 5); 

Section 10. Conditions

Section 10. Conditions - Control Flow

  • Conditional statements are used to perform different action based on different condition
  • Conditional statements allow the developer to make correct decisions and perform right actions as per condition
  • It helps to perform different actions for different decisions
  • We can use conditional operator to check our condition: >, <, >=, <=, ==, !=, ===

We can use the following conditional statements in JavaScript to make decisions:

  1. If Statement
  2. If...else Statement
  3. If...else if...else Statement
  4. Switch...Case Statement

10.01. The if statement

10.01. The if statement and comparison operators

Syntax & Example: 10.01.01.script.js

// if conditional statement

/*if(condition/expression) {
  // Code to be executed if condition/expression is true
}
*/

let user = 'A';

if (user == 'A') {
  window.alert('Welcome A!');
}

if (user == 'B') {
  window.alert('Welcome Authorised User: ' + user + '!');
}

// ------------------------------

let age = 20;

if (age >= 18) {
  window.alert('MAJOR! Eligible for Voting');
}

// ------------------------------

let currentHours = 10;

if(currentHours < 12) {
  window.alert('Good Morning!');
}

if(currentHours >=6 && currentHours < 12) {
  window.alert('Good Morning!');
}

10.02. The if else statement

  • The JavaScript if...else statement is used to execute the code weather condition is true or false
let user = 'Ambar';

if (user == 'A') {
  window.alert('Welcome Dinanath!');
} else {
  window.alert('Welcome Guest!');
}

// ------------------------------

let age = 15;

if (age >= 18) {
  window.alert('MAJOR! Eligible for Voting');
} else {
  window.alert('MINOR! NOT Eligible for Voting');
}

// ------------------------------

let currentHours = 10;

if(currentHours < 12) {
  window.alert('Good Morning!');
} else {
  window.alert('Good Evening!');
}

Section 11. Array

11.01. What is an Array?

  • An Array is a special type of variable/object which consists of / stores multiple values
  • Arrays are complex variables that allow us to store more than one value or a group of values under a single variable name
  • Arrays are defined with square brackets [ ] and with new keyword
  • Array items are normally separated with commas,
  • Arrays are zero-indexed i.e. the first element of an array is at index/position 0
  • An array is ordered collection, where we have a 0th, 1st, a 2nd, and so on elements
  • Each value (an element) in an array has a numeric position, known as its index, starts from 0, so that the first array element position/index is arr[0] not arr[1]

Different ways to create/define an Array

There are 3 main ways to construct an array:

  1. By array literal
  2. By creating an instance of Array directly (using the new keyword)
  3. By using an Array constructor (using the new keyword)

11.02. Create Array by array literal

  • The simplest way to create an array in JavaScript is enclosing a comma-separated list of values in square brackets [ ]
  • var myArray = [element0, element1, ..., elementN];

Syntax & Example: 11.02.01.script.js

// create array with array literal ie. [] square bracket

// var myArray = [element0, element1, ..., elementN];

var arrColors = ['Red', 'Green', 'Blue', 'Orange'];
alert(arrColors); // show all elements

// ------------------------------

var arrCities = ['AbuDhabi', 'Dubai', 'Alain'];
alert(arrCities[1]); // show 1st index ie. 2nd positioned element

// ------------------------------

var arrTechnologies = [];
arrTechnologies[0] = 'Java';
arrTechnologies[1] = 'Python';
arrTechnologies[2] = 'C';
alert('Total Elements: ' + arrTechnologies.length);

11.03. Create Array by creating an instance of array directly

11.03. Create Array by creating an instance of array directly (using new keyword)

  • Array instance can be created using the new keyword new Array()
  • var myArray = new Array(); OR var myArray = Array();

Syntax & Example: 11.03.01.script.js

// create array with new keyword

// var myArray = new Array();

var arrColors = new Array();

arrColors[0] = 'Red'
arrColors[1] = 'Green'
arrColors[2] = 'Blue'
arrColors[3] = 'Orange'
alert(arrColors); // show all elements

// read/get array items/elements
for (let i = 0; i < arrColors.length; i++) {
  alert(arrColors[i]);
}


var arrTechnologies = new Array();

// add new array items/elements
for (let i = 0; i <= 5; i++) {
  arrTechnologies[i] = 'JavaScript';
}

alert(arrTechnologies); // show all elements

11.04. Create Array by using an array constructor

11.04. Create Array by using an array constructor (using new keyword)

  • Array instance can be created using the new keyword new Array() passing arguments in constructor so that we don't have to provide value explicitly
  • var myArray = new Array(element0, element1, ..., elementN);

Syntax & Example: 11.04.01.script.js

// create array with new keyword Array constructor passing parameter

// var myArray = new Array(element0, element1, ..., elementN);

var arrColors = new Array('Red', 'Green', 'Blue', 'Orange');

// ------------------------------

var arrJsFrameworks = new Array('jQuery','Angular','React','Node','Vue','Express','D3');

11.05. Getting the Length of an Array

  • The length property returns the length of an array, total number of elements in an array
  • length property brings back an array length - the fixed amount of items stored in the array
  • The array length is always greater than the index of any of its element (Array length = last array index + 1)
  • The maximum length allowed for an array is 4,294,967,295
  • myarray.length

Syntax & Example: 11.05.01.script.js

// get/retrieve/find array length

// myarray.length

var arrColors = new Array('Red', 'Green', 'Blue', 'Orange');
alert(arrColors.length);

// ------------------------------


11.06. Accessing Looping through an Array Elements
---------------------
11.06. Loop through an Array Elements
---------------------

- Array elements can be accessed by their `index using the square bracket notation ie. [index]`
- Arrays are `zero-indexed` i.e. the first element of an array is at index/position 0
- An array is `ordered collection`, where we have a 0th, 1st, a 2nd, and so on elements
- Each value (an `element`) in an array has a `numeric position`, known as its `index`, `starts from 0`, so that the first array element is `arr[0]` not arr[1]
- One can use `for loop` in coordination with array `length` property to access each element of an array in sequential order
- myarray[indexNumber], myarray[0] // get first array element

> **Syntax & Example**: `11.06.01.script.js`
```javascript
// access/loop through array element

// myarray[indexNumber], myarray[0]

var arrColors = new Array('Red', 'Green', 'Blue', 'Orange');

alert(arrColors[0]); // Red
alert(arrColors[2]); // Blue

// ------------------------------

var arrJsFrameworks = new Array('jQuery', 'Angular', 'React', 'Node', 'Vue', 'Express', 'D3');
alert(arrJsFrameworks[3]); // Node
alert(arrJsFrameworks[5]); // Express

// Loop through an Array Elements
for (let i = 0; i < arrJsFrameworks.length; i++) {
  document.write('<li>'+arrJsFrameworks[i] + '</li>');
}

11.07. Adding Editing an Array Elements

  • One can add/edit an array element by simply specifying array[index] and value ie. myarray[5]='value'

Syntax & Example: 11.07.01.script.js

// add/edit array element

// myarray[indexNumber]='value', myarray[2]='value', myarray.push('value'), myarray.unshift('value')

var arrColors = new Array('Red', 'Green', 'Blue', 'Orange');
alert(arrColors);
alert('arrColors.length: ' + arrColors.length);

// add an element at the end of the array
arrColors.push('Cyan');
alert(arrColors);
alert('arrColors.length: ' + arrColors.length);

// ------------------------------

// edit 1st index ie. 'white' to 'pink'
arrColors[1] = 'pink';
alert(arrColors);
alert('arrColors.length: ' + arrColors.length);

11.09. Array properties and methods

Syntax & Example: ``

// length
var arrColors = new Array('Red', 'Green', 'Blue', 'Orange');
alert(arrColors.length);

// sort
let newSortedColorsArray = arrColors.sort();
alert(newSortedColorsArray);
alert(numberArray.sort());
*/

// find
alert(numberArray.find(40));

Section 12. Objects

  • JavaScript is an object-based language and in JavaScript, almost everything is an object or acts like/as an object

12.01. The Window object

  • Window Object the global variable/global object available in the browser environment, represents the browser window in which the script is running
  • Simply, the window object represents a window in a browser
  • The Window interface represents a window containing a DOM (Document Object Model)
  • In Browser -> Inspect Element -> Console Panel -> Type Window, check different properties and methods available

Syntax & Example:

// Methods
window.alert('Alert! Hello, Welcome to JavaScript');

// const namePrompt = window.prompt();
const namePrompt = window.prompt('Enter Your Name');
window.alert(namePrompt);


if(window.confirm('Are you sure?')) {
  window.alert('YES - selected');
} else {
  window.alert('NO - clicked');
}



12.10. The Math Object
---------------------

- The Math object allows to perform mathematical tasks
- Math object provides several constants and methods to perform mathematical operation  (like `min, max, sqrt, pi, round, random`, etc)

> **Syntax & Example**: 
```javascript

let pieValue = Math.PI;

let a= Math.sqrt(64));

alert(Math.pow(8,2)); //64
alert(Math.pow(10,3)); //10 * 10 * 10 = 1000

12.11. Date and Time

  • The Date object is used to deal/work with date and time
  • Simply, the JavaScript date object can be used to get date, day, month and year
  • Date objects are created with new Date() - Date constructor can be used to create date object, It provides methods to get and set day, month, year, hour, minute and seconds

Syntax & Example:

const today = new Date();
alert('today is:', today);

const date1 = new Date('March 28 1979');

let currentDate = new Date();

const currentDateToday = currentDate.getDate();
const currentDayToday = currentDate.getDay();
const currentMonth = currentDate.getMonth();
const currentYear = currentDate.getYear();
const currentHours = currentDate.getHours();
const currentMinutes = currentDate.getMinutes();

Section 13. Events

13.01. Understanding Events and Event Handlers

  • Events are happening/triggering all over, Event lets the developer know something has occurred/happened
  • Events occur when the page loads (Onload), when the user interacts with the web page (clicked a link or button/hover) (onlick), pressed key, moved the mouse pointer, mouse-clicked/hover (onmouseover), entered text into an input box or textarea (onchange, onblur, onfocus), submits a form (submit), page unloads (unload)
  • When an event occurs, use a JavaScript event handler (or an event listener) to detect them and perform a specific task - Event handlers name always begin with the word "on", like onclick, onload, onblur, and so on
  • To react to an event you listen for it and supply a callback function or event handler which will be called by the browser when the event occurs

13.02. Different Event category

In general, the events can be categorized into four main groups:

  1. Mouse events
  2. Keyboard events
  3. Form events
  4. Document/Window events

13.02.01. Mouse events

A mouse event is triggered when the user clicks some element, move the mouse pointer over an element, etc. Find here some of the important mouse events and their event handler:

  • click (onclick event handler)
    • Occurs When the mouse clicks on an element, links, buttons etc. on a web page
  • contextmenu (oncontextmenu event handler)
    • Occurs when a user clicks the right mouse button on an element to open a context menu
  • mouseover / mouseout (onmouseover & onmouseout event handler)
    • Occurs when the mouse pointer/cursor comes over / leaves (goes outside of) an element
  • mousedown / mouseup (onclick/onmousedown & onmouseup)
    • Occurs when the mouse button is pressed/released over an element
  • mousemove (onmousemove event handler)
    • Occurs when the mouse pointer/cursor is moved

Syntax & Example:

<ol class="normalList">
  <li><strong>click</strong> (`onclick` event handler) <br/>
    <span onclick="alert('You have clicked an element!')" style="color:blue;cursor: pointer;">Occurs When the `mouse clicks on an element`, links, buttons etc. on a web page </span>
  </li>
  <li><strong>contextmenu</strong> (`oncontextmenu` event handler) <br/>
    <span oncontextmenu="alert('You have Right clicked on Me!')" style="color:blue;cursor: pointer;">Occurs when a `user clicks the right mouse button` on an element to open a context menu</span>
  </li>
  <li><strong>mouseover / mouseout</strong> (`onmouseover` &  `onmouseout` event handler) <br/>
    <span onmouseover="alert('You have Mouse Over Me!')" onmouseout="alert('You have Mouse Out Me!')"  style="color:blue;cursor: pointer;">Occurs when the mouse pointer/cursor comes over / leaves (goes outside of) an element</span>
  </li>
  <li><strong>mousedown / mouseup</strong> (`onclick/onmousedown` & `onmouseup`) <br/>
    <span onmousedown="alert('You have clicked on Me!')" onmouseup="alert('You have released click on Me!')"style="color:blue;cursor: pointer;">Occurs when the mouse button is pressed / released over an element</span>
  </li>
  <li><strong>mousemove</strong> (`onmousemove` event handler) <br/>
    <span onmousemove="alert('You Moved mouse over Me!')" style="color:blue;cursor: pointer;">Occurs when the mouse pointer/cursor is moved</span>
  </li>
</ol>

13.02.02. Keyboard events

A keyboard event is fired up when the user presses or release a key on the keyboard. Here're some of the important keyboard events and their event handler:

  • keydown / keyup (onkeydown & onkeyup event handler)
    • Occurs when the user presses down a key and then releases the button/a key on the keyboard
  • keypress (onkeypress event handler)
    • Occurs when the user presses down a key on the keyboard that has a character value associated with it
    • Keys like Ctrl, Shift, Alt, Esc, Arrow keys, etc. will not generate a keypress event, but will generate a keydown and keyup event

Syntax & Example:

<label>Enter Name:</label> 

<input type="text" placeholder="Enter Name" 
onkeydown="alert('onkeydown pressed a key inside input text!')" 
onkeyup="alert('onkeyup released a key inside input text!')" 
onkeypress="alert('onkeypress Other than Ctrl, Shift, Alt, Esc, Arrow keys pressed!')"/>

13.02.03. Form events

A form event is triggered when a form control/form fields (text fields/radio buttons/checkbox) receives or loses focus or when the user modifies a form control value by typing text in a text input, select an option in a dropdown/select box, etc. Let us look into some of the most important form events and their event handler:

  • focus (onfocus event handler)
    • Occurs when the user focuses on an element on a web page, e.g. on an input text field
  • blur (onblur event handler)
    • Occurs when the user takes the focus away from a form element or a window
  • change (onchange event handler)
    • Occurs when the user changes the value of a form element/fields
  • submit (onsubmit event handler)
    • Occurs only when the user submits a form on a web page

Syntax & Example:

<form action="" method="post" onsubmit="alert('Form data submitted to the server!');">

  <label>First Name:</label>
  <input type="text" name="first-name" onfocus="showHighlight(this)" onblur="resetHighlight(this)" required> <br/> <br/>

  <select onchange="alert('You have selected something!');">
      <option>Select</option>
      <option>Male</option>
      <option>Female</option>
  </select> <br/> <br/>

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


<script>

  // focus text field
  function showHighlight(curTxtField) {
    curTxtField.style.background = "pink";
  }

  function resetHighlight(curTxtField) {
    curTxtField.style.background = "white";
  }

</script>

13.02.04. Document/Window events

Events are happening/triggering all over. Events do trigger even when the page has loaded/unloaded or the user resizes the browser window. Mentioned here some of the most important document/window events and their event handler:

  • DOMContentLoaded (DOMContentLoaded event handler)
    • Occurs when the HTML is loaded and processed, DOM is fully built
  • load (onload event handler)
    • Occurs when web page has finished loading in the web browser
  • unload (onunload event handler)
    • Occurs when a user leaves the current web page

Note:
The unload event is not supported properly in most of the browsers.

Syntax & Example:

<body onload="window.alert('Page loaded successfully!');" onunload="window.alert('sure you want to leave this page?');">


<script>

   
</script>

13.03. Different ways to write the event handler

  1. HTML Attribute
  2. DOM element properties (anonymous function)

13.03.01. HTML attribute

Syntax & Example:

<h2 onclick="window.alert('HTML attribute onclick used here!')" style="color:#0000ff; cursor:pointer">    13.03.01. HTML attribute | Click Me!</h2>

<button onclick="alert('Hello world! Welcome to JavaScript Events!!')">Click here...</button>

<button onclick="fnShowMessage()">Invoke Function</button>


// event handler function

function fnShowMessage () {
  alert('Welcome to fnShowMessage event handler!');
  alert('Welcome to fnShowMessage event handler!');
}

Note:
This way should be avoided as it makes markup less readable and making it harder to find if there is any bug.

13.03.02. DOM element properties

Syntax & Example:

<button id="messageButton1">Click here...</button>
<button id="messageButton2">Click here...</button>


// DOM element properties

// method - 1
messageButton1.onclick = function () {
  alert('Welcome to event handler!');
  alert('Welcome to event handler!');
}

// method - 2
document.getElementById("messageButton2").onclick = fnShowMessage;

function fnShowMessage() {
  alert('Hello World! Welcome to JavaScript events');
}

Section 14. DOM (Document Object Model)

14.01. What is DOM?

14.01. What is the Document Object Model?

  • DOM represents the whole HTML document, DOM is a structure of HTML web page where all tags are defined in a structured/structural way
  • The Document Object Model (DOM) is the model that describes how all elements in an HTML page (like input fields, images, paragraphs, headings, etc.), are related to the topmost structure: the document itself
  • DOM defines the logical structure of the documents and how they can be accessed and manipulated
  • DOM is a W3C (World Wide Web Consortium) standard which defines a standard for accessing documents like programmers can build documents, navigate their structure, and add, modify, or delete elements and content
  • In DOM world always think in form/terms of Nodes (elements, its attributes, text, etc.)
  • Structural representation of HTML document (Tree of nodes/elements/tags)

14.02. Node

As we learned above, in DOM, all parts of the document (like elements, its attributes, text, etc.) are organized in a hierarchical tree-like structure; similar to a real-life family tree that consists of parents and children. In DOM terminology these individual parts of the document are known as nodes.

There are different types of nodes like: Elements, Attribute & Text Node.

Syntax & Example:

<ul id="list"> --> Element & Attribute NODE
  <li>first item </li> --> text NODE
</ul>

* Elements NODES does not contain text

Syntax & Example: In Browser Window -> Inspect Element (Developer Tools) -> Console: type following and check the output thoroughly

  • document - outputs the entire document/current page

  • document.all - shows HTMLAllCollection(1532) [html, head, meta (html tags)

  • document.url - displays current url/path

HTMLAllCollection(1532) [html, head, meta, link, link, link, link, link, link, link, link, link, meta, title, meta, link, link, meta, meta, meta, meta, meta, meta, meta, meta, meta,

14.03. JavaScript DOM Selectors

JavaScript is commonly used to find or select, to get or modify the content/value of the HTML elements on the page, and as well as to apply some effects (like show, hide, add events, animate, etc.)

DOM selectors are nothing but methods which helps to pull/traverse/navigate things (elements, nodes)f from the document and do some operations on the same.

Let's learn some of the common ways of selecting the elements on a page and do something using JavaScript.

14.03.01. Selecting Elements by ID (getElementById())

  • One can select an element based on its unique ID with the getElementById() method
  • getElementById() is the easiest and most common way to find/access an HTML element in the DOM tree
  • getElementById() method returns the element having the given id value

Syntax & Example:

// Selecting element with id 
let mainHeadingElement = document.getElementById('mainHeadingText');

// get html of selected element
let mainHeadingHtml = mainHeadingElement.innerHTML;

// get text of selected element
let mainHeadingText = mainHeadingElement.innerText;
alert('mainHeadingHtml: ' + mainHeadingHtml); // text with complete html tags
alert('mainHeadingText: ' + mainHeadingText); // only text

// alert('// ------------------------------');

// set text of selected element
mainHeadingElement.innerHTML = 'This text changed with DOM method...';

// alert('// ------------------------------');

// set text of another element
let subHeadingElement = document.getElementById('subHeadingText');
subHeadingElement.innerHTML = mainHeadingElement.innerHTML ;

// alert('// ------------------------------');

// set css style
mainHeadingElement.style.backgroundColor = 'pink';

14.04. JavaScript DOM CSS Styling

Using JavaScript we can also apply CSS style on HTML elements to change the visual look and feel specification/presentation of HTML documents dynamically/at run time. We can apply/set almost all the CSS styles for the elements like fonts, colors, margins, padding, borders, alignments, background images, width and height, position, and so on.

Naming Conventions of CSS Properties in JavaScript

  • CSS properties like font-size, background-image, text-decoration, etc. contain hyphens (-) in names
  • In JavaScript hyphens (-) is a reserved operator (a minus sign), so it is impossible to write an expression with hyphens (-), like: elem.style.font-size = '10px';
  • In JavaScript the CSS property names with hyphens are converted to intercapitalized style word (camelCasingNaming)
  • So CSS property font-size, background-color,border-left-style becomes the DOM property fontSize, borderLeftStyle respectively and so on

14.04.01. Applying/Setting Inline Styles on Elements

  • In HTML inline styles are applied directly to the specific HTML element using the style attribute, eg. <element style="color:red;">
  • In JavaScript the style property is used to get or set the inline style of an element, eg. elem.style.color = 'red';

Syntax & Example:

// Selecting element with id 
let mainHeadingElement = document.getElementById('mainHeadingText');

// set css style
mainHeadingElement.style.padding = '5px';
mainHeadingElement.style.backgroundColor = 'pink';
mainHeadingElement.style.color = 'blue';
mainHeadingElement.style.border = '5px solid #999999';

14.04.02. Retrieving/Getting CSS Styles details from Elements

  • We can get the styles applied on the HTML elements using the style property
  • style property only returns the style rules set in the element's style attribute, not those applied through internal/embedded style sheets, or external style sheets
  • To get the values of all CSS properties that actually render an element we can use the window.getComputedStyle() method

Syntax & Example:

// Selecting element with id 
let mainHeadingElement = document.getElementById('mainHeadingText');

// set css style
mainHeadingElement.style.padding = '5px';
mainHeadingElement.style.backgroundColor = 'pink';

// alert('// ------------------------------');

// get inline css styles
alert('mainHeadingElement.style.padding:',mainHeadingElement.style.padding);
alert('mainHeadingElement.style.backgroundColor:',mainHeadingElement.style.backgroundColor);

// alert('// ------------------------------');

14.04.03. Applying/Adding CSS Classes to Elements - className

  • We can also get or set CSS classes to the HTML elements using the className property
  • As class is a reserved word in JavaScript, it uses the className property to reference the value of the HTML class attribute

Syntax & Example:

// Selecting element with id 
let mainHeadingElement = document.getElementById('mainHeadingText');

// remove old classes and apply/set css class
mainHeadingElement.className = 'bg-color';

// apply/set css class
mainHeadingElement.className += ' border';

14.05. JavaScript DOM HTML get set attributes

  • An attribute in HTML provides extra information about the element, and it is applied within the start tag
  • An HTML attribute contains two fields: name & value / key & value
  • JavaScript provides several methods for adding, reading or removing an HTML element's attribute like setAttribute(), getAttribute(), removeAttribute()

14.05.01. Applying/Setting Attribute on Element

  • The setAttribute() method is used to set an attribute on the specified element
  • If the attribute already present/exists on the element, the attribute value will be updated; else a new attribute is added with the specified name and value

Syntax & Example:

// Selecting element with id 
let mainHeadingElement = document.getElementById('mainHeadingText');
let clickButtonElement = document.getElementById('clickButton');
let linkTextElement = document.getElementById('linkText');

// set attribute class named 'btn'
mainHeadingElement.setAttribute('class', 'btn');

// set attribute disabled
clickButtonElement.setAttribute('disabled', '');

// set blank/empty attribute so that it will remove exisiting attribute value
linkTextElement.setAttribute('href','');

14.05.02. Retrieving/Getting Attribute Value

  • The getAttribute() method is used to get the current value of an attribute on the element
  • If the specified attribute does not present/exists on the element, it will return null

Syntax & Example:

// Selecting element with id 
let mainHeadingElement = document.getElementById('mainHeadingText');
let clickButtonElement = document.getElementById('clickButton');
let linkTextElement = document.getElementById('linkText');

// getting the attributes values
let getAttrClass = mainHeadingElement.getAttribute('class');
alert('getAttrClass:', getAttrClass);

let getAttrDisabled = clickButtonElement.getAttribute('disabled');
alert('getAttrDisabled:', getAttrDisabled);

let getAttrHref = linkTextElement.getAttribute('href');
alert('getAttrHref:', getAttrHref);

14.05.03. Removing Attributes from Elements

  • The removeAttribute() method is used to remove an attribute from the specified element

Syntax & Example:

// Selecting element with id 
let mainHeadingElement = document.getElementById('mainHeadingText');
let clickButtonElement = document.getElementById('clickButton');
let linkTextElement = document.getElementById('linkText');

// removing the attributes 
mainHeadingElement.removeAttribute('class');

// verify/confirm class removed or not
alert('mainHeadingElement.getAttribute:', mainHeadingElement.getAttribute('class'));
alert('mainHeadingElement.classList.contains:', mainHeadingElement.classList.contains('class'));

// alert('// ------------------------------');

clickButtonElement.removeAttribute('disabled');

linkTextElement.removeAttribute('href');

14.05.04. Selecting document elements without selectors

14.05.04. Select HTMLCollection without selectors

Syntax & Example:

- document.forms
  - document.forms[0] or use respective form element index
  - document.forms[0].id
  - document.forms[1].method
  - document.forms[1].action

- document.links
  - document.links[0]
  - document.links[0].className //class names as a string
  - document.links[1].classList[] // collection of classes

- document.images
  - document.images[0]

- document.scripts
  - document.scripts[0]
  - document.scripts[1].getAttribute('src');

Section 15. What's Next Step?

Great Job! Thank You for looking into JavaScript for Beginners. I hope you enjoyed and learned a lot out of it. I think Now you have better understandings of how JavaScript works and functions. To learn more about JavaScript visit Mozilla JavaScript Reference Guide.

  • Your Next step could be looking into advanced topics of HTML5, [CSS3] or [JavaScript].
  • For detailed view on JavaScript look into [Advanced JavaScript Tutorial], JavaScript ES6 Tutorial or TypeScript Tutorials.
  • You may move forward with any famous and popular JavaScript Frameworks or Libraries like jQuery.js, Angular, React.js, NPM, Node.js, Vue.js etc.

Best of Luck! Happy Learning!

About

A JavaScript tutorials for beginners, An introduction to JavaScript programming languages building blocks, step-by-step guide to JavaScript

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages

  • HTML 83.3%
  • JavaScript 16.7%