Finding HTML Elements by Tag Name
This example demonstrates the getElementsByTagName method.
JavaScript is the world's most popular programming language.
JavaScript is the programming language of the Web.
JavaScript is easy to learn.
JavaScript and Java are completely different languages, both in concept and design.
JavaScript was invented by Brendan Eich in 1995, and became an ECMA standard in 1997.
ECMA-262 is the official name of the standard. ECMAScript is the official name of the language.
Javascript changing inner p element
Javascript can change size
Javascript can hide HTML elements
A Paragraph (Javascript in Head)
A Paragraph(Javascript in body)
Never call document.write after the document has finished loading. It will overwrite the whole document.
JavaScript changes the value of the src attribute of an < img > tag.
A JavaScript program is a list of statements to be executed by a computer.
The JavaScript syntax defines two types of values:
Fixed values
Variable values
Fixed values are called Literals.
Variable values are called Variables.
In a programming language, variables are used to store data values.
JavaScript uses the keywords var, let and const to declare variables.
An equal sign is used to assign values to variables.
The values can be of various types, such as numbers and strings. For example, "John" + " " + "Doe", evaluates to "John Doe":
Not all JavaScript statements are "executed".
Code after double slashes // or between /* and */ is treated as a comment.
Comments are ignored, and will not be executed:
JavaScript Identifiers
Identifiers are names.
In JavaScript, identifiers are used to name variables (and keywords, and functions, and labels).
The rules for legal names are much the same in most programming languages.
In JavaScript, the first character must be a letter, or an underscore (_), or a dollar sign ($).
Subsequent characters may be letters, digits, underscores, or dollar signs.
Numbers are not allowed as the first character.
This way JavaScript can easily distinguish identifiers from numbers.
JavaScript and Camel Case
Historically, programmers have used different ways of joining multiple words into one variable name:
Hyphens:
first-name, last-name, master-card, inter-city.
Hyphens are not allowed in JavaScript. They are reserved for subtractions.
Underscore:
first_name, last_name, master_card, inter_city.
Upper Camel Case (Pascal Case):
FirstName, LastName, MasterCard, InterCity.
Lower Camel Case:
JavaScript programmers tend to use camel case that starts with a lowercase letter:
firstName, lastName, masterCard, interCity.
There are 3 ways to declare a JavaScript variable:
Using var
Using let
Using const
The let keyword was introduced in ES6 (2015).
Variables defined with let cannot be Redeclared.
Variables defined with let must be Declared before use.
Variables defined with let have Block Scope.
ES6 introduced two important new JavaScript keywords: let and const.
These two keywords provide Block Scope in JavaScript.
Variables declared inside a { } block cannot be accessed from outside the block:
Variables declared with the var keyword can NOT have block scope.
Variables declared inside a { } block can be accessed from outside the block.
The const keyword was introduced in ES6 (2015).
Variables defined with const cannot be Redeclared.
Variables defined with const cannot be Reassigned.
Variables defined with const have Block Scope.
When to use JavaScript const?
As a general rule, always declare a variable with const unless you know that the value will change.
Use const when you declare:
A new Array
A new Object
A new Function
A new RegExp
Constant Objects and Arrays
The keyword const is a little misleading.
It does not define a constant value. It defines a constant reference to a value.
Because of this you can NOT:
Reassign a constant value
Reassign a constant array
Reassign a constant object
But you CAN:
Change the elements of constant array
Change the properties of constant object
Arithmetic operators are used to perform arithmetic on numbers:
Operator | Description |
---|---|
+ | Addition |
- | Subtraction |
* | Multiplication |
** | Exponentiation (ES2016) |
/ | Division |
% | Modulus (Division Remainder) |
++ | Increment |
-- | Decrement |
Assignment operators assign values to JavaScript variables.
Operator | Example | Same As |
---|---|---|
= | x = y | x = y |
+= | x += y | x = x + y |
-= | x -= y | x = x - y |
*= | x *= y | x = x * y |
/= | x /= y | x = x / y |
%= | x %= y | x = x % y |
**= | x **= y | x = x ** y |
Declaring a constant object does NOT make the objects properties unchangeable:
Exponentiation : the operation of raising one quantity to the power of another
The +
operator can also be used to add (concatenate) strings.
The +=
assignment operator can also be used to add (concatenate) strings:
Adding two numbers, will return the sum, but adding a number and a string will return a string:
Operator | Description |
---|---|
== | equal to |
=== | equal value and equal type |
!= | not equal |
!== | not equal value or not equal type |
> | greater than |
< | less than |
>= | greater than or equal to |
<= | less than or equal to |
? | ternary operator |
Operator | Description |
---|---|
&& | logical and |
|| | logical or |
! | logical not |
Operator | Description |
---|---|
typeof | Returns the type of a variable |
instanceof | Returns true if an object is an instance of an object type |
Bit operators work on 32 bits numbers.
Any numeric operand in the operation is converted into a 32 bit number. The result is converted back to a JavaScript number.Operator | Description | Example | Same as | Result | Decimal |
---|---|---|---|---|---|
& | AND | 5 & 1 | 0101 & 0001 | 0001 | 1 |
| | OR | 5 | 1 | 0101 | 0001 | 0101 | 5 |
~ | NOT | ~ 5 | ~0101 | 1010 | 10 |
^ | XOR | 5 ^ 1 | 0101 ^ 0001 | 0100 | 4 |
<< | Zero fill left shift | 5 << 1 | 0101 << 1 | 1010 | 10 |
>> | Signed right shift | 5 >> 1 | 0101 >> 1 | 0010 | 2 |
>>> | Zero fill right shift | 5 >>> 1 | 0101 >>> 1 | 0010 | 2 |
Pale red entries indicates ECMAScript 2015 (ES6) or higher.
Value | Operator | Description | Example |
---|---|---|---|
21 | ( ) | Expression grouping | (3 + 4) |
20 | . | Member | person.name |
20 | [] | Member | person["name"] |
20 | () | Function call | myFunction() |
20 | new | Create | new Date() |
18 | ++ | Postfix Increment | i++ |
18 | -- | Postfix Decrement | i-- |
17 | ++ | Prefix Increment | ++i |
17 | -- | Prefix Decrement | --i |
17 | ! | Logical not | !(x==y) |
17 | typeof | Type | typeof x |
16 | ** | Exponentiation (ES2016) | 10 ** 2 |
15 | * | Multiplication | 10 * 5 |
15 | / | Division | 10 / 5 |
15 | % | Division Remainder | 10 % 5 |
14 | + | Addition | 10 + 5 |
14 | - | Subtraction | 10 - 5 |
13 | << | Shift left | x << 2 |
13 | >> | Shift right | x >> 2 |
13 | >>> | Shift right (unsigned) | x >>> 2 |
12 | < | Less than | x < y |
12 | <= | Less than or equal | x <= y |
12 | > | Greater than | x > y |
12 | >= | Greater than or equal | x >= y |
12 | in | Property in Object | "PI" in Math |
12 | instanceof | Instance of Object | instanceof Array |
11 | == | Equal | x == y |
11 | === | Strict equal | x === y |
11 | != | Unequal | x != y |
11 | !== | Strict unequal | x !== y |
10 | & | Bitwise AND | x & y |
9 | ^ | Bitwise XOR | x ^ y |
8 | | | Bitwise OR | x | y |
7 | && | Logical AND | x && y |
6 | || | Logical OR | x || y |
5 | ?? | Nullish Coalescing | x ?? y |
4 | ? : | Condition | ? "Yes" : "No" |
3 | += | Assignment | x += y |
3 | /= | Assignment | x /= y |
3 | -= | Assignment | x -= y |
3 | *= | Assignment | x *= y |
3 | %= | Assignment | x %= y |
3 | <<= | Assignment | x <<= y |
3 | >>= | Assignment | x >>= y |
3 | >>>= | Assignment | x >>>= y |
3 | &= | Assignment | x &= y |
3 | ^= | Assignment | x ^= y |
3 | |= | Assignment | x |= y |
2 | yield | Pause Function | yield x |
1 | , | Comma | 5 , 6 |
Expressions in parentheses are fully computed before the value is used in the rest of the expression.
Accessing a function without () will return the function definition instead of the function result:
txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
var x = "John"; var y = new String("John");
Also note that comparing two JavaScript objects will always return false.
JavaScript will try to convert strings to numbers in all numeric operations:
var x = "100";
var y = "10";
NaN - Not A Number
JavaScript interprets numeric constants as hexadecimal if they are preceded by 0x :
you can use the toString() method to output numbers from base 2 to base 36. Hexadecimal is base 16. Decimal is base 10. Octal is base 8. Binary is base 2.
Comparing two JavaScript objects will always return false.
Number()method :
parseInt() Method :
parseFloat() Method :
Number Properties :
These properties can only be accessed as Number.MAX_VALUE.
Using myNumber.MAX_VALUE, where myNumber is a variable, expression, or value, will return undefined
you can have variables of different types in the same Array. You can have objects in an Array. You can have functions in an Array. You can have arrays in an Array
You can also use the Array.forEach() function:
ArrayName.constructor.toString().indexOf(Array)>-1 is one type method
ArrayName instanceof Array is a method :
Using delete may leave undefined holes in the array. Use pop() or shift() instead.
The concat() method does not change the existing arrays. It always returns a new array.
The slice() method creates a new array. It does not remove any elements from the source array.
Alphabetical Sort :
Numeric Sort :
array.sort(), is not accurate, it will favor some numbers over the others. The most popular correct method, is called the Fisher Yates shuffle
Random Array Sorting :
Object Sort Numeric properties :MAX AND MIN
Array.forEach() Method :
The forEach() method calls a function (a callback function) once for each array element.
Array.map() Method :
The map() method creates a new array by performing a function on each array element.
The map() method does not execute the function for array elements without values.
The map() method does not change the original array.
This example multiplies each array value by 2:
Array.filter() Method :
The filter() method creates a new array with array elements that passes a test.
This example creates a new array from elements with a value larger than 18:
Array.reduce() Method :
The reduce() method runs a function on each array element to produce (reduce it to) a single value.
The reduce() method works from left-to-right in the array. See also reduceRight().
The reduce() method does not reduce the original array.
This example finds the sum of all numbers in an array:
Array.reduceRight() Method :
The reduceRight() works from right-to-left in the array.
Array.every() Method :
The every() method check if all array values pass a test.
This example check if all array values are larger than 18:
Array.some() Method :
The some() method check if some array values pass a test.
Array.find() Method :
The find() method returns the value of the first array element that passes a test function.
This example finds (returns the value of) the first element that is larger than 18:
You cannot omit month. If you supply only one parameter it will be treated as milliseconds.
One and two digit years will be interpreted as 19xx:
Everything With a "Value" is True.
Everything Without a "Value" is False.
Input your age and click the button:
Input your age and click the button:
Switch Method :
If multiple cases matches a case value, the first case is selected.
If no matching cases are found, the program continues to the default label.
If no default label is found, the program continues to the statement(s) after the switch.
Switch cases use strict comparison (===).
For Loop :
Statement 1 :
This is not always the case, JavaScript doesn't care. Statement 1 is optional.
You can initiate many values in statement 1
And you can omit statement 1 (like when your values are set before the loop starts):
Statement 2 :
This is not always the case, JavaScript doesn't care. Statement 2 is also optional.
If statement 2 returns true, the loop will start over again, if it returns false, the loop will end.
Statement 3 :
This is not always the case, JavaScript doesn't care, and statement 3 is optional.
Statement 3 can do anything like negative increment (i--), positive increment (i = i + 15), or anything else.
Statement 3 can also be omitted (like when you increment your values inside the loop):
For Loop :
The JavaScript for in statement loops through the properties of an Object:
The JavaScript for in statement can also loop over the properties of an Array:
The forEach() method calls a function (a callback function) once for each array element.
JavaScript Labels :
To label JavaScript statements you precede the statements with a label name and a colon:
Syntax :
label:
statements
In JavaScript there are 5 different data types that can contain values:
string
number
boolean
object
function
There are 6 types of objects:
Object
Date
Array
String
Number
Boolean
And 2 data types that cannot contain values:
null
undefined
Number Method () :
The global method Number() can convert strings to numbers.
Strings containing numbers (like "3.14") convert to numbers (like 3.14).
Empty strings convert to 0.
Anything else converts to NaN (Not a Number).
Please input a number between 5 and 10:
If you assign a value to a variable that has not been declared, it will automatically become a GLOBAL variable :
Hoisting is JavaScript's default behavior of moving all declarations to the top of the current scope.
It has different values depending on where it is used:
In a method, this refers to the owner object.
Alone, this refers to the global object.
In a function, this refers to the global object.
In a function, in strict mode, this is undefined.
In an event, this refers to the element that received the event.
Methods like call(), and apply() can refer this to any object.
JavaScript Arrow Function :
This example shows the syntax of an Arrow Function, and how to use it.
How to use a JavaScript Class.
How to define and use a Class method.
If you expect to access a DOM element several times, access it once, and the use it as a local variable:
Types of Creating Object :
Using an Object Literal
An object literal is a list of name:value pairs (like age:50) inside curly braces {}.
This example creates an empty JavaScript object, and then adds 4 properties:
Using the JavaScript Keyword new :
The following example create a new JavaScript object using new Object(), and then adds 4 properties:
JavaScript Objects are Mutable :
Objects are mutable: They are addressed by reference, not by value.
The object x is not a copy of person. It is person. Both x and person are the same object.
Any changes to x will also change person, because x and person are the same object.
Accessing JavaScript Properties :
example 1 :
Example 2 :
JavaScript for...in Loop :
Adding New Properties and Deleting Properties :
Nested Objects :
Values in an object can be another object:
Nested Arrays and Objects :
Values in objects can be arrays, and values in arrays can be objects:
Adding a Method to an Object :
JavaScript Object Accessors
JavaScript Getter (The get Keyword) :
JavaScript Setter (The set Keyword) :
Differences between JavaScript Function or Getter :
JavaScript Object Constructors :
// Create object with an existing object as prototype
Object.create()
// Adding or changing an object property
Object.defineProperty(object, property, descriptor)
// Adding or changing object properties
Object.defineProperties(object, descriptors)
// Accessing Properties
Object.getOwnPropertyDescriptor(object, property)
// Returns all properties as an array
Object.getOwnPropertyNames(object)
// Accessing the prototype
Object.getPrototypeOf(object)
// Returns enumerable properties as an array
Object.keys(object)
// Prevents adding properties to an object
Object.preventExtensions(object)
// Returns true if properties can be added to an object
Object.isExtensible(object)
// Prevents changes of object properties (not values)
Object.seal(object)
// Returns true if object is sealed
Object.isSealed(object)
// Prevents any changes to an object
Object.freeze(object)
// Returns true if object is frozen
Object.isFrozen(object)
writable : true // Property value can be changed
enumerable : true // Property can be enumerated
configurable : true // Property can be reconfigured
writable : false // Property value can not be changed
enumerable : false // Property can be not enumerated
configurable : false // Property can be not reconfigured
A Map object holds key-value pairs where the keys can be any datatype.
A Map object remembers the original insertion order of the keys.
A Map object has a property that represents the size of the map.
Essensial Map() Methods :
new Map() Creates a new Map object
set() Sets a value for a key in a Map object
get() Gets a value for a key in a Map object
entries() Returns an array of the key/value pairs in a Map object
keys() Returns an array of the keys in a Map object
values() Returns an array of the values in a Map object
Map() Properties
size Gets a value for a key in a Map object
Other Map() Methods :
clear() Removes all elements in a Map
delete() Removes an element specified by a key.
has() Returns true if a key exists.
forEach() Invokes a callback for each key/value pair.
JavaScript Set Objects :
Create a Set and add existing variables :
Create a Set and add literal values :
Pass an Array to the new Set() constructor :
Set Object Methods and Properties :
new Set() Creates a new Set object
add() Adds a new element to the Set
clear() Removes all elements from a Set
delete() Removes an element specified by its value.
entries() Returns an array of the values in a Set object
has() Returns true if a value exists
forEach() Invokes a callback for each element
keys() Returns an array of the values in a Set object
values() Same as keys()
size Returns the element count
The Function() Constructor :
Hoisting is JavaScript's default behavior of moving declarations to the top of the current scope.
Hoisting applies to variable declarations and to function declarations.
If a function is called with missing arguments (less than declared), the missing values are set to undefined.
JavaScript functions have a built-in object called the arguments object.
The argument object contains an array of the arguments used when the function was called (invoked).
With the call() method, you can write a method that can be used on different objects.
With call(), an object can use a method belonging to another object.
0
Unlike functions, and other JavaScript declarations, class declarations are not hoisted.
That means that you must declare a class before you can use it:
Static class methods are defined on the class itself.
You cannot call a static method on an object, only on an object class.
You can call 'hello()' on the Car Class:
But NOT on a Car Object:
If you want to use the myCar object inside the static method, you can send it as a parameter :
The DOM is a W3C (World Wide Web Consortium) standard.
The DOM defines a standard for accessing documents:
"The W3C Document Object Model (DOM) is a platform and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure, and style of a document."
The W3C DOM standard is separated into 3 different parts:
Core DOM - standard model for all document types
XML DOM - standard model for XML documents
HTML DOM - standard model for HTML documents
What is the HTML DOM?
The HTML DOM is a standard object model and programming interface for HTML. It defines:
The HTML elements as objects
The properties of all HTML elements
The methods to access all HTML elements
The events for all HTML elements
In other words: The HTML DOM is a standard for how to get, change, add, or delete HTML elements.
HI
HI1
Finding HTML Elements by Tag Name
This example demonstrates the getElementsByTagName method.
Hello World!
This example demonstrates the getElementsByClassName method.
HI2
HI3
HI4
Please input a number between 1 and 10
This is atext. This is a text. This is a text. This is a text.
HI6
HI7
Enter your Name :HI8
Window Resize Random Number
Click me!
Click me!
This div element has an onmousemove event handler that displays a random number every time you move your mouse inside this orange field.
Click the remove button to remove the div's event handler.
Click the add button to add the div's event handler.
Commented This in Javascript
Commented This in Javascript
Creating HTML Element in Javascript
This is a Paragraph
This is another Paragraph
Removed 18 p Element
Removing Element
Enter a number between 100 to 300 and click OK:
Enter a number below 100 and click OK:
Enter a number and click OK:
When you write something inside ${} in a template literal, its result will be computed, converted to a string, and included at that position.
There is only one value in JavaScript that is not equal to itself, and that is NaN
The rules for converting strings and numbers to Boolean values state that 0, NaN, and the empty string ("") count as false
So 0 || -1 produces -1, and "" || "!?" yields "!?".
The function Number converts a value to a number. We need that conversion because the result of prompt is a string value, and we want a number.
The Number.isNaN function is a standard JavaScript function that returns true only if the argument it is given is NaN