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.
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:
- The Internet and the World Wide Web (WWW) Web Design Development Foundations-Web Technology Fundamentals
- Good working knowledge of HyperText Markup Language (HTML) HTML5 Essentials and
- Its good to know CSS3 Fundamentals
- Introducing JavaScript
- 02.02. What is JavaScript?
- 02.03. What is a scripting language?
- 02.04. What can you do with JavaScript? | Use of JavaScript?
- JavaScript Getting Started
- 03.01. How to write Javascript? | JavaScript in HTML
- 03.02. Where to write JavaScript in HTML? | Where to embed include write put JavaScript in HTML?
- 03.03. JavaScript Code structure
- 03.04. JavaScript Keywords
- 03.05. Comments
- JavaScript Language Fundamentals
- 04.01. Generating Output
- Variables
- Data types
- 06.01. Data types
- 06.02. Primitive data type | Primitive, Primary or Value data type
- 06.03. Non-primitive data type | Non-primitive, Reference or Composite data type
- 06.04. JavaScript has Dynamic Types
- 06.05. The typeof Operator
- 06.06. Type conversion | typeof parseInt parseFloat
- 06.07. Type coercion
- Operators
- 07.01. What is the Operator?
- 07.02. Arithmetic Operators
- 07.03. Assignment Operators
- 07.04. Logical Operators
- 07.05. Comparison Operators | Relational Operators
- 07.06. Conditional Operator | Ternary Operator
- 07.07. String Operators
- 07.08. Operator precedence
- Functions
- 08.01. What is a Function?
- 08.02. Types of Function
- 08.03. Different ways to define Function
- 08.04. String Methods and Concatenation
- Loops | Loops and Iterations
- 09.01. The for loop
- 09.02. The while loop
- 09.03. The do while loop
- Conditions - Control Flow
- Array
- 11.01. What is an Array?
- 11.02. Create Array by array literal
- 11.03. Create Array by creating an instance of array directly
- 11.04. Create Array by using an array constructor
- 11.05. Getting the Length of an Array
- 11.06. Accessing Looping through an Array Elements | Loop through an Array Elements
- 11.09. Array properties and methods
- Objects
- 12.01. The Window object
- 12.02. The Math Object
- 12.03. Date and Time
- Events
- DOM (Document Object Model)
- 14.01. What is DOM? | What is the Document Object Model?
- 14.02. Node
- 14.03. JavaScript DOM Selectors
- 14.04. JavaScript DOM CSS Styling
- 14.05. JavaScript DOM HTML get set attributes
- JavaScript is
1 of the 3 core language/layersof web...(HTML, CSS & JavaScript) - JavaScript is a dynamic computer programming language. It is an
interpreted (translated)programming language withobject-oriented capabilities - JavaScript is case sensitive language
Note:
Now-a-days with the help ofNode (Node.js)JavaScript is used forBack-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.
- 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 programneeds to be compiled before running whereas normally, a scripting language likeJavaScript or PHPneed not be compiled
- A script is nothing but sets of instructions
- JavaScript gives HTML designers a
programming tool - JavaScript can react to
events(mouse click, hover (rollover, rollout), focus, blur) - JavaScript can be used to
validatedata (Client-side validation) - JavaScript can manipulate
HTML contentandCSS styles - Displaying live/current/dynamic
date and time (clocks) - Displaying
pop-up windowsanddialog boxes(analert,confirmandpromptdialog box) - Change the website's
behaviorand make it moredynamic with advancedweb designs
- 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
JavaScript was originally designed and developed to run only in browsers.
-
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)
-
Browsers - To view output of .html pages with .js files -
Google Chrome, Mozilla Firefox, Internet Explorer, Safarietc.- 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
-
JavaScript Output / Debugging Tool (Developer console) -
- alert() or window.alert()
- Google Chrome / Safari –
Developer Tools Inspect/ Inpsect element (in browser -> Right Click on page -> chooseInspect / Inspect Element -> Console Tab - Mozilla FireFox –
Firebug
- 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 ofbodytag/section ie. just before the closing</body>tag
- So the best practice is to place/add the
Note:
JavaScript is the default scripting language in HTML. The old HTML standard attributes liketype="text/javascript"andlanguage="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>- Inside the HEAD section
- Inside the BODY section
- External JavaScript .js file (separation of concern)
- 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 thehead section (<head> elementof 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>- 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 thebody section, just before theclosing </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>- 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 separateour JavaScript behavior code from our HTML markup code - We can use/add/attach an external JavaScript file by using
<script>tag withsrc (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>');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:
- 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
- JavaScript statements are generally followed by a
semicolon; character - JavaScript interprets the line break as an
implicitsemicolon, called anautomatic semicolon insertion
Note:
It is a good programming practice to use semicolons; after every statement
- 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';andvar FirstName='b';herefirstName & FirstNameare different ie. two different variable
Note:
Take care/precautions while writing variable and function names in JavaScript
- 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();- 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- 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. */- JavaScript does not have any
display or built-in printfunctions
- Writing into an alert box with
alert() or window.alert() - Writing into the HTML / Browser Window with
document.write() - Write into an element of HTML / Inserting Output Inside an HTML Element with
innerHTML
- One can use
alert dialog boxesto 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');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');- We can write or insert output inside an HTML element using the element's
innerHTMLproperty - 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>';- A JavaScript variable is simply a
name of the storage location (named containers/named storage)for data - Variables are declared using the keyword
varkeyword - The
assignment operator (=)is used to assign value to a variable, like this:var varName = value;orvar 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 withletkeyword: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 literalVariables 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';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;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 & FirstNameare different ie. two different variable
- Example: var firstName='Sarra'; and var FirstName='Sarra'; here
- 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;- Use
constto declare a constant(read-only / unchanging)variable - Constants are
read-only, youcannot reassign new valuesto them
Syntax & Example:
05.06.02.script.js
// traditional var syntax
const PI1 = 3.14;
PI1 = 100; // errorA 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:
- Primitive (Primary or Value) data type
- String
- Number
- Boolean
- Undefined
- Null
- Non-primitive (Reference or Composite) data type
- Array
- Object
- Function
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 |
- 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';- 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;- 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 testingof code - Example:
var isDone = true;
var isMarried = false;- 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;- The typeof operator returns the
type of the argument - It can be used with or without parentheses
(typeof(x)ortypeof 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"- 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');- JavaScript ability to convert type automatically :
Syntax & Example:
const num1 = '20';
const num1 = 10;
const sum = num1 + num2;
alert(sum);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- 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- 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) |
- 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); // trueVariables 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!- The function declaration starts by using the
function keyword, - followed by a
unique function name, - a list of
parameters in parenthesesi.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');
}- 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();
- Regular Function
- Parameterized Function
- Return Type Function (Function returning values)
- 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();- 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);- A function can
return a valueback to the script that called thefunction, 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);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)
- 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));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));
- Loops are used to execute the
same block of code again, with a different value, until a certain condition is met
- for loop
- while loop
- do...while loop
- for...in loop
- for...each
- The
Forloop is used to run a piece of code aset 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 conditionis met - The for loop is the most simple/compact form of looping
- For loop consists of 3 statements (), mostly
i = indexis 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);
}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);
} */
}- 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++;
}- 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); - 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: >, <, >=, <=, ==, !=, ===
- If Statement
- If...else Statement
- If...else if...else Statement
- Switch...Case Statement
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!');
}- The JavaScript
if...else statementis used to execute the codeweather 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!');
}- 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 withnewkeyword - Array items are normally separated with
commas, - Arrays are
zero-indexedi.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 anumeric position, known as itsindex,starts from 0, so that the first array element position/index isarr[0]not arr[1]
There are 3 main ways to construct an array:
- By array literal
- By creating an instance of Array directly (using the new keyword)
- By using an Array constructor (using the new keyword)
- 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);- Array instance can be created using the
newkeywordnew 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- Array instance can be created using the
newkeywordnew Array() passing argumentsin 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');- The
lengthproperty returns thelength of an array,total number of elementsin an array lengthproperty brings back anarray length - the fixed amount of itemsstored 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>');
}- One can add/edit an array element by simply specifying
array[index] and valueie.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);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));- JavaScript is an
object-based languageand in JavaScript, almost everything is an object or acts like/as an 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-> TypeWindow, 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
- 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();- 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 detectthem 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
listenfor it and supply acallback function or event handlerwhich will be called by the browser when the event occurs
In general, the events can be categorized into four main groups:
- Mouse events
- Keyboard events
- Form events
- Document/Window 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 (
onclickevent handler)- Occurs When the
mouse clicks on an element, links, buttons etc. on a web page
- Occurs When the
- contextmenu (
oncontextmenuevent handler)- Occurs when a
user clicks the right mouse buttonon an element to open a context menu
- Occurs when a
- mouseover / mouseout (
onmouseover&onmouseoutevent 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 (
onmousemoveevent 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>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&onkeyupevent handler)- Occurs when the user presses down a key and then releases the button/a key on the keyboard
- keypress (
onkeypressevent 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!')"/>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 (
onfocusevent handler)- Occurs when the user focuses on an element on a web page, e.g. on an
inputtext field
- Occurs when the user focuses on an element on a web page, e.g. on an
- blur (
onblurevent handler)- Occurs when the user takes the focus away from a form element or a window
- change (
onchangeevent handler)- Occurs when the user changes the value of a form element/fields
- submit (
onsubmitevent 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>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 (
DOMContentLoadedevent handler)- Occurs when the HTML is loaded and processed, DOM is fully built
- load (
onloadevent handler)- Occurs when web page has finished loading in the web browser
- unload (
onunloadevent 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>- HTML Attribute
- DOM element properties (anonymous function)
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.
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');
}- 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)
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 textSyntax & 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,
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.
- One can select an element based on its
unique IDwith thegetElementById()method getElementById()is the easiest and most common way to find/access an HTML element in the DOM treegetElementById()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';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.
- CSS properties like
font-size,background-image,text-decoration, etc. containhyphens (-)in names - In JavaScript
hyphens (-)is a reserved operator (a minus sign), so it is impossible to write an expression withhyphens (-), 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-stylebecomes the DOM propertyfontSize,borderLeftStylerespectively and so on
- 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 propertyis 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';- We can get the styles applied on the HTML elements using the
style property style propertyonly 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('// ------------------------------');- We can also get or set CSS classes to the HTML elements using the
className property - As
classis a reserved word in JavaScript, it uses theclassNameproperty 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';- An attribute in HTML
provides extra informationabout 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()
- 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','');- 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);- 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');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');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!
