0% found this document useful (0 votes)
16K views635 pages

JavaScript PDF

This document provides an introduction and overview of JavaScript. It explains that JavaScript is the programming language of the web and allows for dynamic interactions on web pages. The document then provides examples of common JavaScript tasks like changing HTML content and styles, hiding and showing elements, and using functions and events. It also discusses best practices for including JavaScript in HTML pages using <script> tags in the <head> or <body>, or linking to external JavaScript files. The document concludes by demonstrating different ways JavaScript can output data, such as using window alerts, document.write(), and modifying innerHTML of elements.

Uploaded by

Tatiana Bodrug
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
16K views635 pages

JavaScript PDF

This document provides an introduction and overview of JavaScript. It explains that JavaScript is the programming language of the web and allows for dynamic interactions on web pages. The document then provides examples of common JavaScript tasks like changing HTML content and styles, hiding and showing elements, and using functions and events. It also discusses best practices for including JavaScript in HTML pages using <script> tags in the <head> or <body>, or linking to external JavaScript files. The document concludes by demonstrating different ways JavaScript can output data, such as using window alerts, document.write(), and modifying innerHTML of elements.

Uploaded by

Tatiana Bodrug
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 635

www.Sohrabpoor.

com
Iauc.ac.ir

H.sohrabpoor@gmail.com
www.Sohrabpoor.com

JavaScript Tutorial
JavaScript is the programming language of HTML and the Web.

Programming makes computers do what you want them to do.

JavaScript is easy to learn.

This tutorial will teach you JavaScript from basic to advanced.

Examples in Each Chapter


With our "Try it Yourself" editor, you can change all examples and view the
results.

Example

My First JavaScript
Click me to display Date and Time

Try it Yourself »

<!DOCTYPE html>

<body>

<h1> My First JavaScript </h1>

<button type="button" onclick="document.getElementById('demo').innerHTML = Date()">

Click me to display Date and Time.</button>

<p id="demo"> </p>

</body>

</html>

We recommend reading this tutorial, in the sequence listed in the left menu.

1
www.Sohrabpoor.com

Learn by Examples
Examples are better than 1000 words. Examples are often easier to
understand than text explanations.

This tutorial supplements all explanations with clarifying "Try it Yourself"


examples.

If you try all the examples, you will learn a lot about JavaScript, in a very
short time!

Why Study JavaScript?


JavaScript is one of the 3 languages all web developers must learn:

1. HTML to define the content of web pages

2. CSS to specify the layout of web pages

3. JavaScript to program the behavior of web pages

This tutorial is about JavaScript, and how JavaScript works with HTML and
CSS.

Learning Speed
In this tutorial, the learning speed is your choice.

Everything is up to you.

If you are struggling, take a break, or reread the material.

Always make sure you understand the "Try-it-Yourself" examples and


exercises.

JavaScript References
W3Schools maintains a complete JavaScript reference, including all HTML
DOM, and browser objects.

The reference contains examples for all objects, properties, and methods,
and is continuously updated according to the latest web standards.

2
www.Sohrabpoor.com

JavaScript Quiz Test


Test your JavaScript skills at W3Schools!

Start JavaScript Quiz!

Did You Know?


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. ECMAScript 6 (released in June 2015) is the
latest JavaScript version.

JavaScript Introduction
This page contains some examples of what JavaScript can do.

JavaScript Can Change HTML Content


One of many JavaScript HTML methods is getElementById().

This example uses the method to "find" an HTML element (with id="demo") and changes the
element content (innerHTML) to "Hello JavaScript":

Example
document.getElementById("demo").innerHTML = "Hello JavaScript";

Try it Yourself »

<p id="demo">JavaScript can change HTML content.</p>

<button type="button" onclick="document.getElementById('demo').innerHTML = 'Hello


JavaScript!'">Click Me!</button>

JavaScript Can Change HTML Attributes


This example changes an HTML image by changing the src (source) attribute of an <img>
tag:

3
www.Sohrabpoor.com

The Light Bulb

Turn on the light Turn off the light

Try it Yourself »

<button onclick="document.getElementById('myImage').src='pic_bulbon.gif'">Turn on the


light</button>

<img id="myImage" src="pic_bulboff.gif" style="width:100px">

<button onclick="document.getElementById('myImage').src='pic_bulboff.gif'">Turn off the


light</button>

JavaScript Can Change HTML Styles (CSS)


Changing the style of an HTML element, is a variant of changing an HTML attribute:

Example
document.getElementById("demo").style.fontSize = "25px";

Try it Yourself »

<p id="demo">JavaScript can change the style of an HTML element.</p>

<button type="button" onclick="document.getElementById('demo').style.fontSize='35px'">Click


Me!</button>

JavaScript Can Hide HTML Elements


Hiding HTML elements can be done by changing the display style:

Example
document.getElementById("demo").style.display="none";

Try it Yourself »

4
www.Sohrabpoor.com

<p id="demo">JavaScript can hide HTML elements.</p>

<button type="button" onclick="document.getElementById('demo').style.display='none'">Click


Me!</button>

JavaScript Can Show HTML Elements


Showing hidden HTML elements can also be done by changing the display style:

Example
document.getElementById("demo").style.display="block";

Try it Yourself »

<p id="demo" style="display:none">Hello JavaScript!</p>

<button type="button" onclick="document.getElementById('demo').style.display='block'">Click


Me!</button>

JavaScript Where To
JavaScript can be placed in the <body> and the <head> sections of an
HTML page.

The <script> Tag


In HTML, JavaScript code must be inserted between <script> and </script>
tags.

Example

5
www.Sohrabpoor.com

<script>
document.getElementById("demo").innerHTML = "My First JavaScript";
</script>

Older examples may use a type attribute: <script type="text/javascript">.


This type attribute is not required. JavaScript is the default scripting
language in HTML

JavaScript Functions and Events


A JavaScript function is a block of JavaScript code, that can be executed
when "asked" for.

For example, a function can be executed when an event occurs, like when
the user clicks a button.

You will learn much more about functions and events in later chapters.

JavaScript in <head> or <body>


You can place any number of scripts in an HTML document.

Scripts can be placed in the <body>, or in the <head> section of an HTML


page, or in both.

Keeping all code in one place, is always a good habit.

JavaScript in <head>
In this example, a JavaScript function is placed in the <head> section of an
HTML page.

The function is invoked (called) when a button is clicked:

Example

6
www.Sohrabpoor.com

<!DOCTYPE html>
<html>

<head>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph
changed.";
}
</script>
</head>

<body>

<h1>My Web Page</h1>

<p id="demo">A Paragraph</p>

<button type="button" onclick="myFunction()">Try it</button>

</body>
</html>

Try it Yourself »

JavaScript in <body>
In this example, a JavaScript function is placed in the <body> section of an
HTML page.

The function is invoked (called) when a button is clicked:

Example

7
www.Sohrabpoor.com

<!DOCTYPE html>
<html>
<body>

<h1>My Web Page</h1>

<p id="demo">A Paragraph</p>

<button type="button" onclick="myFunction()">Try it</button>

<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>

</body>
</html>

Try it Yourself »

It is a good idea to place scripts at the bottom of the <body> element.


This can improve page load, because script compilation can slow down the
display.

External JavaScript
Scripts can also be placed in external files:

myScript.js
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}

External scripts are practical when the same code is used in many different
web pages.

JavaScript files have the file extension .js.

To use an external script, put the name of the script file in the src (source)
attribute of a <script> tag:

Example

8
www.Sohrabpoor.com

<!DOCTYPE html>
<html>
<body>
<script src="myScript.js"></script>
</body>
</html>

Try it Yourself »

<p id="demo">A Paragraph.</p>

<button type="button" onclick="myFunction()">Try it</button>

<p><strong>Note:</strong> myFunction is stored in an external file called


"myScript.js".</p>

<script src="myScript.js"></script>

You can place an external script reference in <head> or <body> as you like.

The script will behave as if it was located exactly where the <script> tag is
located.

External scripts cannot contain <script> tags.

External JavaScript Advantages


Placing JavaScripts in external files has some advantages:

 It separates HTML and code


 It makes HTML and JavaScript easier to read and maintain
 Cached JavaScript files can speed up page loads

JavaScript Output
9
www.Sohrabpoor.com

JavaScript does NOT have any built-in print or display functions.

JavaScript Display Possibilities


JavaScript can "display" data in different ways:

 Writing into an alert box, using window.alert().


 Writing into the HTML output using document.write().
 Writing into an HTML element, using innerHTML.
 Writing into the browser console, using console.log().

Using window.alert()
You can use an alert box to display data:

Example
<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>


<p>My first paragraph.</p>

<script>
window.alert(5 + 6);
</script>

</body>
</html>

Try it Yourself »

Using document.write()
For testing purposes, it is convenient to use document.write():

Example
<!DOCTYPE html>
<html>
<body>

10
www.Sohrabpoor.com

<h1>My First Web Page</h1>


<p>My first paragraph.</p>

<script>
document.write(5 + 6);
</script>

</body>
</html>

Try it Yourself »

Using document.write() after an HTML document is fully loaded, will delete


all existing HTML:

Example
<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>


<p>My first paragraph.</p>

<button onclick="document.write(5 + 6)">Try it</button>

</body>
</html>

Try it Yourself »

The document.write() method should only be used for testing.

Using innerHTML
To access an HTML element, JavaScript can use
the document.getElementById(id) method.

The id attribute defines the HTML element. The innerHTML property defines
the HTML content:

Example
<!DOCTYPE html>
<html>

11
www.Sohrabpoor.com

<body>

<h1>My First Web Page</h1>


<p>My First Paragraph</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>

</body>
</html>

Try it Yourself »

To "display data" in HTML, (in most cases) you will set the value of an
innerHTML property.

Using console.log()
In your browser, you can use the console.log() method to display data.

Activate the browser console with F12, and select "Console" in the menu.

Example
<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>


<p>My first paragraph.</p>

<script>
console.log(5 + 6);
</script>

</body>
</html>

Try it Yourself »

JavaScript Syntax
12
www.Sohrabpoor.com

JavaScript syntax is the set of rules, how JavaScript programs are


constructed.

JavaScript Programs
A computer program is a list of "instructions" to be "executed" by the
computer.

In a programming language, these program instructions are


called statements.

JavaScript is a programming language.

JavaScript statements are separated by semicolons.

Example
<p id="demo"></p>
<script>
var x = 5;
var y = 6;
var z = x + y;
document.getElementById("demo").innerHTML = z;
</script>

Try it Yourself »

In HTML, JavaScript programs can be executed by the web browser.

JavaScript Statements
JavaScript statements are composed of:

Values, Operators, Expressions, Keywords, and Comments.

JavaScript Values

13
www.Sohrabpoor.com

The JavaScript syntax defines two types of values: Fixed values and variable
values.

Fixed values are called literals. Variable values are called variables.

JavaScript Literals
The most important rules for writing fixed values are:

Numbers are written with or without decimals:

10.50

1001

Try it Yourself »

Strings are text, written within double or single quotes:

"John Doe"

'John Doe'

Try it Yourself »

JavaScript Variables
In a programming language, variables are used to store data values.

JavaScript uses the var keyword to declare variables.

An equal sign is used to assign values to variables.

In this example, x is defined as a variable. Then, x is assigned (given) the


value 6:

var x;
x = 6;

Try it Yourself »

JavaScript Operators

14
www.Sohrabpoor.com

JavaScript uses an assignment operator ( = ) to assign values to


variables:

var x = 5;
var y = 6;

Try it Yourself »

JavaScript uses arithmetic operators ( + - * / ) to compute values:

(5 + 6) * 10

Try it Yourself »

JavaScript Expressions
An expression is a combination of values, variables, and operators, which
computes to a value.

The computation is called an evaluation.

For example, 5 * 10 evaluates to 50:

5 * 10

Try it Yourself »

Expressions can also contain variable values:

x * 10

Try it Yourself »

The values can be of various types, such as numbers and strings.

For example, "John" + " " + "Doe", evaluates to "John Doe":

"John" + " " + "Doe"

<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "John" + " " + "Doe";
</script>
Try it Yourself »

15
www.Sohrabpoor.com

JavaScript Keywords
JavaScript keywords are used to identify actions to be performed.

The var keyword tells the browser to create a new variable:

<p id="demo"></p>
<script>
var x = 5 + 6;
var y = x * 10;
document.getElementById("demo").innerHTML = y;
</script>

Try it Yourself »

JavaScript Comments
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:

var x = 5; // I will be executed

// var x = 6; I will NOT be executed

Try it Yourself »

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, an underscore (_), or a


dollar sign ($).
16
www.Sohrabpoor.com

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 is Case Sensitive


All JavaScript identifiers are case sensitive.

The variables lastName and lastname, are two different variables.

lastName = "Doe";
lastname = "Peterson";

Try it Yourself »

JavaScript does not interpret VAR or Var as the keyword var.

JavaScript and Camel Case


Historically, programmers have used three ways of joining multiple words
into one variable name:

Hyphens:

first-name, last-name, master-card, inter-city.

Underscore:

first_name, last_name, master_card, inter_city.

Camel Case:

FirstName, LastName, MasterCard, InterCity.

17
www.Sohrabpoor.com

In programming languages, especially in JavaScript, camel case often starts


with a lowercase letter:

firstName, lastName, masterCard, interCity.

Hyphens are not allowed in JavaScript. It is reserved for subtractions.

JavaScript Character Set


JavaScript uses the Unicode character set.

Unicode covers (almost) all the characters, punctuations, and symbols in the
world.

For a closer look, please study our Complete Unicode Reference.

JavaScript Statements
❮ Previous Next ❯

In HTML, JavaScript statements are "instructions" to be "executed" by the web browser.

JavaScript Statements

18
www.Sohrabpoor.com

This statement tells the browser to write "Hello Dolly." inside an HTML element with
id="demo":

Example
document.getElementById("demo").innerHTML = "Hello Dolly.";

Try it Yourself »

JavaScript Programs
Most JavaScript programs contain many JavaScript statements.

The statements are executed, one by one, in the same order as they are written.

In this example x, y, and z are given values, and finally z is displayed:

Example
var x = 5;
var y = 6;
var z = x + y;
document.getElementById("demo").innerHTML = z;

Try it Yourself »

JavaScript programs (and JavaScript statements) are often called JavaScript code.

Semicolons ;
Semicolons separate JavaScript statements.

Add a semicolon at the end of each executable statement:

a = 5;
b = 6;
c = a + b;

Try it Yourself »

When separated by semicolons, multiple statements on one line are allowed:

19
www.Sohrabpoor.com

a = 5; b = 6; c = a + b;

Try it Yourself »

On the web, you might see examples without semicolons.


Ending statements with semicolon is not required, but highly recommended.

JavaScript White Space


JavaScript ignores multiple spaces. You can add white space to your script to make it more
readable.

The following lines are equivalent:

var person = "Hege";


var person="Hege";

A good practice is to put spaces around operators ( = + - * / ):

var x = y + z;

JavaScript Line Length and Line Breaks


For best readability, programmers often like to avoid code lines longer than 80 characters.

If a JavaScript statement does not fit on one line, the best place to break it, is after an
operator:

Example
document.getElementById("demo").innerHTML =
"Hello Dolly.";

Try it Yourself »

JavaScript Code Blocks


JavaScript statements can be grouped together in code blocks, inside curly brackets {...}.

The purpose of code blocks is to define statements to be executed together.

20
www.Sohrabpoor.com

One place you will find statements grouped together in blocks, are in JavaScript functions:

Example
function myFunction() {
document.getElementById("demo").innerHTML = "Hello Dolly.";
document.getElementById("myDIV").innerHTML = "How are you?";
}

Try it Yourself »

In this tutorial we use 4 spaces of indentation for code blocks.


You will learn more about functions later in this tutorial.

JavaScript Keywords
JavaScript statements often start with a keyword to identify the JavaScript action to be
performed.

Here is a list of some of the keywords you will learn about in this tutorial:

Keyword Description

break Terminates a switch or a loop

continue Jumps out of a loop and starts at the top

debugger Stops the execution of JavaScript, and calls (if available) the debugging
function

do ... while Executes a block of statements, and repeats the block, while a condition is
true

for Marks a block of statements to be executed, as long as a condition is true

21
www.Sohrabpoor.com

function Declares a function

if ... else Marks a block of statements to be executed, depending on a condition

return Exits a function

switch Marks a block of statements to be executed, depending on different cases

try ... catch Implements error handling to a block of statements

var Declares a variable

JavaScript keywords are reserved words. Reserved words cannot be used as names for
variables.

JavaScript Comments
JavaScript comments can be used to explain JavaScript code, and to
make it more readable.

JavaScript comments can also be used to prevent execution, when testing


alternative code.

Single Line Comments


Single line comments start with //.

Any text between // and the end of the line will be ignored by JavaScript (will
not be executed).

This example uses a single-line comment before each code line:

22
www.Sohrabpoor.com

Example
<h1 id="myH"></h1>
<p id="myP"></p>
<script>
// Change heading:
document.getElementById("myH").innerHTML = "My First Page";
// Change paragraph:
document.getElementById("myP").innerHTML = "My first paragraph.";
</script>
Try it Yourself »

This example uses a single line comment at the end of each line to explain
the code:

Example
var x = 5; // Declare x, give it the value of 5
var y = x + 2; // Declare y, give it the value of x + 2

Try it Yourself »

Multi-line Comments
Multi-line comments start with /* and end with */.

Any text between /* and */ will be ignored by JavaScript.

This example uses a multi-line comment (a comment block) to explain the


code:

Example
/*
The code below will change
the heading with id = "myH"
and the paragraph with id = "myP"
in my web page:
*/
document.getElementById("myH").innerHTML = "My First Page";
document.getElementById("myP").innerHTML = "My first paragraph.";

Try it Yourself »

23
www.Sohrabpoor.com

It is most common to use single line comments.


Block comments are often used for formal documentation.

Using Comments to Prevent Execution


Using comments to prevent execution of code is suitable for code testing.

Adding // in front of a code line changes the code lines from an executable
line to a comment.

This example uses // to prevent execution of one of the code lines:

Example
//document.getElementById("myH").innerHTML = "My First Page";
document.getElementById("myP").innerHTML = "My first paragraph.";

Try it Yourself »

This example uses a comment block to prevent execution of multiple lines:

Example
/*
document.getElementById("myH").innerHTML = "My First Page";
document.getElementById("myP").innerHTML = "My first paragraph.";
*/

Try it Yourself »

JavaScript Variables
JavaScript Variables
JavaScript variables are containers for storing data values.

In this example, x, y, and z, are variables:

Example
var x = 5;
var y = 6;
var z = x + y;

Try it Yourself »

24
www.Sohrabpoor.com

From the example above, you can expect:

 x stores the value 5


 y stores the value 6
 z stores the value 11

Much Like Algebra


In this example, price1, price2, and total, are variables:

Example
<script>
var price1 = 5;
var price2 = 6;
var total = price1 + price2;
document.getElementById("demo").innerHTML ="The total is: " + total;
</script>

Try it Yourself »

In programming, just like in algebra, we use variables (like price1) to hold


values.

In programming, just like in algebra, we use variables in expressions (total =


price1 + price2).

From the example above, you can calculate the total to be 11.

JavaScript variables are containers for storing data values.

JavaScript Identifiers
All JavaScript variables must be identified with unique names.

These unique names are called identifiers.

Identifiers can be short names (like x and y) or more descriptive names


(age, sum, totalVolume).

The general rules for constructing names for variables (unique identifiers)
are:

25
www.Sohrabpoor.com

 Names can contain letters, digits, underscores, and dollar signs.


 Names must begin with a letter
 Names can also begin with $ and _ (but we will not use it in this
tutorial)
 Names are case sensitive (y and Y are different variables)
 Reserved words (like JavaScript keywords) cannot be used as names

JavaScript identifiers are case-sensitive.

The Assignment Operator


In JavaScript, the equal sign (=) is an "assignment" operator, not an "equal
to" operator.

This is different from algebra. The following does not make sense in algebra:

x = x + 5

In JavaScript, however, it makes perfect sense: it assigns the value of x + 5


to x.

(It calculates the value of x + 5 and puts the result into x. The value of x is
incremented by 5.)

The "equal to" operator is written like == in JavaScript.

JavaScript Data Types


JavaScript variables can hold numbers like 100 and text values like "John
Doe".

In programming, text values are called text strings.

JavaScript can handle many types of data, but for now, just think of numbers
and strings.

Strings are written inside double or single quotes. Numbers are written
without quotes.

If you put a number in quotes, it will be treated as a text string.

26
www.Sohrabpoor.com

Example
var pi = 3.14;
var person = "John Doe";
var answer = 'Yes I am!';

Try it Yourself »

Declaring (Creating) JavaScript Variables


Creating a variable in JavaScript is called "declaring" a variable.

You declare a JavaScript variable with the var keyword:

var carName;

After the declaration, the variable has no value. (Technically it has the value
of undefined)

To assign a value to the variable, use the equal sign:

carName = "Volvo";

You can also assign a value to the variable when you declare it:

var carName = "Volvo";

In the example below, we create a variable called carName and assign the
value "Volvo" to it.

Then we "output" the value inside an HTML paragraph with id="demo":

Example
<p id="demo"></p>

<script>
var carName = "Volvo";
document.getElementById("demo").innerHTML = carName;
</script>

Try it Yourself »

It's a good programming practice to declare all variables at the beginning of


a script.

27
www.Sohrabpoor.com

One Statement, Many Variables


You can declare many variables in one statement.

Start the statement with var and separate the variables by comma:

var person = "John Doe", carName = "Volvo", price = 200;

Try it Yourself »

A declaration can span multiple lines:

var person = "John Doe",


carName = "Volvo",
price = 200;

Try it Yourself »

Value = undefined
In computer programs, variables are often declared without a value. The
value can be something that has to be calculated, or something that will be
provided later, like user input.

A variable declared without a value will have the value undefined.

The variable carName will have the value undefined after the execution of
this statement:

Example
var carName;

Try it Yourself »

Re-Declaring JavaScript Variables


If you re-declare a JavaScript variable, it will not lose its value.

The variable carName will still have the value "Volvo" after the execution of
these statements:

28
www.Sohrabpoor.com

Example
var carName = "Volvo";
var carName;

Try it Yourself »

JavaScript Arithmetic
As with algebra, you can do arithmetic with JavaScript variables, using
operators like = and +:

Example
var x = 5 + 2 + 3;

Try it Yourself »

You can also add strings, but strings will be concatenated:

Example
var x = "John" + " " + "Doe";

Try it Yourself »

Also try this:

Example
var x = "5" + 2 + 3;

Try it Yourself »

If you put a number in quotes, the rest of the numbers will be treated as
strings, and concatenated.

Now try this:

Example
var x = 2 + 3 + "5";

Try it Yourself »

29
www.Sohrabpoor.com

JavaScript Operators

Example
Assign values to variables and add them together:

var x = 5; // assign the value 5 to x


var y = 2; // assign the value 2 to y
var z = x + y; // assign the value 7 to z (x + y)

Try it Yourself »

JavaScript Arithmetic Operators


Arithmetic operators are used to perform arithmetic on numbers (literals or
variables).

Operator Description

+ Addition

- Subtraction

* Multiplication

/ Division

% Modulus

++ Increment

30
www.Sohrabpoor.com

-- Decrement

The addition operator (+) adds numbers:

Adding
var x = 5;
var y = 2;
var z = x + y;

Try it Yourself »

The multiplication operator (*) multiplies numbers.

Multiplying
var x = 5;
var y = 2;
var z = x * y;

Try it Yourself »

You will learn more about JavaScript operators in the next chapters.

JavaScript Assignment Operators


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

31
www.Sohrabpoor.com

*= x *= y x=x*y

/= x /= y x=x/y

%= x %= y x=x%y

The assignment operator (=) assigns a value to a variable.

Assignment
var x = 10;

Try it Yourself »

The addition assignment operator (+=) adds a value to a variable.

Assignment
var x = 10;
x += 5;

Try it Yourself »

JavaScript String Operators


The + operator can also be used to add (concatenate) strings.

When used on strings, the + operator is called the concatenation operator.

Example
txt1 = "John";
txt2 = "Doe";
txt3 = txt1 + " " + txt2;

The result of txt3 will be:

John Doe

Try it Yourself »

32
www.Sohrabpoor.com

The += assignment operator can also be used to add (concatenate) strings:

Example
txt1 = "What a very ";
txt1 += "nice day";

The result of txt1 will be:

What a very nice day

Try it Yourself »

Adding Strings and Numbers


Adding two numbers, will return the sum, but adding a number and a string
will return a string:

Example
x = 5 + 5;
y = "5" + 5;
z = "Hello" + 5;

The result of x, y, and z will be:

10
55
Hello5

Try it Yourself »

The rule is: If you add a number and a string, the result will be a
string!

33
www.Sohrabpoor.com

JavaScript Comparison and Logical Operators


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

Comparison and logical operators are described in the JS


Comparisons chapter.

34
www.Sohrabpoor.com

JavaScript Type Operators


Operator Description

typeof Returns the type of a variable

instanceof Returns true if an object is an instance of an object type

Type operators are described in the JS Type Conversion chapter.

JavaScript Arithmetic
A typical thing to do with numbers is arithmetic.

JavaScript Arithmetic Operators


Arithmetic operators perform arithmetic on numbers (literals or variables).

Operator Description

+ Addition

- Subtraction

* Multiplication

/ Division

35
www.Sohrabpoor.com

% Modulus

++ Increment

-- Decrement

Arithmetic Operations
A typical arithmetic operation operates on two numbers.

The two numbers can be literals:

Example
var x = 100 + 50;

Try it Yourself »

or variables:

Example
var x = a + b;

Try it Yourself »

or expressions:

Example
var x = (100 + 50) * a;

Try it Yourself »

Operators and Operands


The numbers (in an arithmetic operation) are called operands.

36
www.Sohrabpoor.com

The operation (to be performed between the two operands) is defined by


an operator.

Operand Operator Operand

100 + 50

The addition operator (+) adds numbers:

Adding
var x = 5;
var y = 2;
var z = x + y;

Try it Yourself »

The subtraction operator (-) subtracts numbers.

Subtracting
var x = 5;
var y = 2;
var z = x - y;

Try it Yourself »

The multiplication operator (*) multiplies numbers.

Multiplying
var x = 5;
var y = 2;
var z = x * y;

Try it Yourself »

The division operator (/) divides numbers.

Dividing
var x = 5;
var y = 2;
var z = x / y;

Try it Yourself »
37
www.Sohrabpoor.com

The modular operator (%) returns the division remainder.

Modulus
var x = 5;
var y = 2;
var z = x % y;

Try it Yourself »

The increment operator (++) increments numbers.

Incrementing
var x = 5;
x++;
var z = x;

Try it Yourself »

The decrement operator (--) decrements numbers.

Decrementing
var x = 5;
x--;
var z = x;

Try it Yourself »

Operator Precedence
Operator precedence describes the order in which operations are performed
in an arithmetic expression.

Example
var x = 100 + 50 * 3;

Try it Yourself »

Is the result of example above the same as 150 * 3, or is it the same as 100
+ 150?

Is the addition or the multiplication done first?

As in traditional school mathematics, the multiplication is done first.


38
www.Sohrabpoor.com

Multiplication (*) and division (/) have higher precedence than addition (+)
and subtraction (-).

And (as in school mathematics) the precedence can be changed by using


parentheses:

Example
var x = (100 + 50) * 3;

Try it Yourself »

When using parentheses, the operations inside the parentheses are


computed first.

When many operations have the same precedence (like addition and
subtraction), they are computed from left to right:

Example
var x = 100 + 50 - 3;

Try it Yourself »

JavaScript Operator Precedence Values


Value Operator Description Example

19 () Expression grouping (3 + 4)

18 . Member person.name

18 [] Member person["name"]

39
www.Sohrabpoor.com

17 () Function call myFunction()

17 new Create new Date()

16 ++ Postfix Increment i++

16 -- Postfix Decrement i--

15 ++ Prefix Increment ++i

15 -- Prefix Decrement --i

15 ! Logical not !(x==y)

15 typeof Type typeof x

14 * Multiplication 10 * 5

40
www.Sohrabpoor.com

14 / Division 10 / 5

14 % Modulo division 10 % 5

14 ** Exponentiation 10 ** 2

13 + Addition 10 + 5

13 - Subtraction 10 - 5

12 << Shift left x << 2

12 >> Shift right x >> 2

11 < Less than x<y

11 <= Less than or equal x <= y

11 > Greater than x>y

41
www.Sohrabpoor.com

11 >= Greater than or equal x >= y

10 == Equal x == y

10 === Strict equal x === y

10 != Unequal x != y

10 !== Strict unequal x !== y

6 && And x && y

5 || Or x || y

3 = Assignment x=y

3 += Assignment x += y

3 -= Assignment x -= y

42
www.Sohrabpoor.com

3 *= Assignment x *= y

3 /= Assignment x /= y

Red entries indicates experimental or proposed technology (ECMASScript


2016 or ES7)

Expressions in parentheses are fully computed before the value is used in the
rest of the expression.

Test Yourself with Exercises!


Exercise 1 » Exercise 2 » Exercise 3 » Exercise 4 » Exercise 5 »

JavaScript Assignment

JavaScript Assignment Operators


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

43
www.Sohrabpoor.com

*= x *= y x=x*y

/= x /= y x=x/y

%= x %= y x=x%y

The = assignment operator assigns a value to a variable.

Assignment
var x = 10;

Try it Yourself »

The += assignment operator adds a value to a variable.

Assignment
var x = 10;
x += 5;

Try it Yourself »

The -= assignment operator subtracts a value from a variable.

Assignment
var x = 10;
x -= 5;

Try it Yourself »

The *= assignment operator multiplies a variable.

Assignment
var x = 10;
x *= 5;

Try it Yourself »

The /= assignment divides a variable.

44
www.Sohrabpoor.com

Assignment
var x = 10;
x /= 5;

Try it Yourself »

The %= assignment operator assigns a remainder to a variable.

Assignment
var x = 10;
x %= 5;

Try it Yourself »

JavaScript Data Types


String, Number, Boolean, Array, Object.

JavaScript Data Types


JavaScript variables can hold many data types: numbers, strings, arrays,
objects and more:

var length = 16; // Number


var lastName = "Johnson"; // String
var cars = ["Saab", "Volvo", "BMW"]; // Array
var x = {firstName:"John", lastName:"Doe"}; // Object

The Concept of Data Types


In programming, data types is an important concept.

To be able to operate on variables, it is important to know something about


the type.

Without data types, a computer cannot safely solve this:

45
www.Sohrabpoor.com

var x = 16 + "Volvo";

Does it make any sense to add "Volvo" to sixteen? Will it produce an error or
will it produce a result?

JavaScript will treat the example above as:

var x = "16" + "Volvo";

When adding a number and a string, JavaScript will treat the number as a
string.

Example
var x = 16 + "Volvo";

Try it Yourself »

Example
var x = "Volvo" + 16;

Try it Yourself »

JavaScript evaluates expressions from left to right. Different sequences can


produce different results:

JavaScript:
var x = 16 + 4 + "Volvo";

Result:
20Volvo

Try it Yourself »

JavaScript:
var x = "Volvo" + 16 + 4;

Result:
Volvo164

Try it Yourself »

In the first example, JavaScript treats 16 and 4 as numbers, until it reaches


"Volvo".

46
www.Sohrabpoor.com

In the second example, since the first operand is a string, all operands are
treated as strings.

JavaScript Has Dynamic Types


JavaScript has dynamic types. This means that the same variable can be
used as different types:

Example
var x; // Now x is undefined
var x = 5; // Now x is a Number
var x = "John"; // Now x is a String

JavaScript Strings
A string (or a text string) is a series of characters like "John Doe".

Strings are written with quotes. You can use single or double quotes:

Example
var carName = "Volvo XC60"; // Using double quotes
var carName = 'Volvo XC60'; // Using single quotes

You can use quotes inside a string, as long as they don't match the quotes
surrounding the string:

Example
var answer = "It's alright"; // Single quote inside double
quotes
var answer = "He is called 'Johnny'"; // Single quotes inside double
quotes
var answer = 'He is called "Johnny"'; // Double quotes inside single
quotes

Try it yourself »

You will learn more about strings later in this tutorial.

47
www.Sohrabpoor.com

JavaScript Numbers
JavaScript has only one type of numbers.

Numbers can be written with, or without decimals:

Example
var x1 = 34.00; // Written with decimals
var x2 = 34; // Written without decimals

Extra large or extra small numbers can be written with scientific


(exponential) notation:

Example
var y = 123e5; // 12300000
var z = 123e-5; // 0.00123

Try it yourself »

You will learn more about numbers later in this tutorial.

JavaScript Booleans
Booleans can only have two values: true or false.

Example
var x = true;
var y = false;

Booleans are often used in conditional testing.

You will learn more about conditional testing later in this tutorial.

JavaScript Arrays
JavaScript arrays are written with square brackets.

Array items are separated by commas.

48
www.Sohrabpoor.com

The following code declares (creates) an array called cars, containing three
items (car names):

Example
var cars = ["Saab", "Volvo", "BMW"];

Try it Yourself »

Array indexes are zero-based, which means the first item is [0], second is
[1], and so on.

You will learn more about arrays later in this tutorial.

JavaScript Objects
JavaScript objects are written with curly braces.

Object properties are written as name:value pairs, separated by commas.

Example
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};

Try it Yourself »

The object (person) in the example above has 4 properties: firstName,


lastName, age, and eyeColor.

You will learn more about objects later in this tutorial.

The typeof Operator


You can use the JavaScript typeof operator to find the type of a JavaScript
variable:

Example
typeof "John" // Returns "string"
typeof 3.14 // Returns "number"
typeof false // Returns "boolean"
typeof [1,2,3,4] // Returns "object" (not "array", see note

49
www.Sohrabpoor.com

below)
typeof {name:'John', age:34} // Returns "object"

Try it Yourself »

The typeof operator returns "object" for arrays because in JavaScript arrays
are objects.

Undefined
In JavaScript, a variable without a value, has the value undefined. The
typeof is also undefined.

Example
var person; // Value is undefined, type is undefined

Try it Yourself »

Any variable can be emptied, by setting the value to undefined. The type
will also be undefined.

Example
person = undefined; // Value is undefined, type is undefined

Try it Yourself »

Empty Values
An empty value has nothing to do with undefined.

An empty string variable has both a value and a type.

Example
var car = ""; // The value is "", the typeof is "string"

Try it Yourself »

50
www.Sohrabpoor.com

Null
In JavaScript null is "nothing". It is supposed to be something that doesn't
exist.

Unfortunately, in JavaScript, the data type of null is an object.

You can consider it a bug in JavaScript that typeof null is an object. It should
be null.

You can empty an object by setting it to null:

Example
var person = null; // Value is null, but type is still an object

Try it Yourself »

You can also empty an object by setting it to undefined:

Example
var person = undefined; // Value is undefined, type is undefined

Try it Yourself »

Difference Between Undefined and Null


typeof undefined // undefined
typeof null // object
null === undefined // false
null == undefined // true

Try it Yourself »

51
www.Sohrabpoor.com

JavaScript Functions
A JavaScript function is a block of code designed to perform a particular task.

A JavaScript function is executed when "something" invokes it (calls it).

Example
function myFunction(p1, p2) {
return p1 * p2; // The function returns the product of p1
and p2
}

Try it Yourself »

JavaScript Function Syntax


A JavaScript function is defined with the function keyword, followed by a name, followed
by parentheses ().

Function names can contain letters, digits, underscores, and dollar signs (same rules as
variables).

The parentheses may include parameter names separated by commas:


(parameter1, parameter2, ...)

The code to be executed, by the function, is placed inside curly brackets: {}

function name(parameter1, parameter2, parameter3) {


code to be executed
}

Function parameters are the names listed in the function definition.

Function arguments are the real values received by the function when it is invoked.

Inside the function, the arguments (the parameters) behave as local variables.

A Function is much the same as a Procedure or a Subroutine, in other programming


languages.

52
www.Sohrabpoor.com

Function Invocation
The code inside the function will execute when "something" invokes (calls) the function:

 When an event occurs (when a user clicks a button)


 When it is invoked (called) from JavaScript code
 Automatically (self invoked)

You will learn a lot more about function invocation later in this tutorial.

Function Return
When JavaScript reaches a return statement, the function will stop executing.

If the function was invoked from a statement, JavaScript will "return" to execute the code
after the invoking statement.

Functions often compute a return value. The return value is "returned" back to the "caller":

Example
Calculate the product of two numbers, and return the result:

var x = myFunction(4, 3); // Function is called, return value will


end up in x

function myFunction(a, b) {
return a * b; // Function returns the product of a and
b
}

The result in x will be:

12

Try it Yourself »

53
www.Sohrabpoor.com

Why Functions?
You can reuse code: Define the code once, and use it many times.

You can use the same code many times with different arguments, to produce different results.

Example
Convert Fahrenheit to Celsius:

function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}
document.getElementById("demo").innerHTML = toCelsius(77);

Try it Yourself »

The () Operator Invokes the Function


Using the example above, toCelsius refers to the function object, and toCelsius() refers to the
function result.

Example
Accessing a function without () will return the function definition:

<p id="demo"></p>
function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}
document.getElementById("demo").innerHTML = toCelsius;

Try it Yourself »

Functions Used as Variable Values


Functions can be used the same way as you use variables, in all types of formulas,
assignments, and calculations.

54
www.Sohrabpoor.com

Example
Instead of using a variable to store the return value of a function:

var x = toCelsius(77);
var text = "The temperature is " + x + " Celsius";

You can use the function directly, as a variable value:

var text = "The temperature is " + toCelsius(77) + " Celsius";


Try it Yourself »

You will learn a lot more about functions later in this tutorial.

JavaScript Objects
Real Life Objects, Properties, and Methods
In real life, a car is an object.

A car has properties like weight and color, and methods like start and
stop:

Object Properties Methods

car.name = Fiat car.start()

car.model = 500 car.drive()

car.weight = 850kg car.brake()

car.color = white car.stop()

All cars have the same properties, but the property values differ from car to
car.

55
www.Sohrabpoor.com

All cars have the same methods, but the methods are performed at different
times.

JavaScript Objects
You have already learned that JavaScript variables are containers for data
values.

This code assigns a simple value (Fiat) to a variable named car:

var car = "Fiat";

Try it Yourself »

Objects are variables too. But objects can contain many values.

This code assigns many values (Fiat, 500, white) to a variable named car:

var car = {type:"Fiat", model:"500", color:"white"};

Try it Yourself »

The values are written as name:value pairs (name and value separated by a
colon).

JavaScript objects are containers for named values.

Object Properties
The name:values pairs (in JavaScript objects) are called properties.

var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};

Property Property Value

firstName John

56
www.Sohrabpoor.com

lastName Doe

age 50

eyeColor blue

Object Methods
Methods are actions that can be performed on objects.

Methods are stored in properties as function definitions.

Property Property Value

firstName John

lastName Doe

age 50

eyeColor blue

fullName function() {return this.firstName + " " + this.lastName;}

JavaScript objects are containers for named values called properties or


methods.

57
www.Sohrabpoor.com

Object Definition
You define (and create) a JavaScript object with an object literal:

Example
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};

Try it Yourself »

Spaces and line breaks are not important. An object definition can span
multiple lines:

Example
var person = {
firstName:"John",
lastName:"Doe",
age:50,
eyeColor:"blue"
};

Try it Yourself »

Accessing Object Properties


You can access object properties in two ways:

objectName.propertyName

or

objectName["propertyName"]

Example1
person.lastName;

Try it Yourself »

Example2
person["lastName"];

Try it Yourself »

58
www.Sohrabpoor.com

Accessing Object Methods


You access an object method with the following syntax:

objectName.methodName()

Example
name = person.fullName();

Try it Yourself »

If you access the fullName method, without (), it will return the function
definition:

Example
name = person.fullName;

Try it Yourself »

A method is actually a function definition stored as a property value.

Do Not Declare Strings, Numbers, and


Booleans as Objects!
When a JavaScript variable is declared with the keyword "new", the variable
is created as an object:

var x = new String(); // Declares x as a String object


var y = new Number(); // Declares y as a Number object
var z = new Boolean(); // Declares z as a Boolean object

Avoid String, Number, and Boolean objects. They complicate your code and
slow down execution speed.

You will learn more about objects later in this tutorial.

59
www.Sohrabpoor.com

JavaScript Scope
Scope is the set of variables you have access to.

JavaScript Scope
In JavaScript, objects and functions are also variables.

In JavaScript, scope is the set of variables, objects, and functions


you have access to.

JavaScript has function scope: The scope changes inside functions.

Local JavaScript Variables


Variables declared within a JavaScript function, become LOCAL to the
function.

Local variables have local scope: They can only be accessed within the
function.

Example
// code here can not use carName

function myFunction() {
var carName = "Volvo";

// code here can use carName

Try it Yourself »

Since local variables are only recognized inside their functions, variables with
the same name can be used in different functions.

Local variables are created when a function starts, and deleted when the
function is completed.

60
www.Sohrabpoor.com

Global JavaScript Variables


A variable declared outside a function, becomes GLOBAL.

A global variable has global scope: All scripts and functions on a web page
can access it.

Example
var carName = " Volvo";

// code here can use carName

function myFunction() {

// code here can use carName

Try it Yourself »

Automatically Global
If you assign a value to a variable that has not been declared, it will
automatically become a GLOBAL variable.

This code example will declare a global variable carName, even if the value
is assigned inside a function.

Example
myFunction();

// code here can use carName

function myFunction() {
carName = "Volvo";
}

Try it Yourself »

Do NOT create global variables unless you intend to.

61
www.Sohrabpoor.com

Global Variables in HTML


With JavaScript, the global scope is the complete JavaScript environment.

In HTML, the global scope is the window object. All global variables belong to
the window object.

Example
var carName = "Volvo";

// code here can use window.carName

Try it Yourself »

Did You Know?


Your global variables (or functions) can overwrite window variables (or
functions).
Any function, including the window object, can overwrite your global
variables and functions.

The Lifetime of JavaScript Variables


The lifetime of a JavaScript variable starts when it is declared.

Local variables are deleted when the function is completed.

Global variables are deleted when you close the page.

Function Arguments
Function arguments (parameters) work as local variables inside functions.

62
www.Sohrabpoor.com

JavaScript Events
HTML events are "things" that happen to HTML elements.

When JavaScript is used in HTML pages, JavaScript can "react" on these


events.

HTML Events
An HTML event can be something the browser does, or something a user
does.

Here are some examples of HTML events:

 An HTML web page has finished loading


 An HTML input field was changed
 An HTML button was clicked

Often, when events happen, you may want to do something.

JavaScript lets you execute code when events are detected.

HTML allows event handler attributes, with JavaScript code, to be added to


HTML elements.

With single quotes:

<some-HTML-element some-event='some JavaScript'>

With double quotes:

<some-HTML-element some-event="some JavaScript">

In the following example, an onclick attribute (with code), is added to a


button element:

Example
<button onclick='document.getElementById("demo").innerHTML=Date()'>The
time is?</button>

<p id="demo"></p>
Try it Yourself »

63
www.Sohrabpoor.com

In the example above, the JavaScript code changes the content of the
element with id="demo".

In the next example, the code changes the content of its own element
(using this.innerHTML):

Example
<button onclick="this.innerHTML=Date()">The time is?</button>

Try it Yourself »

JavaScript code is often several lines long. It is more common to see event
attributes calling functions:

Example
<button onclick="displayDate()">The time is?</button>

Try it Yourself »

Common HTML Events


Here is a list of some common HTML events:

Event Description

onchange An HTML element has been changed

onclick The user clicks an HTML element

onmouseover The user moves the mouse over an HTML element

onmouseout The user moves the mouse away from an HTML element

64
www.Sohrabpoor.com

onkeydown The user pushes a keyboard key

onload The browser has finished loading the page

The list is much longer: W3Schools JavaScript Reference HTML DOM Events.

What can JavaScript Do?


Event handlers can be used to handle, and verify, user input, user actions,
and browser actions:

 Things that should be done every time a page loads


 Things that should be done when the page is closed
 Action that should be performed when a user clicks a button
 Content that should be verified when a user inputs data
 And more ...

Many different methods can be used to let JavaScript work with events:

 HTML event attributes can execute JavaScript code directly


 HTML event attributes can call JavaScript functions
 You can assign your own event handler functions to HTML elements
 You can prevent events from being sent or being handled
 And more ...

You will learn a lot more about events and event handlers in the HTML DOM
chapters.

JavaScript Strings
JavaScript strings are used for storing and manipulating text.

JavaScript Strings
A JavaScript string simply stores a series of characters like "John Doe".

A string can be any text inside quotes. You can use single or double quotes:

65
www.Sohrabpoor.com

Example
var carname = "Volvo XC60";
var carname = 'Volvo XC60';

Try it Yourself »

You can use quotes inside a string, as long as they don't match the quotes
surrounding the string:

Example
var answer = "It's alright";
var answer = "He is called 'Johnny'";
var answer = 'He is called "Johnny"';

Try it Yourself »

String Length
The length of a string is found in the built in property length:

Example
var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var sln = txt.length;

Try it Yourself »

Special Characters
Because strings must be written within quotes, JavaScript will misunderstand
this string:

var y = "We are the so-called "Vikings" from the north."

The string will be chopped to "We are the so-called ".

The solution to avoid this problem, is to use the \ escape character.

66
www.Sohrabpoor.com

The backslash escape character turns special characters into string


characters:

Example
var x = 'It\'s alright';
var y = "We are the so-called \"Vikings\" from the north."

Try it Yourself »

The escape character (\) can also be used to insert other special characters
in a string.

This is the list of special characters that can be added to a text string with
the backslash sign:

Code Outputs

\' single quote

\" double quote

\\ backslash

\n new line

\r carriage return

\t tab

\b backspace

\f form feed

67
www.Sohrabpoor.com

Breaking Long Code Lines


For best readability, programmers often like to avoid code lines longer than
80 characters.

If a JavaScript statement does not fit on one line, the best place to break it is
after an operator:

Example
document.getElementById("demo").innerHTML ="Hello Dolly.";

Try it Yourself »

You can also break up a code line within a text string with a single
backslash:

Example
document.getElementById("demo").innerHTML = "Hello \
Dolly!";

Try it Yourself »

The \ method is not a ECMAScript (JavaScript) standard.


Some browsers do not allow spaces behind the \ character.

The safest (but a little slower) way to break a long string is to use string
addition:

Example
document.getElementById("demo").innerHTML = "Hello" + "Dolly!";

Try it Yourself »

You cannot break up a code line with a backslash:

Example
document.getElementById("demo").innerHTML = \"Hello Dolly!";

Try it Yourself »

68
www.Sohrabpoor.com

Strings Can be Objects


Normally, JavaScript strings are primitive values, created from literals: var
firstName = "John"

But strings can also be defined as objects with the keyword new: var
firstName = new String("John")

Example
var x = "John";
var y = new String("John");

// typeof x will return string


// typeof y will return object

Try it Yourself »

Don't create strings as objects. It slows down execution speed.


The new keyword complicates the code. This can produce some unexpected
results:

When using the == equality operator, equal strings look equal:

Example
var x = "John";
var y = new String("John");

// (x == y) is true because x and y have equal values

Try it Yourself »

When using the === equality operator, equal strings are not equal, because
the === operator expects equality in both type and value.

Example
var x = "John";
var y = new String("John");

// (x === y) is false because x and y have different types (string and


object)

Try it Yourself »

Or even worse. Objects cannot be compared:

69
www.Sohrabpoor.com

Example
var x = new String("John");
var y = new String("John");

// (x == y) is false because x and y are different objects


// (x == x) is true because both are the same object

Try it Yourself »

JavaScript objects cannot be compared.

JavaScript String Methods


String methods help you to work with strings.

String Methods and Properties


Primitive values, like "John Doe", cannot have properties or methods
(because they are not objects).

But with JavaScript, methods and properties are also available to primitive
values, because JavaScript treats primitive values as objects when executing
methods and properties.

String Length
The length property returns the length of a string:

Example
var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var sln = txt.length;

Try it Yourself »

70
www.Sohrabpoor.com

Finding a String in a String


The indexOf() method returns the index of (the position of)
the first occurrence of a specified text in a string:

Example
var str = "Please locate where 'locate' occurs!";
var pos = str.indexOf("locate");

Try it Yourself »

The lastIndexOf() method returns the index of the last occurrence of a


specified text in a string:

Example
var str = "Please locate where 'locate' occurs!";
var pos = str.lastIndexOf("locate");

Try it Yourself »

Both the indexOf(), and the lastIndexOf() methods return -1 if the text is not
found.

JavaScript counts positions from zero.


0 is the first position in a string, 1 is the second, 2 is the third ...

Both methods accept a second parameter as the starting position for the
search.

Searching for a String in a String


The search() method searches a string for a specified value and returns the
position of the match:

Example
var str = "Please locate where 'locate' occurs!";
var pos = str.search("locate");

Try it Yourself »

71
www.Sohrabpoor.com

Did You Notice?


The two methods, indexOf() and search(), are equal.

They accept the same arguments (parameters), and they return the same
value.

The two methods are equal, but the search() method can take much more
powerful search values.

You will learn more about powerful search values in the chapter about
regular expressions.

Extracting String Parts


There are 3 methods for extracting a part of a string:

 slice(start, end)
 substring(start, end)
 substr(start, length)

The slice() Method


slice() extracts a part of a string and returns the extracted part in a new
string.

The method takes 2 parameters: the starting index (position), and the
ending index (position).

This example slices out a portion of a string from position 7 to position 13:

Example
var str = "Apple, Banana, Kiwi";
var res = str.slice(7,13);

The result of res will be:

Banana

Try it Yourself »

72
www.Sohrabpoor.com

If a parameter is negative, the position is counted from the end of the string.

This example slices out a portion of a string from position -12 to position -6:

Example
var str = "Apple, Banana, Kiwi";
var res = str.slice(-12,-6);

The result of res will be:

Banana

Try it Yourself »

If you omit the second parameter, the method will slice out the rest of the
string:

Example
var res = str.slice(7);

Try it Yourself »

or, counting from the end:

Example
var res = str.slice(-12);

Try it Yourself »

Negative positions do not work in Internet Explorer 8 and earlier.

The substring() Method


substring() is similar to slice().

The difference is that substring() cannot accept negative indexes.

Example
var str = "Apple, Banana, Kiwi";
var res = str.substring(7,13);

document.getElementById("demo").innerHTML = str.substring(7,13);

73
www.Sohrabpoor.com

The result of res will be:

Banana

Try it Yourself »

If you omit the second parameter, substring() will slice out the rest of the
string.

The substr() Method


substr() is similar to slice().

The difference is that the second parameter specifies the length of the
extracted part.

Example
var str = "Apple, Banana, Kiwi";
var res = str.substr(7,6);

The result of res will be:

Banana

Try it Yourself »

If the first parameter is negative, the position counts from the end of the
string.

The second parameter can not be negative, because it defines the length.

If you omit the second parameter, substr() will slice out the rest of the
string.

Replacing String Content


The replace() method replaces a specified value with another value in a
string:

74
www.Sohrabpoor.com

Example
str = "Please visit Microsoft!";
var n = str.replace("Microsoft","W3Schools");

Try it Yourself »

The replace() method can also take a regular expression as the search value.

By default, the replace() function replaces only the first match. To replace all
matches, use a regular expression with a g flag (for global match):

Example
str = "Please visit Microsoft!";
var n = str.replace(/Microsoft/g,"W3Schools");

Try it Yourself »

The replace() method does not change the string it is called on. It returns a
new string.

Converting to Upper and Lower Case


A string is converted to upper case with toUpperCase():

Example
var text1 = "Hello World!"; // String
var text2 = text1.toUpperCase(); // text2 is text1 converted to upper

Try it Yourself »

A string is converted to lower case with toLowerCase():

Example
var text1 = "Hello World!"; // String
var text2 = text1.toLowerCase(); // text2 is text1 converted to lower

Try it Yourself »

75
www.Sohrabpoor.com

The concat() Method


concat() joins two or more strings:

Example
var text1 = "Hello";
var text2 = "World";
text3 = text1.concat(" ",text2);

Try it Yourself »

The concat() method can be used instead of the plus operator. These two
lines do the same:

Example
var text = "Hello" + " " + "World!";
var text = "Hello".concat(" ","World!");

All string methods return a new string. They don't modify the original string.
Formally said: Strings are immutable: Strings cannot be changed, only
replaced.

Extracting String Characters


There are 2 safe methods for extracting string characters:

 charAt(position)
 charCodeAt(position)

The charAt() Method


The charAt() method returns the character at a specified index (position) in
a string:

Example
var str = "HELLO WORLD";
str.charAt(0); // returns H

Try it Yourself »
76
www.Sohrabpoor.com

The charCodeAt() Method


The charCodeAt() method returns the unicode of the character at a
specified index in a string:

Example
var str = "HELLO WORLD";

str.charCodeAt(0); // returns 72

Try it Yourself »

Accessing a String as an Array is Unsafe


You might have seen code like this, accessing a string as an array:

var str = "HELLO WORLD";

str[0]; // returns H

This is unsafe and unpredictable:

 It does not work in all browsers (not in IE5, IE6, IE7)


 It makes strings look like arrays (but they are not)
 str[0] = "H" does not give an error (but does not work)

If you want to read a string as an array, convert it to an array first.

Converting a String to an Array


A string can be converted to an array with the split() method:

Example
var txt = "a,b,c,d,e"; // String
txt.split(","); // Split on commas
txt.split(" "); // Split on spaces
txt.split("|"); // Split on pipe

Try it Yourself »

77
www.Sohrabpoor.com

If the separator is omitted, the returned array will contain the whole string in
index [0].

If the separator is "", the returned array will be an array of single characters:

Example
var txt = "Hello"; // String
txt.split(""); // Split in characters

Try it Yourself »

Complete String Reference


For a complete reference, go to our Complete JavaScript String Reference.

The reference contains descriptions and examples of all string properties and
methods.

JavaScript Numbers
JavaScript has only one type of number.

Numbers can be written with, or without, decimals.

JavaScript Numbers
JavaScript numbers can be written with, or without decimals:

Example
var x = 34.00; // A number with decimals
var y = 34; // A number without decimals

Extra large or extra small numbers can be written with scientific (exponent)
notation:

78
www.Sohrabpoor.com

Example
var x = 123e5; // 12300000
var y = 123e-5; // 0.00123

JavaScript Numbers are Always 64-bit


Floating Point
Unlike many other programming languages, JavaScript does not define
different types of numbers, like integers, short, long, floating-point etc.

JavaScript numbers are always stored as double precision floating point


numbers, following the international IEEE 754 standard.

This format stores numbers in 64 bits, where the number (the fraction) is
stored in bits 0 to 51, the exponent in bits 52 to 62, and the sign in bit 63:

Value (aka Fraction/Mantissa) Exponent Sign

52 bits (0 - 51) 11 bits (52 - 62) 1 bit (63)

Precision
Integers (numbers without a period or exponent notation) are considered
accurate up to 15 digits.

Example
var x = 999999999999999; // x will be 999999999999999
var y = 9999999999999999; // y will be 10000000000000000

Try it Yourself »

The maximum number of decimals is 17, but floating point arithmetic is not
always 100% accurate:

79
www.Sohrabpoor.com

Example
var x = 0.2 + 0.1; // x will be 0.30000000000000004

Try it yourself »

To solve the problem above, it helps to multiply and divide:

Example
var x = (0.2 * 10 + 0.1 * 10) / 10; // x will be 0.3

Try it Yourself »

Hexadecimal
JavaScript interprets numeric constants as hexadecimal if they are preceded
by 0x.

Example
var x = 0xFF; // x will be 255

Try it Yourself »

Never write a number with a leading zero (like 07).


Some JavaScript versions interpret numbers as octal if they are written with
a leading zero.

By default, Javascript displays numbers as base 10 decimals.

But you can use the toString() method to output numbers as base 16 (hex),
base 8 (octal), or base 2 (binary).

Example
var myNumber = 128;
myNumber.toString(16); // returns 80
myNumber.toString(8); // returns 200
myNumber.toString(2); // returns 10000000

Try it Yourself »

80
www.Sohrabpoor.com

Infinity
Infinity (or -Infinity) is the value JavaScript will return if you calculate a
number outside the largest possible number.

Example
var myNumber = 2;
while (myNumber != Infinity) { // Execute until Infinity
myNumber = myNumber * myNumber;
}

Try it yourself »

Division by 0 (zero) also generates Infinity:

Example
var x = 2 / 0; // x will be Infinity
var y = -2 / 0; // y will be -Infinity

Try it Yourself »

Infinity is a number: typeOf Infinity returns number.

Example
typeof Infinity; // returns "number"

Try it Yourself »

NaN - Not a Number


NaN is a JavaScript reserved word indicating that a number is not a legal
number.

Trying to do arithmetic with a non-numeric string will result in NaN (Not a


Number):

Example
var x = 100 / "Apple"; // x will be NaN (Not a Number)

Try it Yourself »

81
www.Sohrabpoor.com

However, if the string contains a numeric value , the result will be a number:

Example
var x = 100 / "10"; // x will be 10

Try it Yourself »

You can use the global JavaScript function isNaN() to find out if a value is a
number.

Example
var x = 100 / "Apple";
isNaN(x); // returns true because x is Not a Number

Try it Yourself »

Watch out for NaN. If you use NaN in a mathematical operation, the result
will also be NaN:

Example
var x = NaN;
var y = 5;
var z = x + y; // z will be NaN

Try it Yourself »

Or the result might be a concatenation:

Example
var x = NaN;
var y = "5";
var z = x + y; // z will be NaN5

Try it Yourself »

NaN is a number, and typeof NaN returns number:

Example
typeof NaN; // returns "number"

Try it Yourself »

82
www.Sohrabpoor.com

Numbers Can be Objects


Normally JavaScript numbers are primitive values created from literals: var
x = 123

But numbers can also be defined as objects with the keyword new: var y =
new Number(123)

Example
var x = 123;
var y = new Number(123);

// typeof x returns number


// typeof y returns object

Try it yourself »

Do not create Number objects. It slows down execution speed.


The new keyword complicates the code. This can produce some unexpected
results:

When using the == equality operator, equal numbers looks equal:

Example
var x = 500;
var y = new Number(500);

// (x == y) is true because x and y have equal values

Try it Yourself »

When using the === equality operator, equal numbers are not equal,
because the === operator expects equality in both type and value.

Example
var x = 500;
var y = new Number(500);

// (x === y) is false because x and y have different types

Try it Yourself »

Or even worse. Objects cannot be compared:

83
www.Sohrabpoor.com

Example
var x = new Number(500);
var y = new Number(500);

// (x == y) is false because objects cannot be compared

Try it Yourself »

JavaScript objects cannot be compared.

JavaScript Number Methods


Number methods help you work with numbers.

Number Methods and Properties


Primitive values (like 3.14 or 2014), cannot have properties and methods
(because they are not objects).

But with JavaScript, methods and properties are also available to primitive
values, because JavaScript treats primitive values as objects when executing
methods and properties.

The toString() Method


toString() returns a number as a string.

All number methods can be used on any type of numbers (literals, variables,
or expressions):

Example
var x = 123;
x.toString(); // returns 123 from variable x
(123).toString(); // returns 123 from literal 123
(100 + 23).toString(); // returns 123 from expression 100 + 23

Try it Yourself »

84
www.Sohrabpoor.com

The toExponential() Method


toExponential() returns a string, with a number rounded and written using
exponential notation.

A parameter defines the number of characters behind the decimal point:

Example
var x = 9.656;
x.toExponential(2); // returns 9.66e+0
x.toExponential(4); // returns 9.6560e+0
x.toExponential(6); // returns 9.656000e+0

Try it yourself »

The parameter is optional. If you don't specify it, JavaScript will not round
the number.

The toFixed() Method


toFixed() returns a string, with the number written with a specified number
of decimals:

Example
var x = 9.656;
x.toFixed(0); // returns 10
x.toFixed(2); // returns 9.66
x.toFixed(4); // returns 9.6560
x.toFixed(6); // returns 9.656000

Try it yourself »

toFixed(2) is perfect for working with money.

The toPrecision() Method


toPrecision() returns a string, with a number written with a specified
length:
85
www.Sohrabpoor.com

Example
var x = 9.656;
x.toPrecision(); // returns 9.656
x.toPrecision(2); // returns 9.7
x.toPrecision(4); // returns 9.656
x.toPrecision(6); // returns 9.65600

Try it Yourself »

The valueOf() Method


valueOf() returns a number as a number.

Example
var x = 123;
x.valueOf(); // returns 123 from variable x
(123).valueOf(); // returns 123 from literal 123
(100 + 23).valueOf(); // returns 123 from expression 100 + 23

Try it Yourself »

In JavaScript, a number can be a primitive value (typeof = number) or an


object (typeof = object).

The valueOf() method is used internally in JavaScript to convert Number


objects to primitive values.

There is no reason to use it in your code.

All JavaScript data types have a valueOf() and a toString() method.

Converting Variables to Numbers


There are 3 JavaScript methods that can be used to convert variables to
numbers:

 The Number() method


 The parseInt() method
 The parseFloat() method

These methods are not number methods, but global JavaScript methods.

86
www.Sohrabpoor.com

Global Methods
JavaScript global methods can be used on all JavaScript data types.

These are the most relevant methods, when working with numbers:

Method Description

Number() Returns a number, converted from its argument.

parseFloat() Parses its argument and returns a floating point number

parseInt() Parses its argument and returns an integer

The Number() Method


Number() can be used to convert JavaScript variables to numbers:

Example
x = true;
Number(x); // returns 1
x = false;
Number(x); // returns 0
x = new Date();
Number(x); // returns 1404568027739
x = "10"
Number(x); // returns 10
x = "10 20"
Number(x); // returns NaN

Try it Yourself »

Used on Date(), the Number() method returns the number of milliseconds


since 1.1.1970.

87
www.Sohrabpoor.com

The parseInt() Method


parseInt() parses a string and returns a whole number. Spaces are allowed.
Only the first number is returned:

Example
parseInt("10"); // returns 10
parseInt("10.33"); // returns 10
parseInt("10 20 30"); // returns 10
parseInt("10 years"); // returns 10
parseInt("years 10"); // returns NaN

Try it yourself »

If the number cannot be converted, NaN (Not a Number) is returned.

The parseFloat() Method


parseFloat() parses a string and returns a number. Spaces are allowed.
Only the first number is returned:

Example
parseFloat("10"); // returns 10
parseFloat("10.33"); // returns 10.33
parseFloat("10 20 30"); // returns 10
parseFloat("10 years"); // returns 10
parseFloat("years 10"); // returns NaN

Try it yourself »

If the number cannot be converted, NaN (Not a Number) is returned.

88
www.Sohrabpoor.com

Number Properties
Property Description

MAX_VALUE Returns the largest number possible in JavaScript

MIN_VALUE Returns the smallest number possible in JavaScript

NEGATIVE_INFINITY Represents negative infinity (returned on overflow)

NaN Represents a "Not-a-Number" value

POSITIVE_INFINITY Represents infinity (returned on overflow)

Example
var x = Number.MAX_VALUE;

Try it yourself »

Number properties belongs to the JavaScript's number object wrapper


called Number.

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:

Example
var x = 6;
var y = x.MAX_VALUE; // y becomes undefined

Try it yourself »

89
www.Sohrabpoor.com

Complete JavaScript Number Reference


For a complete reference, go to our Complete JavaScript Number Reference.

The reference contains descriptions and examples of all Number properties


and methods.

JavaScript Math Object


The Math object allows you to perform mathematical tasks on numbers.

The Math Object


The Math object allows you to perform mathematical tasks.

The Math object includes several mathematical methods.

One common use of the Math object is to create a random number:

Example
Math.random(); // returns a random number

Try it Yourself »

Math has no constructor. No methods have to create a Math object first.

Math.min() and Math.max()


Math.min() and Math.max() can be used to find the lowest or highest value
in a list of arguments:

Example
Math.min(0, 150, 30, 20, -8, -200); // returns -200

Try it Yourself »

90
www.Sohrabpoor.com

Example
Math.max(0, 150, 30, 20, -8, -200); // returns 150

Try it Yourself »

Math.random()
Math.random() returns a random number between 0 (inclusive), and 1
(exclusive):

Example
Math.random(); // returns a random number

Try it Yourself »

Math.random() always returns a number lower than 1.

Math.round()
Math.round() rounds a number to the nearest integer:

Example
Math.round(4.7); // returns 5
Math.round(4.4); // returns 4

Try it Yourself »

Math.ceil()
Math.ceil() rounds a number up to the nearest integer:

Example
Math.ceil(4.4); // returns 5

Try it Yourself »

91
www.Sohrabpoor.com

Math.floor()
Math.floor() rounds a number down to the nearest integer:

Example
Math.floor(4.7); // returns 4

Try it Yourself »

Math.floor() and Math.random() can be used together to return a random


number between 0 and 10:

Example
Math.floor(Math.random() * 11); // returns a random number between 0 and
10

Try it Yourself »

Math Constants
JavaScript provides 8 mathematical constants that can be accessed with the
Math object:

Example
Math.E // returns Euler's number
Math.PI // returns PI
Math.SQRT2 // returns the square root of 2
Math.SQRT1_2 // returns the square root of 1/2
Math.LN2 // returns the natural logarithm of 2
Math.LN10 // returns the natural logarithm of 10
Math.LOG2E // returns base 2 logarithm of E
Math.LOG10E // returns base 10 logarithm of E

Try it Yourself »

92
www.Sohrabpoor.com

Math Object Methods


Method Description

abs(x) Returns the absolute value of x

acos(x) Returns the arccosine of x, in radians

asin(x) Returns the arcsine of x, in radians

atan(x) Returns the arctangent of x as a numeric value between -PI/2 and PI/2
radians

atan2(y,x) Returns the arctangent of the quotient of its arguments

ceil(x) Returns x, rounded upwards to the nearest integer

cos(x) Returns the cosine of x (x is in radians)

exp(x) Returns the value of Ex

floor(x) Returns x, rounded downwards to the nearest integer

log(x) Returns the natural logarithm (base E) of x

max(x,y,z,...,n) Returns the number with the highest value

93
www.Sohrabpoor.com

min(x,y,z,...,n) Returns the number with the lowest value

pow(x,y) Returns the value of x to the power of y

random() Returns a random number between 0 and 1

round(x) Rounds x to the nearest integer

sin(x) Returns the sine of x (x is in radians)

sqrt(x) Returns the square root of x

tan(x) Returns the tangent of an angle

Complete Math Reference


For a complete reference, go to our complete Math object reference.

The reference contains descriptions and examples of all Math properties and
methods.

JavaScript Dates
The Date object lets you work with dates (years, months, days, hours,
minutes, seconds, and milliseconds)

94
www.Sohrabpoor.com

JavaScript Date Formats


A JavaScript date can be written as a string:

Fri Sep 16 2016 09:49:13 GMT+0430 (Iran Daylight Time)

or as a number:

1474003153194

Dates written as numbers, specifies the number of milliseconds since January


1, 1970, 00:00:00.

Displaying Dates
In this tutorial we use a script to display dates inside a <p> element with
id="demo":

Example
<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = Date();
</script>

Try it Yourself »

The script above says: assign the value of Date() to the content (innerHTML)
of the element with id="demo".

You will learn how to display a date, in a more readable format, at the
bottom of this page.

Creating Date Objects


The Date object lets us work with dates.

A date consists of a year, a month, a day, an hour, a minute, a second, and


milliseconds.

Date objects are created with the new Date() constructor.

95
www.Sohrabpoor.com

There are 4 ways of initiating a date:

new Date()
new Date(milliseconds)
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds)

Using new Date(), creates a new date object with the current date and
time:

Example
<script>
var d = new Date();
document.getElementById("demo").innerHTML = d;
</script>

Try it Yourself »

Using new Date(date string), creates a new date object from the specified
date and time:

Example
<script>
var d = new Date("October 13, 2014 11:13:00");
document.getElementById("demo").innerHTML = d;
</script>

Try it Yourself »

Valid date strings (date formats) are described in the next chapter.

Using new Date(number), creates a new date object as zero time plus the
number.

Zero time is 01 January 1970 00:00:00 UTC. The number is specified in


milliseconds:

Example
<script>
var d = new Date(86400000);
document.getElementById("demo").innerHTML = d;
</script>

Try it Yourself »

JavaScript dates are calculated in milliseconds from 01 January, 1970


00:00:00 Universal Time (UTC). One day contains 86,400,000 millisecond.

96
www.Sohrabpoor.com

Using new Date(7 numbers), creates a new date object with the specified
date and time:

The 7 numbers specify the year, month, day, hour, minute, second, and
millisecond, in that order:

Example
<script>
var d = new Date(99,5,24,11,33,30,0);
document.getElementById("demo").innerHTML = d;
</script>

Try it Yourself »

Variants of the example above let us omit any of the last 4 parameters:

Example
<script>
var d = new Date(99,5,24);
document.getElementById("demo").innerHTML = d;
</script>

Try it Yourself »

JavaScript counts months from 0 to 11. January is 0. December is 11.

Date Methods
When a Date object is created, a number of methods allow you to operate
on it.

Date methods allow you to get and set the year, month, day, hour, minute,
second, and millisecond of objects, using either local time or UTC (universal,
or GMT) time.

Date methods are covered in a later chapter.

Displaying Dates
When you display a date object in HTML, it is automatically converted to a
string, with the toString() method.

97
www.Sohrabpoor.com

Example
<p id="demo"></p>

<script>
d = new Date();
document.getElementById("demo").innerHTML = d;
</script>

Is the same as:

<p id="demo"></p>

<script>
d = new Date();
document.getElementById("demo").innerHTML = d.toString();
</script>

Try it Yourself »

The toUTCString() method converts a date to a UTC string (a date display


standard).

Example
<script>
var d = new Date();
document.getElementById("demo").innerHTML = d.toUTCString();
</script>

Try it Yourself »

The toDateString() method converts a date to a more readable format:

Example
<script>
var d = new Date();
document.getElementById("demo").innerHTML = d.toDateString();
</script>

Try it Yourself »

Date objects are static. The computer time is ticking, but date objects, once
created, are not.

98
www.Sohrabpoor.com

Time Zones
When setting a date, without specifying the time zone, JavaScript will use the
browser's time zone.

When getting a date, without specifying the time zone, the result is
converted to the browser's time zone.

In other words: If a date/time is created in GMT (Greenwich Mean Time), the


date/time will be converted to CDT (Central US Daylight Time) if a user
browses from central US.

Read more about time zones in the next chapters.

JavaScript Date Formats


JavaScript Date Input
There are generally 4 types of JavaScript date input formats:

Type Example

ISO Date "2015-03-25" (The International Standard)

Short Date "03/25/2015" or "2015/03/25"

Long Date "Mar 25 2015" or "25 Mar 2015"

Full Date "Wednesday March 25 2015"

99
www.Sohrabpoor.com

JavaScript Date Output


Independent of input format, JavaScript will (by default) output dates in full
text string format:

Wed Mar 25 2015 04:30:00 GMT+0430 (Iran Daylight Time)

JavaScript ISO Dates


ISO 8601 is the international standard for the representation of dates and
times.

The ISO 8601 syntax (YYYY-MM-DD) is also the preferred JavaScript date
format:

Example (Complete date)


var d = new Date("2015-03-25");

Try it Yourself »

The computed date will be relative to your time zone.


Depending on your time zone, the result above will vary between March 24
and March 25.

It can be written without specifying the day (YYYY-MM):

Example (Year and month)


var d = new Date("2015-03");

Try it Yourself »

Time zones will vary the result above between February 28 and March 01.

It can be written without month and day (YYYY):

Example (Only year)


var d = new Date("2015");

Try it Yourself »

Time zones will vary the result above between December 31 2014 and
January 01 2015.

100
www.Sohrabpoor.com

It can be written with added hours, minutes, and seconds (YYYY-MM-


DDTHH:MM:SS):

Example (Complete date plus hours, minutes, and


seconds)
var d = new Date("2015-03-25T12:00:00");

Try it Yourself »

The T in the date string, between the date and time, indicates UTC time.

UTC (Universal Time Coordinated) is the same as GMT (Greenwich Mean


Time).

JavaScript Short Dates.


Short dates are most often written with an "MM/DD/YYYY" syntax like this:

Example
var d = new Date("03/25/2015");

Try it Yourself »

JavaScript will also accept "YYYY/MM/DD":

Example
var d = new Date("2015/03/25");

Try it Yourself »

Month is written before day in all short date and ISO date formats.

Leading Zero WARNING !


In most browsers, ISO dates with months or days with no leading zeroes will
be interpreted as short dates:

101
www.Sohrabpoor.com

Example
var d = new Date("2015-03-25");

var d = new Date("2015-3-25");

Try it Yourself »

JavaScript Long Dates.


Long dates are most often written with a "MMM DD YYYY" syntax like this:

Example
var d = new Date("Mar 25 2015");

Try it Yourself »

Month and day can be in any order:

Example
var d = new Date("25 Mar 2015");

Try it Yourself »

And, month can be written in full (January), or abbreviated (Jan):

Example
var d = new Date("January 25 2015");

Try it Yourself »

Example
var d = new Date("Jan 25 2015");

Try it Yourself »

Commas are ignored. Names are case insensitive:

Example
var d = new Date("JANUARY, 25, 2015");

Try it Yourself »

102
www.Sohrabpoor.com

Full Date Format


JavaScript will accept date strings in "full JavaScript format":

Example
var d = new Date("Wed Mar 25 2015 09:56:24 GMT+0100 (W. Europe Standard
Time)");

Try it Yourself »

JavaScript will ignore errors both in the day name and in the time
parentheses:

Example
var d = new Date("Fri Mar 25 2015 09:56:24 GMT+0100 (Tokyo Time)");

Try it Yourself »

Time Zones
JavaScript accepts these time zones:

Time Zone Description

UTC Coordinated Universal Time

GMT Greenwich Mean Time

EDT (US) Eastern Daylight Time

CDT (US) Central Daylight Time

103
www.Sohrabpoor.com

MDT (US) Mountain Daylight Time

PDT (US) Pacific Daylight Time

EST (US) Eastern Standard Time

CST (US) Central Standard Time

MST (US) Mountain Standard Time

PST (US) Pacific Standard Time

When setting a date, without specifying the time zone, JavaScript will use the
browser's time zone.

When getting a date, without specifying the time zone, the result is
converted to the browser's time zone.

In other words: If a date/time is created in GMT (Greenwich Mean Time), the


date/time will be converted to CDT (Central US Daylight Time) if a user
browses from central US.

JavaScript Date Methods


Date methods let you get and set date values (years, months, days,
hours, minutes, seconds, milliseconds)

Date Get Methods


Get methods are used for getting a part of a date. Here are the most
common (alphabetically):

104
www.Sohrabpoor.com

Method Description

getDate() Get the day as a number (1-31)

getDay() Get the weekday as a number (0-6)

getFullYear() Get the four digit year (yyyy)

getHours() Get the hour (0-23)

getMilliseconds() Get the milliseconds (0-999)

getMinutes() Get the minutes (0-59)

getMonth() Get the month (0-11)

getSeconds() Get the seconds (0-59)

getTime() Get the time (milliseconds since January 1, 1970)

The getTime() Method


getTime() returns the number of milliseconds since January 1, 1970:

Example
<script>
var d = new Date();
document.getElementById("demo").innerHTML = d.getTime();
</script>

Try it Yourself »

105
www.Sohrabpoor.com

The getFullYear() Method


getFullYear() returns the year of a date as a four digit number:

Example
<script>
var d = new Date();
document.getElementById("demo").innerHTML = d.getFullYear();
</script>

Try it Yourself »

The getDay() Method


getDay() returns the weekday as a number (0-6):

Example
<script>
var d = new Date();
document.getElementById("demo").innerHTML = d.getDay();
</script>

Try it Yourself »

In JavaScript, the first day of the week (0) means "Sunday", even if some
countries in the world consider the first day of the week to be "Monday"

You can use an array of names, and getDay() to return the weekday as a
name:

Example
<script>
var d = new Date();
var days =
["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
document.getElementById("demo").innerHTML = days[d.getDay()];
</script>

Try it Yourself »

106
www.Sohrabpoor.com

Date Set Methods


Set methods are used for setting a part of a date. Here are the most
common (alphabetically):

Method Description

setDate() Set the day as a number (1-31)

setFullYear() Set the year (optionally month and day)

setHours() Set the hour (0-23)

setMilliseconds() Set the milliseconds (0-999)

setMinutes() Set the minutes (0-59)

setMonth() Set the month (0-11)

setSeconds() Set the seconds (0-59)

setTime() Set the time (milliseconds since January 1, 1970)

The setFullYear() Method


setFullYear() sets a date object to a specific date. In this example, to
January 14, 2020:

107
www.Sohrabpoor.com

Example
<script>
var d = new Date();
d.setFullYear(2020, 0, 14);
document.getElementById("demo").innerHTML = d;
</script>

Try it Yourself »

The setDate() Method


setDate() sets the day of the month (1-31):

Example
<script>
var d = new Date();
d.setDate(20);
document.getElementById("demo").innerHTML = d;
</script>

Try it Yourself »

The setDate() method can also be used to add days to a date:

Example
<script>
var d = new Date();
d.setDate(d.getDate() + 50);
document.getElementById("demo").innerHTML = d;
</script>

Try it Yourself »

If adding days, shifts the month or year, the changes are handled
automatically by the Date object.

Date Input - Parsing Dates


If you have a valid date string, you can use the Date.parse() method to
convert it to milliseconds.

108
www.Sohrabpoor.com

Date.parse() returns the number of milliseconds between the date and


January 1, 1970:

Example
<script>
var msec = Date.parse("March 21, 2012");
document.getElementById("demo").innerHTML = msec;
</script>

Try it Yourself »

You can then use the number of milliseconds to convert it to a date object:

Example
<script>
var msec = Date.parse("March 21, 2012");
var d = new Date(msec);
document.getElementById("demo").innerHTML = d;
</script>

Try it Yourself »

Compare Dates
Dates can easily be compared.

The following example compares today's date with January 14, 2100:

Example
var today, someday, text;
today = new Date();
someday = new Date();
someday.setFullYear(2100, 0, 14);

if (someday > today) {


text = "Today is before January 14, 2100.";
} else {
text = "Today is after January 14, 2100.";
}
document.getElementById("demo").innerHTML = text;

Try it Yourself »

JavaScript counts months from 0 to 11. January is 0. December is 11.

109
www.Sohrabpoor.com

UTC Date Methods


UTC date methods are used for working UTC dates (Univeral Time Zone
dates):

Method Description

getUTCDate() Same as getDate(), but returns the UTC date

getUTCDay() Same as getDay(), but returns the UTC day

getUTCFullYear() Same as getFullYear(), but returns the UTC year

getUTCHours() Same as getHours(), but returns the UTC hour

getUTCMilliseconds() Same as getMilliseconds(), but returns the UTC milliseconds

getUTCMinutes() Same as getMinutes(), but returns the UTC minutes

getUTCMonth() Same as getMonth(), but returns the UTC month

getUTCSeconds() Same as getSeconds(), but returns the UTC seconds

Complete JavaScript Date Reference


For a complete reference, go to our Complete JavaScript Date Reference.

The reference contains descriptions and examples of all Date properties and
methods.

110
www.Sohrabpoor.com

JavaScript Arrays
JavaScript arrays are used to store multiple values in a single variable.

Example
var cars = ["Saab", "Volvo", "BMW"];

Try it Yourself »

What is an Array?
An array is a special variable, which can hold more than one value at a time.

If you have a list of items (a list of car names, for example), storing the cars
in single variables could look like this:

var car1 = "Saab";


var car2 = "Volvo";
var car3 = "BMW";

However, what if you want to loop through the cars and find a specific one?
And what if you had not 3 cars, but 300?

The solution is an array!

An array can hold many values under a single name, and you can access the
values by referring to an index number.

Creating an Array
Using an array literal is the easiest way to create a JavaScript Array.

Syntax:

var array-name = [item1, item2, ...];

Example
var cars = ["Saab", "Volvo", "BMW"];

Try it Yourself »

111
www.Sohrabpoor.com

Spaces and line breaks are not important. A declaration can span multiple
lines:

Example
var cars = [
"Saab",
"Volvo",
"BMW"
];

Try it Yourself »

Never put a comma after the last element (like "BMW",).


The effect is inconsistent across browsers.

Using the JavaScript Keyword new


The following example also creates an Array, and assigns values to it:

Example
var cars = new Array("Saab", "Volvo", "BMW");

Try it Yourself »

The two examples above do exactly the same. There is no need to use new
Array().
For simplicity, readability and execution speed, use the first one (the array
literal method).

Access the Elements of an Array


You refer to an array element by referring to the index number.

This statement accesses the value of the first element in cars:

var name = cars[0];

This statement modifies the first element in cars:

cars[0] = "Opel";

112
www.Sohrabpoor.com

Example
var cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars[0];

Try it Yourself »

[0] is the first element in an array. [1] is the second. Array indexes start
with 0.

Access the Full Array


With JavaScript, the full array can be accessed by referring to the array
name:

Example
var cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars;

Try it Yourself »

Arrays are Objects


Arrays are a special type of objects. The typeof operator in JavaScript
returns "object" for arrays.

But, JavaScript arrays are best described as arrays.

Arrays use numbers to access its "elements". In this


example, person[0] returns John:

Array:
var person = ["John", "Doe", 46];

Try it Yourself »

Objects use names to access its "members". In this


example, person.firstName returns John:

Object:
var person = {firstName:"John", lastName:"Doe", age:46};

Try it Yourself »

113
www.Sohrabpoor.com

Array Elements Can Be Objects


JavaScript variables can be objects. Arrays are special kinds of objects.

Because of this, 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:

myArray[0] = Date.now;
myArray[1] = myFunction;
myArray[2] = myCars;

Array Properties and Methods


The real strength of JavaScript arrays are the built-in array properties and
methods:

Examples
var x = cars.length; // The length property returns the number of
elements
var y = cars.sort(); // The sort() method sorts arrays

Array methods are covered in the next chapters.

The length Property


The length property of an array returns the length of an array (the number
of array elements).

Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.length; // the length of fruits is 4

Try it Yourself »

The length property is always one more than the highest array index.

114
www.Sohrabpoor.com

Looping Array Elements


The best way to loop through an array, is using a "for" loop:

Example
var fruits, text, fLen, i;

fruits = ["Banana", "Orange", "Apple", "Mango"];


fLen = fruits.length;
text = "<ul>";
for (i = 0; i < fLen; i++) {
text += "<li>" + fruits[i] + "</li>";
}

Try it Yourself »

Adding Array Elements


The easiest way to add a new element to an array is using the push method:

Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Lemon"); // adds a new element (Lemon) to
fruits

Try it Yourself »

New element can also be added to an array using the length property:

Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[fruits.length] = "Lemon"; // adds a new element (Lemon) to
fruits

Try it Yourself »

WARNING !

Adding elements with high indexes can create undefined "holes" in an array:

115
www.Sohrabpoor.com

Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[6] = "Lemon"; // adds a new element (Lemon) to
fruits

Try it Yourself »

Associative Arrays
Many programming languages support arrays with named indexes.

Arrays with named indexes are called associative arrays (or hashes).

JavaScript does not support arrays with named indexes.

In JavaScript, arrays always use numbered indexes.

Example
var person = [];
person[0] = "John";
person[1] = "Doe";
person[2] = 46;
var x = person.length; // person.length will return 3
var y = person[0]; // person[0] will return "John"

Try it Yourself »

WARNING !!
If you use a named index, JavaScript will redefine the array to a standard
object.
After that, all array methods and properties will produce incorrect
results.

Example:
var person = [];
person["firstName"] = "John";
person["lastName"] = "Doe";
person["age"] = 46;
var x = person.length; // person.length will return 0
var y = person[0]; // person[0] will return undefined

Try it Yourself »

116
www.Sohrabpoor.com

The Difference Between Arrays and Objects


In JavaScript, arrays use numbered indexes.

In JavaScript, objects use named indexes.

Arrays are a special kind of objects, with numbered indexes.

When to Use Arrays. When to use Objects.


 JavaScript does not support associative arrays.
 You should use objects when you want the element names to
be strings (text).
 You should use arrays when you want the element names to
be numbers.

Avoid new Array()


There is no need to use the JavaScript's built-in array
constructor new Array().

Use [] instead.

These two different statements both create a new empty array named
points:

var points = new Array(); // Bad


var points = []; // Good

These two different statements both create a new array containing 6


numbers:

var points = new Array(40, 100, 1, 5, 25, 10); // Bad


var points = [40, 100, 1, 5, 25, 10]; // Good

Try it Yourself »

The new keyword only complicates the code. It can also produce some
unexpected results:

var points = new Array(40, 100); // Creates an array with two elements
(40 and 100)

117
www.Sohrabpoor.com

What if I remove one of the elements?

var points = new Array(40); // Creates an array with 40 undefined


elements !!!!!

Try it Yourself »

How to Recognize an Array


A common question is: How do I know if a variable is an array?

The problem is that the JavaScript operator typeof returns "object":

var fruits = ["Banana", "Orange", "Apple", "Mango"];

typeof fruits; // returns object

Try it Yourself »

The typeof operator returns object because a JavaScript array is an object.

Solution 1:
To solve this problem ECMAScript 5 defines a new method Array.isArray():

Array.isArray(fruits); // returns true

Try it Yourself »

The problem with this solution is that ECMAScript 5 is not supported in


older browsers.

Solution 2:
To solve this problem you can create your own isArray() function:

function isArray(x) {
return x.constructor.toString().indexOf("Array") > -1;
}

Try it Yourself »

The function above always returns true if the argument is an array.

Or more precisely: it returns true if the object prototype contains the word
"Array".

118
www.Sohrabpoor.com

Solution 3:
The instanceof operator returns true if an object is created by a given
constructor:

var fruits = ["Banana", "Orange", "Apple", "Mango"];

fruits instanceof Array // returns true

Try it Yourself »

JavaScript Array Methods


The strength of JavaScript arrays lies in the array methods.

Converting Arrays to Strings


The JavaScript method toString() converts an array to a string of (comma
separated) array values.

Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.toString();

Result
Banana,Orange,Apple,Mango

Try it Yourself »

The join() method also joins all array elements into a string.

It behaves just like toString(), but in addition you can specify the separator:

Example
var fruits = ["Banana", "Orange","Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.join(" * ");

Result
Banana * Orange * Apple * Mango

Try it Yourself »

119
www.Sohrabpoor.com

Popping and Pushing


When you work with arrays, it is easy to remove elements and add new
elements.

This is what popping and pushing is:

Popping items out of an array, or pushing items into an array.

Popping
The pop() method removes the last element from an array:

Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.pop(); // Removes the last element ("Mango") from
fruits

Try it Yourself »

The pop() method returns the value that was "popped out":

Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var x = fruits.pop(); // the value of x is "Mango"

Try it Yourself »

Pushing
The push() method adds a new element to an array (at the end):

Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi"); // Adds a new element ("Kiwi") to fruits

Try it Yourself »

The push() method returns the new array length:

120
www.Sohrabpoor.com

Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var x = fruits.push("Kiwi"); // the value of x is 5

Try it Yourself »

Shifting Elements
Shifting is equivalent to popping, working on the first element instead of the
last.

The shift() method removes the first array element and "shifts" all other
elements to a lower index.

Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.shift(); // Removes the first element "Banana" from
fruits

Try it Yourself »

The unshift() method adds a new element to an array (at the beginning),
and "unshifts" older elements:

Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.unshift("Lemon"); // Adds a new element "Lemon" to fruits

Try it Yourself »

The shift() method returns the string that was "shifted out".

The unshift() method returns the new array length.

Changing Elements
Array elements are accessed using their index number:

Array indexes start with 0. [0] is the first array element, [1] is the second,
[2] is the third ...

121
www.Sohrabpoor.com

Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[0] = "Kiwi"; // Changes the first element of fruits to
"Kiwi"

Try it Yourself »

The length property provides an easy way to append a new element to an


array:

Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[fruits.length] = "Kiwi"; // Appends "Kiwi" to fruit

Try it Yourself »

Deleting Elements
Since JavaScript arrays are objects, elements can be deleted by using the
JavaScript operator delete:

Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
delete fruits[0]; // Changes the first element in fruits to undefined

Try it Yourself »

Using delete may leave undefined holes in the array. Use pop() or shift()
instead.

Splicing an Array
The splice() method can be used to add new items to an array:

Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 0, "Lemon", "Kiwi");

Try it Yourself »

122
www.Sohrabpoor.com

The first parameter (2) defines the position where new elements should
be added (spliced in).

The second parameter (0) defines how many elements should be removed.

The rest of the parameters ("Lemon" , "Kiwi") define the new elements to
be added.

Using splice() to Remove Elements


With clever parameter setting, you can use splice() to remove elements
without leaving "holes" in the array:

Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(0, 1); // Removes the first element of fruits

Try it Yourself »

The first parameter (0) defines the position where new elements should
be added (spliced in).

The second parameter (1) defines how many elements should be removed.

The rest of the parameters are omitted. No new elements will be added.

Joining Arrays
The concat() method creates a new array by concatenating two arrays:

Example
var myGirls = ["Cecilie", "Lone"];
var myBoys = ["Emil", "Tobias","Linus"];
var myChildren = myGirls.concat(myBoys); // Concatenates (joins)
myGirls and myBoys

Try it Yourself »

The concat() method can take any number of array arguments:

123
www.Sohrabpoor.com

Example
var arr1 = ["Cecilie", "Lone"];
var arr2 = ["Emil", "Tobias","Linus"];
var arr3 = ["Robin", "Morgan"];
var myChildren = arr1.concat(arr2, arr3); // Concatenates arr1 with
arr2 and arr3

document.getElementById("demo").innerHTML = myChildren;
Try it Yourself »

Slicing an Array
The slice() method slices out a piece of an array into a new array.

This example slices out a part of an array starting from array element 1
("Orange"):

Example
var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var citrus = fruits.slice(1);

Try it Yourself »

The slice() method creates a new array. It does not remove any elements
from the source array.

This example slices out a part of an array starting from array element 3
("Apple"):

Example
var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var citrus = fruits.slice(3);

Try it Yourself »

The slice() method can take two arguments like slice(1,3).

The method then selects elements from the start argument, and up to (but
not including) the end argument.

124
www.Sohrabpoor.com

Example
var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var citrus = fruits.slice(1, 3);

Try it Yourself »

If the end argument is omitted, like in the first examples, the slice() method
slices out the rest of the array.

Example
var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var citrus = fruits.slice(2);

Try it Yourself »

The valueOf() Method


The valueOf() method is the default behavior for an array. It converts an
array to a primitive value.

JavaScript will automatically convert an array to a string when a primitive


value is expected.

Because of this, all these examples will produce the same result:

Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits;

Try it Yourself »

Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.valueOf();

Try it Yourself »

Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.toString();

Try it Yourself »

125
www.Sohrabpoor.com

All JavaScript objects have a valueOf() and a toString() method.

Sorting Arrays
Sorting arrays are covered in the next chapter of this tutorial.

Complete Array Reference


For a complete reference, go to our Complete JavaScript Array Reference.

The reference contains descriptions and examples of all Array properties and
methods.

JavaScript Sorting Arrays


The sort() method is one of the strongest array methods.

Sorting an Array
The sort() method sorts an array alphabetically:

Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort(); // Sorts the elements of fruits

Try it Yourself »

Reversing an Array
The reverse() method reverses the elements in an array.

You can use it to sort an array in descending order:

126
www.Sohrabpoor.com

Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort(); // Sorts the elements of fruits
fruits.reverse(); // Reverses the order of the elements

Try it Yourself »

Numeric Sort
By default, the sort() function sorts values as strings.

This works well for strings ("Apple" comes before "Banana").

However, if numbers are sorted as strings, "25" is bigger than "100",


because "2" is bigger than "1".

Because of this, the sort() method will produce incorrect result when sorting
numbers.

You can fix this by providing a compare function:

Example
var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a - b});

Try it Yourself »

Use the same trick to sort an array descending:

Example
var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return b - a});

Try it Yourself »

The Compare Function


The purpose of the compare function is to define an alternative sort order.

127
www.Sohrabpoor.com

The compare function should return a negative, zero, or positive value,


depending on the arguments:

function(a, b){return a-b}

When the sort() function compares two values, it sends the values to the
compare function, and sorts the values according to the returned (negative,
zero, positive) value.

Example:

When comparing 40 and 100, the sort() method calls the compare
function(40,100).

The function calculates 40-100, and returns -60 (a negative value).

The sort function will sort 40 as a value lower than 100.

You can use this code snippet to experiment with numerically and
alphabetically sorting:

<button onclick="myFunction1()">Sort Alphabetically</button>


<button onclick="myFunction2()">Sort Numerically</button>

<p id="demo"></p>

<script>
var points = [40, 100, 1, 5, 25, 10];
document.getElementById("demo").innerHTML = points;

function myFunction1() {
points.sort();
document.getElementById("demo").innerHTML = points;
}
function myFunction2() {
points.sort(function(a, b){return a - b});
document.getElementById("demo").innerHTML = points;
}
</script>

Try it Yourself »

128
www.Sohrabpoor.com

Sorting an Array in Random Order


Example
var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return 0.5 - Math.random()});

Try it Yourself »

Find the Highest (or Lowest) Value


How to find the highest value in an array?

Example
var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return b - a});
// now points[0] contains the highest value

Try it Yourself »

And the lowest:

Example
var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a - b});
// now points[0] contains the lowest value

Try it Yourself »

Sorting Object Arrays


JavaScript arrays often contain objects:

Example
var cars = [
{type:"Volvo", year:2016},
{type:"Saab", year:2001},
{type:"BMW", year:2010}];

129
www.Sohrabpoor.com

Even if objects have properties of different data types, the sort() method can
be used to sort the array.

The solution is to write a compare function to compare the property values:

Example
cars.sort(function(a, b){return a.year - b.year});

Try it Yourself »

Comparing string properties is a little more complex::

Example
cars.sort(function(a, b){
var x = a.type.toLowerCase();
var y = b.type.toLowerCase();
if (x < y) {return -1;}
if (x > y) {return 1;}
return 0;
});

Try it Yourself »

JavaScript Booleans
A JavaScript Boolean represents one of two values: true or false.

Boolean Values
Very often, in programming, you will need a data type that can only have
one of two values, like

 YES / NO
 ON / OFF
 TRUE / FALSE

For this, JavaScript has a Boolean data type. It can only take the
values true or false.

130
www.Sohrabpoor.com

The Boolean() Function


You can use the Boolean() function to find out if an expression (or a variable)
is true:

Example
Boolean(10 > 9) // returns true

Try it Yourself »

Or even easier:

Example
(10 > 9) // also returns true
10 > 9 // also returns true

Try it Yourself »

Comparisons and Conditions


The chapter JS Comparisons gives a full overview of comparison operators.

The chapter JS Conditions gives a full overview of conditional statements.

Here are some examples:

Operator Description Example

== equal to if (day == "Monday")

> greater than if (salary > 9000)

< less than if (age < 18)

The Boolean value of an expression is the fundament for JavaScript


comparisons and conditions.
131
www.Sohrabpoor.com

Everything With a "Real" Value is True


Examples
100

3.14

-15

"Hello"

"false"

7 + 1 + 3.14

5 < 6

Try it Yourself »

Everything Without a "Real" is False


The Boolean value of 0 (zero) is false:

var x = 0;
Boolean(x); // returns false

Try it Yourself »

The Boolean value of -0 (minus zero) is false:

var x = -0;
Boolean(x); // returns false

Try it Yourself »

The Boolean value of "" (empty string) is false:

var x = "";
Boolean(x); // returns false

Try it Yourself »

132
www.Sohrabpoor.com

The Boolean value of undefined is false:

var x;
Boolean(x); // returns false

Try it Yourself »

The Boolean value of null is false:

var x = null;
Boolean(x); // returns false

Try it Yourself »

The Boolean value of false is (you guessed it) false:

var x = false;
Boolean(x); // returns false

Try it Yourself »

The Boolean value of NaN is false:

var x = 10 / "H";
Boolean(x); // returns false

Try it Yourself »

Boolean Properties and Methods


Primitive values, like true and false, cannot have properties or methods
(because they are not objects).

But with JavaScript, methods and properties are also available to primitive
values, because JavaScript treats primitive values as objects when executing
methods and properties.

133
www.Sohrabpoor.com

Complete Boolean Reference


For a complete reference, go to our Complete JavaScript Boolean Reference.

The reference contains descriptions and examples of all Boolean properties


and methods.

JavaScript Comparison and Logical


Operators
Comparison and Logical operators are used to test for true or false.

Comparison Operators
Comparison operators are used in logical statements to determine equality or
difference between variables or values.

Given that x = 5, the table below explains the comparison operators:

Operator Description Comparing Returns Try it

== equal to x == 8 false Try it »

x == 5 true Try it »

x == "5" true Try it »

=== x === 5 true Try it »

134
www.Sohrabpoor.com

equal value and x === "5" false Try it »


equal type

!= not equal x != 8 true Try it »

!== not equal value or x !== 5 false Try it »


not equal type

x !== "5" true Try it »

x !== 8 true Try it »

> greater than x>8 false Try it »

< less than x<8 true Try it »

>= greater than or equal x >= 8 false Try it »


to

<= less than or equal to x <= 8 true Try it »

How Can it be Used


Comparison operators can be used in conditional statements to compare
values and take action depending on the result:

if (age < 18) text = "Too young";

You will learn more about the use of conditional statements in the next
chapter of this tutorial.

135
www.Sohrabpoor.com

Logical Operators
Logical operators are used to determine the logic between variables or
values.

Given that x = 6 and y = 3, the table below explains the logical operators:

Operator Description Example Try it

&& and (x < 10 && y > 1) is true Try it »

|| or (x == 5 || y == 5) is false Try it »

! not !(x == y) is true Try it »

Conditional (Ternary) Operator


JavaScript also contains a conditional operator that assigns a value to a
variable based on some condition.

Syntax
variablename = (condition) ? value1:value2

Example
var voteable = (age < 18) ? "Too young":"Old enough";

Try it Yourself »

If the variable age is a value below 18, the value of the variable voteable will
be "Too young", otherwise the value of voteable will be "Old enough".

136
www.Sohrabpoor.com

Comparing Different Types


Comparing data of different types may give unexpected results.

When comparing a string with a number, JavaScript will convert the string to
a number when doing the comparison. An empty string converts to 0. A non-
numeric string converts to NaN which is always false.

Case Value Try

2 < 12 true Try it »

2 < "12" true Try it »

2 < "John" false Try it »

2 > "John" false Try it »

2 == "John" false Try it »

"2" < "12" false Try it »

"2" > "12" true Try it »

"2" == "12" false Try it »

When comparing two strings, "2" will be greater than "12", because
(alphabetically) 1 is less than 2.

To secure a proper result, variables should be converted to the proper type


before comparison:

137
www.Sohrabpoor.com

age = Number(age);
if (isNaN(age)) {
voteable = "Error in input";
} else {
voteable = (age < 18) ? "Too young" : "Old enough";
}

Try it Yourself »

JavaScript Bitwise Operators


Bit operators work on 32-bit 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 x=5&1 0101 & 0001 0001 1

| OR x=5|1 0101 | 0001 0101 5

~ NOT x=~5 ~0101 1010 10

^ XOR x=5^1 0101 ^ 0001 0100 4

<< Left shift x = 5 << 1 0101 << 1 1010 10

>> Right shift x = 5 >> 1 0101 >> 1 0010 2

The table above use 4 bits unsigned examples. But JavaScript uses 32-bit
signed numbers.
Because of this, in JavaScript, ~ 5 will not return 10. It will return -6:

138
www.Sohrabpoor.com

~00000000000000000000000000000101 will return


11111111111111111111111111111010

Example
x = 5 & 1;

The result in x:

Try it Yourself »

Example
x = 5 | 1;

The result in x:

Try it Yourself »

Example
x = 5 >> 1;

The result in x:

Try it Yourself »

Example
x = 5 << 1;

The result in x:

10

Try it Yourself »

Example
x = ~ 5;

The result in x:

-6

Try it Yourself »

139
www.Sohrabpoor.com

JavaScript If...Else Statements


Conditional statements are used to perform different actions based on
different conditions.

Conditional Statements
Very often when you write code, you want to perform different actions for
different decisions.

You can use conditional statements in your code to do this.

In JavaScript we have the following conditional statements:

 Use if to specify a block of code to be executed, if a specified condition


is true
 Use else to specify a block of code to be executed, if the same
condition is false
 Use else if to specify a new condition to test, if the first condition is
false
 Use switch to specify many alternative blocks of code to be executed

The if Statement
Use the if statement to specify a block of JavaScript code to be executed if a
condition is true.

Syntax
if (condition) {
block of code to be executed if the condition is true
}

Note that if is in lowercase letters. Uppercase letters (If or IF) will generate a
JavaScript error.

Example
Make a "Good day" greeting if the hour is less than 18:00:

140
www.Sohrabpoor.com

if (hour < 18) {


greeting = "Good day";
}

The result of greeting will be:

Good day

Try it Yourself »

The else Statement


Use the else statement to specify a block of code to be executed if the
condition is false.

if (condition) {
block of code to be executed if the condition is true
} else {
block of code to be executed if the condition is false
}

Example
If the hour is less than 18, create a "Good day" greeting, otherwise "Good
evening":

if (hour < 18) {


greeting = "Good day";
} else {
greeting = "Good evening";
}

The result of greeting will be:

Good day

Try it Yourself »

The else if Statement


Use the else if statement to specify a new condition if the first condition is
false.

141
www.Sohrabpoor.com

Syntax
if (condition1) {
block of code to be executed if condition1 is true
} else if (condition2) {
block of code to be executed if the condition1 is false and condition2
is true
} else {
block of code to be executed if the condition1 is false and condition2
is false
}

Example
If time is less than 10:00, create a "Good morning" greeting, if not, but time
is less than 20:00, create a "Good day" greeting, otherwise a "Good
evening":

if (time < 10) {


greeting = "Good morning";
} else if (time < 20) {
greeting = "Good day";
} else {
greeting = "Good evening";
}

The result of greeting will be:

Good morning

Try it Yourself »

More Examples
Random link
This example will write a link to either W3Schools or to the World Wildlife
Foundation (WWF). By using a random number, there is a 50% chance for
each of the links.

142
www.Sohrabpoor.com

JavaScript Switch Statement


The switch statement is used to perform different actions based on
different conditions.

The JavaScript Switch Statement


Use the switch statement to select one of many blocks of code to be
executed.

Syntax
switch(expression) {
case n:
code block
break;
case n:
code block
break;
default:
default code block
}

This is how it works:

 The switch expression is evaluated once.


 The value of the expression is compared with the values of each case.
 If there is a match, the associated block of code is executed.

Example
The getDay() method returns the weekday as a number between 0 and 6.
(Sunday=0, Monday=1, Tuesday=2 ..)

Use the weekday number to calculate weekday name:

switch (new Date().getDay()) {


case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:

143
www.Sohrabpoor.com

day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
}

document.getElementById("demo").innerHTML = "Today is " + day;

The result of day will be:

Friday

Try it Yourself »

The break Keyword


When JavaScript reaches a break keyword, it breaks out of the switch block.

This will stop the execution of more code and case testing inside the block.

When a match is found, and the job is done, it's time for a break. There is no
need for more testing.

A break can save a lot of execution time because it "ignores" the execution of
all the rest of the code in the switch block.

It is not necessary to break the last case in a switch block. The block breaks
(ends) there anyway.

144
www.Sohrabpoor.com

The default Keyword


The default keyword specifies the code to run if there is no case match:

Example
The getDay() method returns the weekday as a number between 0 and 6.

If today is neither Saturday (6) nor Sunday (0), write a default message:

switch (new Date().getDay()) {


case 6:
text = "Today is Saturday";
break;
case 0:
text = "Today is Sunday";
break;
default:
text = "Looking forward to the Weekend";
}

The result of text will be:

Looking forward to the Weekend

Try it Yourself »

Common Code and Fall-Through


Sometimes, in a switch block, you will want different cases to use the same
code, or fall-through to a common default.

Note from the next example, that cases can share the same code block, and
that the default case does not have to be the last case in a switch block:

Example
switch (new Date().getDay()) {
case 1:
case 2:
case 3:
default:
text = "Looking forward to the Weekend";
break;

145
www.Sohrabpoor.com

case 4:
case 5:
text = "Soon it is Weekend";
break;
case 0:
case 6:
text = "It is Weekend";
}

Try it Yourself »

If default is not the last case in the switch block, remember to end it with a
break.

JavaScript For Loop


Loops can execute a block of code a number of times.

JavaScript Loops
Loops are handy, if you want to run the same code over and over again,
each time with a different value.

Often this is the case when working with arrays:

Instead of writing:
text += cars[0] + "<br>";
text += cars[1] + "<br>";
text += cars[2] + "<br>";
text += cars[3] + "<br>";
text += cars[4] + "<br>";
text += cars[5] + "<br>";

You can write:


for (i = 0; i < cars.length; i++) {
text += cars[i] + "<br>";
}

Try it Yourself »

146
www.Sohrabpoor.com

Different Kinds of Loops


JavaScript supports different kinds of loops:

 for - loops through a block of code a number of times


 for/in - loops through the properties of an object
 while - loops through a block of code while a specified condition is
true
 do/while - also loops through a block of code while a specified
condition is true

The For Loop


The for loop is often the tool you will use when you want to create a loop.

The for loop has the following syntax:

for (statement 1; statement 2; statement 3) {


code block to be executed
}

Statement 1 is executed before the loop (the code block) starts.

Statement 2 defines the condition for running the loop (the code block).

Statement 3 is executed each time after the loop (the code block) has been
executed.

Example
for (i = 0; i < 5; i++) {
text += "The number is " + i + "<br>";
}

Try it Yourself »

From the example above, you can read:

Statement 1 sets a variable before the loop starts (var i = 0).

Statement 2 defines the condition for the loop to run (i must be less than 5).

Statement 3 increases a value (i++) each time the code block in the loop has
been executed.

147
www.Sohrabpoor.com

Statement 1
Normally you will use statement 1 to initiate the variable used in the loop (i
= 0).

This is not always the case, JavaScript doesn't care. Statement 1 is optional.

You can initiate many values in statement 1 (separated by comma):

Example
for (i = 0, len = cars.length, text = ""; i < len; i++) {
text += cars[i] + "<br>";
}

Try it Yourself »

And you can omit statement 1 (like when your values are set before the loop
starts):

Example
var i = 2;
var len = cars.length;
var text = "";
for (; i < len; i++) {
text += cars[i] + "<br>";
}

Try it Yourself »

Statement 2
Often statement 2 is used to evaluate the condition of the initial variable.

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.

If you omit statement 2, you must provide a break inside the loop.
Otherwise the loop will never end. This will crash your browser. Read about
breaks in a later chapter of this tutorial.

148
www.Sohrabpoor.com

Statement 3
Often statement 3 increases the initial variable.

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):

Example
var i = 0;
var len = cars.length;
for (; i < len; ) {
text += cars[i] + "<br>";
i++;
}

Try it Yourself »

The For/In Loop


The JavaScript for/in statement loops through the properties of an object:

Example
var person = {fname:"John", lname:"Doe", age:25};

var text = "";


var x;
for (x in person) {
text += person[x];
}

Try it Yourself »

149
www.Sohrabpoor.com

The While Loop


The while loop and the do/while loop will be explained in the next chapter.

JavaScript While Loop


Loops can execute a block of code as long as a specified condition is true.

The While Loop


The while loop loops through a block of code as long as a specified condition
is true.

Syntax
while (condition) {
code block to be executed
}

Example
In the following example, the code in the loop will run, over and over again,
as long as a variable (i) is less than 10:

Example
while (i < 10) {
text += "The number is " + i;
i++;
}

Try it Yourself »

If you forget to increase the variable used in the condition, the loop will
never end. This will crash your browser.

150
www.Sohrabpoor.com

The Do/While Loop


The do/while loop is a variant of the while loop. This loop will execute the
code block once, before checking if the condition is true, then it will repeat
the loop as long as the condition is true.

Syntax
do {
code block to be executed
}
while (condition);

Example
The example below uses a do/while loop. The loop will always be executed at
least once, even if the condition is false, because the code block is executed
before the condition is tested:

Example
do {
text += "The number is " + i;
i++;
}
while (i < 10);

Try it Yourself »

Do not forget to increase the variable used in the condition, otherwise the
loop will never end!

Comparing For and While


If you have read the previous chapter, about the for loop, you will discover
that a while loop is much the same as a for loop, with statement 1 and
statement 3 omitted.

The loop in this example uses a for loop to collect the car names from the
cars array:

151
www.Sohrabpoor.com

Example
var cars = ["BMW", "Volvo", "Saab", "Ford"];
var i = 0;
var text = "";

for (;cars[i];) {
text += cars[i] + "<br>";
i++;
}

Try it Yourself »

The loop in this example uses a while loop to collect the car names from the
cars array:

Example
var cars = ["BMW", "Volvo", "Saab", "Ford"];
var i = 0;
var text = "";

while (cars[i]) {
text += cars[i] + "<br>";
i++;
}

Try it Yourself »

JavaScript Break and Continue


The break statement "jumps out" of a loop.

The continue statement "jumps over" one iteration in the loop.

The Break Statement


You have already seen the break statement used in an earlier chapter of this
tutorial. It was used to "jump out" of a switch() statement.

The break statement can also be used to jump out of a loop.

152
www.Sohrabpoor.com

The break statement breaks the loop and continues executing the code
after the loop (if any):

Example
for (i = 0; i < 10; i++) {
if (i === 3) { break; }
text += "The number is " + i + "<br>";
}

Try it Yourself »

The Continue Statement


The continue statement breaks one iteration (in the loop), if a specified
condition occurs, and continues with the next iteration in the loop.

This example skips the value of 3:

Example
for (i = 0; i < 10; i++) {
if (i === 3) { continue; }
text += "The number is " + i + "<br>";
}

Try it Yourself »

JavaScript Labels
To label JavaScript statements you precede the statements with a label name
and a colon:

label:
statements

The break and the continue statements are the only JavaScript statements
that can "jump out of" a code block.

Syntax:

153
www.Sohrabpoor.com

break labelname;

continue labelname;

The continue statement (with or without a label reference) can only be used
to skip one loop iteration.

The break statement, without a label reference, can only be used to jump
out of a loop or a switch.

With a label reference, the break statement can be used to jump out of any
code block:

Example
var cars = ["BMW", "Volvo", "Saab", "Ford"];
list: {
text += cars[0] + "<br>";
text += cars[1] + "<br>";
text += cars[2] + "<br>";
break list;
text += cars[3] + "<br>";
text += cars[4] + "<br>";
text += cars[5] + "<br>";
}

Try it Yourself »

A code block is a block of code between { and }.

JavaScript Type Conversion


Number() converts to a Number, String() converts to a String, Boolean()
converts to a Boolean.

JavaScript Data Types


In JavaScript there are 5 different data types that can contain values:

 string
 number
 boolean

154
www.Sohrabpoor.com

 object
 function

There are 3 types of objects:

 Object
 Date
 Array

And 2 data types that cannot contain values:

 null
 undefined

The typeof Operator


You can use the typeof operator to find the data type of a JavaScript
variable.

Example
typeof "John" // Returns "string"
typeof 3.14 // Returns "number"
typeof NaN // Returns "number"
typeof false // Returns "boolean"
typeof [1,2,3,4] // Returns "object"
typeof {name:'John', age:34} // Returns "object"
typeof new Date() // Returns "object"
typeof function () {} // Returns "function"
typeof myCar // Returns "undefined" *
typeof null // Returns "object"

Try it Yourself »

Please observe:

 The data type of NaN is number


 The data type of an array is object
 The data type of a date is object
 The data type of null is object
 The data type of an undefined variable is undefined *
 The data type of a variable that has not been assigned a value is
also undefined *

You cannot use typeof to determine if a JavaScript object is an array (or a


date).

155
www.Sohrabpoor.com

The Data Type of typeof


The typeof operator is not a variable. It is an operator. Operators ( + - * / )
do not have any data type.

But, the typeof operator always returns a string containing the type of the
operand.

The constructor Property


The constructor property returns the constructor function for all JavaScript
variables.

Example
"John".constructor // Returns "function String() {
[native code] }"
(3.14).constructor // Returns "function Number() {
[native code] }"
false.constructor // Returns "function Boolean() {
[native code] }"
[1,2,3,4].constructor // Returns "function Array() {
[native code] }"
{name:'John', age:34}.constructor // Returns" function Object() {
[native code] }"
new Date().constructor // Returns "function Date() {
[native code] }"
function () {}.constructor // Returns "function Function(){
[native code] }"

Try it Yourself »

You can check the constructor property to find out if an object is an Array
(contains the word "Array"):

Example
function isArray(myArray) {
return myArray.constructor.toString().indexOf("Array") > -1;
}

Try it Yourself »

You can check the constructor property to find out if an object is a Date
(contains the word "Date"):

156
www.Sohrabpoor.com

Example
function isDate(myDate) {
return myDate.constructor.toString().indexOf("Date") > -1;
}

Try it Yourself »

JavaScript Type Conversion


JavaScript variables can be converted to a new variable and another data
type:

 By the use of a JavaScript function


 Automatically by JavaScript itself

Converting Numbers to Strings


The global method String() can convert numbers to strings.

It can be used on any type of numbers, literals, variables, or expressions:

Example
String(x) // returns a string from a number variable x
String(123) // returns a string from a number literal 123
String(100 + 23) // returns a string from a number from an expression

Try it Yourself »

The Number method toString() does the same.

Example
x.toString()
(123).toString()
(100 + 23).toString()

Try it Yourself »

In the chapter Number Methods, you will find more methods that can be
used to convert numbers to strings:

157
www.Sohrabpoor.com

Method Description

toExponential() Returns a string, with a number rounded and written using exponential
notation.

toFixed() Returns a string, with a number rounded and written with a specified number
of decimals.

toPrecision() Returns a string, with a number written with a specified length

Converting Booleans to Strings


The global method String() can convert booleans to strings.

String(false) // returns "false"


String(true) // returns "true"

The Boolean method toString() does the same.

false.toString() // returns "false"


true.toString() // returns "true"

Converting Dates to Strings


The global method String() can convert dates to strings.

String(Date()) // returns "Thu Jul 17 2014 15:38:19 GMT+0200 (W.


Europe Daylight Time)"

The Date method toString() does the same.

Example
Date().toString() // returns "Thu Jul 17 2014 15:38:19 GMT+0200 (W.
Europe Daylight Time)"

158
www.Sohrabpoor.com

In the chapter Date Methods, you will find more methods that can be used to
convert dates to strings:

Method Description

getDate() Get the day as a number (1-31)

getDay() Get the weekday a number (0-6)

getFullYear() Get the four digit year (yyyy)

getHours() Get the hour (0-23)

getMilliseconds() Get the milliseconds (0-999)

getMinutes() Get the minutes (0-59)

getMonth() Get the month (0-11)

getSeconds() Get the seconds (0-59)

getTime() Get the time (milliseconds since January 1, 1970)

Converting Strings to Numbers


The global method Number() can convert strings to numbers.

Strings containing numbers (like "3.14") convert to numbers (like 3.14).

159
www.Sohrabpoor.com

Empty strings convert to 0.

Anything else converts to NaN (Not a number).

Number("3.14") // returns 3.14


Number(" ") // returns 0
Number("") // returns 0
Number("99 88") // returns NaN

In the chapter Number Methods, you will find more methods that can be
used to convert strings to numbers:

Method Description

parseFloat() Parses a string and returns a floating point number

parseInt() Parses a string and returns an integer

The Unary + Operator


The unary + operator can be used to convert a variable to a number:

Example
var y = "5"; // y is a string
var x = + y; // x is a number

Try it Yourself »

If the variable cannot be converted, it will still become a number, but with
the value NaN (Not a number):

Example
var y = "John"; // y is a string
var x = + y; // x is a number (NaN)

Try it Yourself »

160
www.Sohrabpoor.com

Converting Booleans to Numbers


The global method Number() can also convert booleans to numbers.

Number(false) // returns 0
Number(true) // returns 1

Converting Dates to Numbers


The global method Number() can be used to convert dates to numbers.

d = new Date();
Number(d) // returns 1404568027739

The date method getTime() does the same.

d = new Date();
d.getTime() // returns 1404568027739

Automatic Type Conversion


When JavaScript tries to operate on a "wrong" data type, it will try to convert
the value to a "right" type.

The result is not always what you expect:

5 + null // returns 5 because null is converted to 0


"5" + null // returns "5null" because null is converted to "null"
"5" + 2 // returns 52 because 2 is converted to "2"
"5" - 2 // returns 3 because "5" is converted to 5
"5" * "2" // returns 10 because "5" and "2" are converted to 5
and 2

Try it Yourself »

161
www.Sohrabpoor.com

Automatic String Conversion


JavaScript automatically calls the variable's toString() function when you try
to "output" an object or a variable:

document.getElementById("demo").innerHTML = myVar;

// if myVar = {name:"Fjohn"} // toString converts to "[object Object]"


// if myVar = [1,2,3,4] // toString converts to "1,2,3,4"
// if myVar = new Date() // toString converts to "Fri Jul 18 2014
09:08:55 GMT+0200"

Numbers and booleans are also converted, but this is not very visible:

// if myVar = 123 // toString converts to "123"


// if myVar = true // toString converts to "true"
// if myVar = false // toString converts to "false"

JavaScript Type Conversion Table


This table shows the result of converting different JavaScript values to
Number, String, and Boolean:

Original Converted Converted Converted Try it


Value to Number to String to Boolean

false 0 "false" false Try it »

true 1 "true" true Try it »

0 0 "0" false Try it »

1 1 "1" true Try it »

162
www.Sohrabpoor.com

"0" 0 "0" true Try it »

"1" 1 "1" true Try it »

NaN NaN "NaN" false Try it »

Infinity Infinity "Infinity" true Try it »

-Infinity -Infinity "-Infinity" true Try it »

"" 0 "" false Try it »

"20" 20 "20" true Try it »

"twenty" NaN "twenty" true Try it »

[] 0 "" true Try it »

[20] 20 "20" true Try it »

[10,20] NaN "10,20" true Try it »

["twenty"] NaN "twenty" true Try it »

["ten","twenty"] NaN "ten,twenty" true Try it »

163
www.Sohrabpoor.com

function(){} NaN "function(){}" true Try it »

{} NaN "[object Object]" true Try it »

null 0 "null" false Try it »

undefined NaN "undefined" false Try it »

Values in quotes indicate string values.

Red values indicate values (some) programmers might not expect.

JavaScript Regular Expressions


A regular expression is a sequence of characters that forms a search
pattern.

The search pattern can be used for text search and text replace
operations.

What Is a Regular Expression?


A regular expression is a sequence of characters that forms a search
pattern.

When you search for data in a text, you can use this search pattern to
describe what you are searching for.

A regular expression can be a single character, or a more complicated


pattern.

Regular expressions can be used to perform all types of text


search and text replace operations.

164
www.Sohrabpoor.com

Syntax
/pattern/modifiers;

Example
var patt = /w3schools/i;

Example explained:

/w3schools/i is a regular expression.

w3schools is a pattern (to be used in a search).

i is a modifier (modifies the search to be case-insensitive).

Using String Methods


In JavaScript, regular expressions are often used with the two string
methods: search() and replace().

The search() method uses an expression to search for a match, and


returns the position of the match.

The replace() method returns a modified string where the pattern is


replaced.

Using String search() With a Regular


Expression
Example
Use a regular expression to do a case-insensitive search for "w3schools" in a
string:

var str = "Visit W3Schools";


var n = str.search(/w3schools/i);

The result in n will be: 6

Try it Yourself »

165
www.Sohrabpoor.com

Using String search() With String


The search method will also accept a string as search argument. The string
argument will be converted to a regular expression:

Example
Use a string to do a search for "W3schools" in a string:

var str = "Visit W3Schools!";


var n = str.search("W3Schools");

Try it Yourself »

Use String replace() With a Regular


Expression
Example
Use a case insensitive regular expression to replace Microsoft with
W3Schools in a string:

var str = "Visit Microsoft!";


var res = str.replace(/microsoft/i, "W3Schools");

The result in res will be:

Visit W3Schools!

Try it Yourself »

Using String replace() With a String


The replace() method will also accept a string as search argument:

var str = "Visit Microsoft!";


var res = str.replace("Microsoft", "W3Schools");

Try it Yourself »

166
www.Sohrabpoor.com

Did You Notice?


Regular expression arguments (instead of string arguments) can be used in
the methods above.
Regular expressions can make your search much more powerful (case
insensitive for example).

Regular Expression Modifiers


Modifiers can be used to perform case-insensitive more global searches:

Modifier Description

i Perform case-insensitive matching

g Perform a global match (find all matches rather than stopping after the first
match)

m Perform multiline matching

Regular Expression Patterns


Brackets are used to find a range of characters:

Expression Description

[abc] Find any of the characters between the brackets

[0-9] Find any of the digits between the brackets

167
www.Sohrabpoor.com

(x|y) Find any of the alternatives separated with |

Metacharacters are characters with a special meaning:

Metacharacter Description

\d Find a digit

\s Find a whitespace character

\b Find a match at the beginning or at the end of a word

\uxxxx Find the Unicode character specified by the hexadecimal number xxxx

Quantifiers define quantities:

Quantifier Description

n+ Matches any string that contains at least one n

n* Matches any string that contains zero or more occurrences of n

n? Matches any string that contains zero or one occurrences of n

168
www.Sohrabpoor.com

Using the RegExp Object


In JavaScript, the RegExp object is a regular expression object with
predefined properties and methods.

Using test()
The test() method is a RegExp expression method.

It searches a string for a pattern, and returns true or false, depending on the
result.

The following example searches a string for the character "e":

Example
var patt = /e/;
patt.test("The best things in life are free!");

Since there is an "e" in the string, the output of the code above will be:

true

Try it Yourself »

You don't have to put the regular expression in a variable first. The two lines
above can be shortened to one:

/e/.test("The best things in life are free!");

Using exec()
The exec() method is a RegExp expression method.

It searches a string for a specified pattern, and returns the found text.

If no match is found, it returns null.

The following example searches a string for the character "e":

169
www.Sohrabpoor.com

Example 1
/e/.exec("The best things in life are free!");

Since there is an "e" in the string, the output of the code above will be:

Try it Yourself »

Complete RegExp Reference


For a complete reference, go to our Complete JavaScript RegExp Reference.

The reference contains descriptions and examples of all RegExp properties


and methods.

JavaScript Errors - Throw and Try to


Catch

The try statement lets you test a block of code for errors.

The catch statement lets you handle the error.

The throw statement lets you create custom errors.

The finally statement lets you execute code, after try and catch,
regardless of the result.

Errors Will Happen!


When executing JavaScript code, different errors can occur.

Errors can be coding errors made by the programmer, errors due to wrong
input, and other unforeseeable things.

170
www.Sohrabpoor.com

Example
In this example we have written alert as adddlert to deliberately produce an
error:

<!DOCTYPE html>
<html>
<body>

<p id="demo"></p>

<script>
try {
adddlert("Welcome guest!");
}
catch(err) {
document.getElementById("demo").innerHTML = err.message;
}
</script>

</body>
</html>

Try it Yourself »

The catch block catches addlert as an error, and executes code to handle
it.

JavaScript try and catch


The try statement allows you to define a block of code to be tested for errors
while it is being executed.

The catch statement allows you to define a block of code to be executed, if


an error occurs in the try block.

The JavaScript statements try and catch come in pairs:

try {
Block of code to try
}
catch(err) {
Block of code to handle errors
}

171
www.Sohrabpoor.com

JavaScript can Raise Errors


When an error occurs, JavaScript will normally stop, and generate an error
message.

The technical term for this is: JavaScript will raise (or throw) an
exception.

The throw Statement


The throw statement allows you to create a custom error.

Technically you can raise (throw) an exception.

The exception can be a JavaScript String, a Number, a Boolean or an Object:

throw "Too big"; // throw a text


throw 500; // throw a number

If you use throw together with try and catch, you can control program flow
and generate custom error messages.

Input Validation Example


This example examines input. If the value is wrong, an exception (err) is
thrown.

The exception (err) is caught by the catch statement and a custom error
message is displayed:

<!DOCTYPE html>
<html>
<body>

<p>Please input a number between 5 and 10:</p>

<input id="demo" type="text">


<button type="button" onclick="myFunction()">Test Input</button>
<p id="message"></p>

<script>
function myFunction() {

172
www.Sohrabpoor.com

var message, x;
message = document.getElementById("message");
message.innerHTML = "";
x = document.getElementById("demo").value;
try {
if(x == "") throw "empty";
if(isNaN(x)) throw "not a number";
x = Number(x);
if(x < 5) throw "too low";
if(x > 10) throw "too high";
}
catch(err) {
message.innerHTML = "Input is " + err;
}
}
</script>

</body>
</html>

Try it Yourself »

HTML Validation
The code above is just an example.

Modern browsers will often use a combination of JavaScript and built-in HTML
validation, using predefined validation rules defined in HTML attributes:

<input id="demo" type="number" min="5" max="10" step="1"

You can read more about forms validation in a later chapter of this tutorial.

The finally Statement


The finally statement lets you execute code, after try and catch, regardless
of the result:

try {
Block of code to try
}
catch(err) {
Block of code to handle errors

173
www.Sohrabpoor.com

}
finally {
Block of code to be executed regardless of the try / catch result
}

Example
function myFunction() {
var message, x;
message = document.getElementById("message");
message.innerHTML = "";
x = document.getElementById("demo").value;
try {
if(x == "") throw "is empty";
if(isNaN(x)) throw "is not a number";
x = Number(x);
if(x > 10) throw "is too high";
if(x < 5) throw "is too low";
}
catch(err) {
message.innerHTML = "Error: " + err + ".";
}
finally {
document.getElementById("demo").value = "";
}
}

Try it Yourself »

JavaScript Debugging
It is easy to get lost writing JavaScript code without a debugger.

JavaScript Debugging
It is difficult to write JavaScript code without a debugger.

Your code might contain syntax errors, or logical errors, that are difficult to
diagnose.

Often, when JavaScript code contains errors, nothing will happen. There are
no error messages, and you will get no indications where to search for
errors.

174
www.Sohrabpoor.com

Normally, errors will happen, every time you try to write some new
JavaScript code.

JavaScript Debuggers
Searching for errors in programming code is called code debugging.

Debugging is not easy. But fortunately, all modern browsers have a built-in
debugger.

Built-in debuggers can be turned on and off, forcing errors to be reported to


the user.

With a debugger, you can also set breakpoints (places where code execution
can be stopped), and examine variables while the code is executing.

Normally, otherwise follow the steps at the bottom of this page, you activate
debugging in your browser with the F12 key, and select "Console" in the
debugger menu.

The console.log() Method


If your browser supports debugging, you can use console.log() to display
JavaScript values in the debugger window:

Example
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<script>
a = 5;
b = 6;
c = a + b;
console.log(c);
</script>
</body>
</html>

Try it Yourself »

175
www.Sohrabpoor.com

Setting Breakpoints
In the debugger window, you can set breakpoints in the JavaScript code.

At each breakpoint, JavaScript will stop executing, and let you examine
JavaScript values.

After examining values, you can resume the execution of code (typically with
a play button).

The debugger Keyword


The debugger keyword stops the execution of JavaScript, and calls (if
available) the debugging function.

This has the same function as setting a breakpoint in the debugger.

If no debugging is available, the debugger statement has no effect.

With the debugger turned on, this code will stop executing before it executes
the third line.

Example
var x = 15 * 5;
debugger;
document.getElementbyId("demo").innerHTML = x;

Try it Yourself »

Major Browsers' Debugging Tools


Normally, you activate debugging in your browser with F12, and select
"Console" in the debugger menu.

Otherwise follow these steps:

176
www.Sohrabpoor.com

Chrome
 Open the browser.
 From the menu, select tools.
 From tools, choose developer tools.
 Finally, select Console.

Firefox Firebug
 Open the browser.
 Go to the web page:
http://www.getfirebug.com
 Follow the instructions how to:
install Firebug

Internet Explorer
 Open the browser.
 From the menu, select tools.
 From tools, choose developer tools.
 Finally, select Console.

Opera
 Open the browser.
 Go to the webpage:
http://dev.opera.com
 Follow the instructions how to:
add a Developer Console button to your toolbar.

Safari Firebug
 Open the browser.
 Go to the webpage:
http://extensions.apple.com
 Follow the instructions how to:
install Firebug Lite.

Safari Develop Menu


 Go to Safari, Preferences, Advanced in the main menu.
 Check "Enable Show Develop menu in menu bar".

177
www.Sohrabpoor.com

 When the new option "Develop" appears in the menu:


Choose "Show Error Console".

Did You Know?


Debugging is the process of testing, finding, and reducing bugs (errors) in
computer programs.
The first known computer bug was a real bug (an insect) stuck in the
electronics.

JavaScript Hoisting
Hoisting is JavaScript's default behavior of moving declarations to the top.

JavaScript Declarations are Hoisted


In JavaScript, a variable can be declared after it has been used.

In other words; a variable can be used before it has been declared.

Example 1 gives the same result as Example 2:

Example 1
x = 5; // Assign 5 to x

elem = document.getElementById("demo"); // Find an element


elem.innerHTML = x; // Display x in the element

var x; // Declare x

Try it Yourself »

Example 2
var x; // Declare x
x = 5; // Assign 5 to x

elem = document.getElementById("demo"); // Find an element


elem.innerHTML = x; // Display x in the element
Try it Yourself »

178
www.Sohrabpoor.com

To understand this, you have to understand the term "hoisting".

Hoisting is JavaScript's default behavior of moving all declarations to the top


of the current scope (to the top of the current script or the current function).

JavaScript Initializations are Not Hoisted


JavaScript only hoists declarations, not initializations.

Example 1 does not give the same result as Example 2:

Example 1
var x = 5; // Initialize x
var y = 7; // Initialize y

elem = document.getElementById("demo"); // Find an element


elem.innerHTML = x + " " + y; // Display x and y

Try it Yourself »

Example 2
var x = 5; // Initialize x

elem = document.getElementById("demo"); // Find an element


elem.innerHTML = x + " " + y; // Display x and y

var y = 7; // Initialize y

Try it Yourself »

Does it make sense that y is undefined in the last example?

This is because only the declaration (var y), not the initialization (=7) is
hoisted to the top.

Because of hoisting, y has been declared before it is used, but because


initializations are not hoisted, the value of y is undefined.

Example 2 is the same as writing:

179
www.Sohrabpoor.com

Example
var x = 5; // Initialize x
var y; // Declare y

elem = document.getElementById("demo"); // Find an element


elem.innerHTML = x + " " + y; // Display x and y

y = 7; // Assign 7 to y

Try it Yourself »

Declare Your Variables At the Top !


Hoisting is (to many developers) an unknown or overlooked behavior of
JavaScript.

If a developer doesn't understand hoisting, programs may contain bugs


(errors).

To avoid bugs, always declare all variables at the beginning of every scope.

Since this is how JavaScript interprets the code, it is always a good rule.

JavaScript in strict mode does not allow variables to be used if they are not
declared.
Study "use strict" in the next chapter.

JavaScript Use Strict


"use strict"; Defines that JavaScript code should be executed in "strict
mode".

The "use strict" Directive


The "use strict" directive is new in JavaScript 1.8.5 (ECMAScript version 5).

It is not a statement, but a literal expression, ignored by earlier versions of


JavaScript.

180
www.Sohrabpoor.com

The purpose of "use strict" is to indicate that the code should be executed in
"strict mode".

With strict mode, you can not, for example, use undeclared variables.

Strict mode is supported in:


IE from version 10. Firefox from version 4.
Chrome from version 13. Safari from version 5.1.
Opera from version 12.

Declaring Strict Mode


Strict mode is declared by adding "use strict"; to the beginning of a script or
a function.

Declared at the beginning of a script, it has global scope (all code in the
script will execute in strict mode):

Example
"use strict";
x = 3.14; // This will cause an error (x is not defined)

Try it Yourself »

Example
"use strict";
myFunction();

function myFunction() {
y = 3.14; // This will also cause an error (y is not defined)
}

Try it Yourself »

Declared inside a function, it has local scope (only the code inside the
function is in strict mode):

x = 3.14; // This will not cause an error.


myFunction();

function myFunction() {
"use strict";
y = 3.14; // This will cause an error (y is not defined)

181
www.Sohrabpoor.com

Try it Yourself »

The "use strict"; Syntax


The syntax, for declaring strict mode, was designed to be compatible with
older versions of JavaScript.

Compiling a numeric literal (4 + 5;) or a string literal ("John Doe";) in a


JavaScript program has no side effects. It simply compiles to a non existing
variable and dies.

So "use strict"; only matters to new compilers that "understand" the


meaning of it.

Why Strict Mode?


Strict mode makes it easier to write "secure" JavaScript.

Strict mode changes previously accepted "bad syntax" into real errors.

As an example, in normal JavaScript, mistyping a variable name creates a


new global variable. In strict mode, this will throw an error, making it
impossible to accidentally create a global variable.

In normal JavaScript, a developer will not receive any error feedback


assigning values to non-writable properties.

In strict mode, any assignment to a non-writable property, a getter-only


property, a non-existing property, a non-existing variable, or a non-existing
object, will throw an error.

Not Allowed in Strict Mode


Using a variable, without declaring it, is not allowed:

"use strict";
x = 3.14; // This will cause an error (x is not defined)

182
www.Sohrabpoor.com

Try it Yourself »

Objects are variables too.

Using an object, without declaring it, is not allowed:

"use strict";
x = {p1:10, p2:20}; // This will cause an error (x is not defined)

Try it Yourself »

Deleting a variable (or object) is not allowed.

"use strict";
var x = 3.14;
delete x; // This will cause an error

Try it Yourself »

Deleting a function is not allowed.

"use strict";
function x(p1, p2) {};
delete x; // This will cause an error

Try it Yourself »

Duplicating a parameter name is not allowed:

"use strict";
function x(p1, p1) {}; // This will cause an error

Try it Yourself »

Octal numeric literals are not allowed:

"use strict";
var x = 010; // This will cause an error

Try it Yourself »

Escape characters are not allowed:

"use strict";
var x = \010; // This will cause an error

Try it Yourself »

183
www.Sohrabpoor.com

Writing to a read-only property is not allowed:

"use strict";
var obj = {};
Object.defineProperty(obj, "x", {value:0, writable:false});

obj.x = 3.14; // This will cause an error

Try it Yourself »

Writing to a get-only property is not allowed:

"use strict";
var obj = {get x() {return 0} };

obj.x = 3.14; // This will cause an error

Try it Yourself »

Deleting an undeletable property is not allowed:

"use strict";
delete Object.prototype; // This will cause an error

Try it Yourself »

The string "eval" cannot be used as a variable:

"use strict";
var eval = 3.14; // This will cause an error

Try it Yourself »

The string "arguments" cannot be used as a variable:

"use strict";
var arguments = 3.14; // This will cause an error

Try it Yourself »

The with statement is not allowed:

"use strict";
with (Math){x = cos(2)}; // This will cause an error

Try it Yourself »

For security reasons, eval() is not allowed to create variables in the scope
from which it was called:

184
www.Sohrabpoor.com

"use strict";
eval ("var x = 2");
alert (x); // This will cause an error

Try it Yourself »

In function calls like f(), the this value was the global object. In strict mode,
it is now undefined.

Future Proof!
Future reserved keywords are not allowed in strict mode. These are:

 implements
 interface
 let
 package
 private
 protected
 public
 static
 yield

"use strict";
var public = 1500; // This will cause an error

Try it Yourself »

Watch Out!
The "use strict" directive is only recognized at the beginning of a script or a
function.

JavaScript Style Guide and Coding


Conventions
Always use the same coding conventions for all your JavaScript projects.

185
www.Sohrabpoor.com

JavaScript Coding Conventions


Coding conventions are style guidelines for programming. They typically
cover:

 Naming and declaration rules for variables and functions.


 Rules for the use of white space, indentation, and comments.
 Programming practices and principles

Coding conventions secure quality:

 Improves code readability


 Make code maintenance easier

Coding conventions can be documented rules for teams to follow, or just be


your individual coding practice.

This page describes the general JavaScript code conventions used by


W3Schools.
You should also read the next chapter "Best Practices", and learn how to
avoid coding pitfalls.

Variable Names
At W3schools we use camelCase for identifier names (variables and
functions).

All names start with a letter.

At the bottom of this page, you will find a wider discussion about naming
rules.

firstName = "John";
lastName = "Doe";

price = 19.90;
tax = 0.20;

fullPrice = price + (price * tax);

186
www.Sohrabpoor.com

Spaces Around Operators


Always put spaces around operators ( = + - * / ), and after commas:

Examples:
var x = y + z;
var values = ["Volvo", "Saab", "Fiat"];

Code Indentation
Always use 4 spaces for indentation of code blocks:

Functions:
function toCelsius(fahrenheit) {
return (5 / 9) * (fahrenheit - 32);
}

Do not use tabs (tabulators) for indentation. Different editors interpret tabs
differently.

Statement Rules
General rules for simple statements:

 Always end a simple statement with a semicolon.

Examples:
var values = ["Volvo", "Saab", "Fiat"];

var person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};

General rules for complex (compound) statements:

187
www.Sohrabpoor.com

 Put the opening bracket at the end of the first line.


 Use one space before the opening bracket.
 Put the closing bracket on a new line, without leading spaces.
 Do not end a complex statement with a semicolon.

Functions:
function toCelsius(fahrenheit) {
return (5 / 9) * (fahrenheit - 32);
}

Loops:
for (i = 0; i < 5; i++) {
x += i;
}

Conditionals:
if (time < 20) {
greeting = "Good day";
} else {
greeting = "Good evening";
}

Object Rules
General rules for object definitions:

 Place the opening bracket on the same line as the object name.
 Use colon plus one space between each property and its value.
 Use quotes around string values, not around numeric values.
 Do not add a comma after the last property-value pair.
 Place the closing bracket on a new line, without leading spaces.
 Always end an object definition with a semicolon.

Example
var person = {
firstName: "John",
lastName: "Doe",
age: 50,

188
www.Sohrabpoor.com

eyeColor: "blue"
};

Short objects can be written compressed, on one line, using spaces only
between properties, like this:

var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};

Line Length < 80


For readability, avoid lines longer than 80 characters.

If a JavaScript statement does not fit on one line, the best place to break it,
is after an operator or a comma.

Example
document.getElementById("demo").innerHTML =
"Hello Dolly.";

Try it Yourself »

Naming Conventions
Always use the same naming convention for all your code. For example:

 Variable and function names written as camelCase


 Global variables written in UPPERCASE (We don't, but it's quite
common)
 Constants (like PI) written in UPPERCASE

Should you use hyp-hens, camelCase, or under_scores in variable


names?

This is a question programmers often discuss. The answer depends on who


you ask:

Hyphens in HTML and CSS:

HTML5 attributes can start with data- (data-quantity, data-price).

CSS uses hyphens in property-names (font-size).

189
www.Sohrabpoor.com

Hyphens can be mistaken as subtraction attempts. Hyphens are not allowed


in JavaScript names.

Underscores:

Many programmers prefer to use underscores (date_of_birth), especially in


SQL databases.

Underscores are often used in PHP documentation.

PascalCase:

PascalCase is often preferred by C programmers.

camelCase:

camelCase is used by JavaScript itself, by jQuery, and other JavaScript


libraries.

Do not start names with a $ sign. It will put you in conflict with many
JavaScript library names.

Loading JavaScript in HTML


Use simple syntax for loading external scripts (the type attribute is not
necessary):

<script src="myscript.js"></script>

Accessing HTML Elements


A consequence of using "untidy" HTML styles, might result in JavaScript
errors.

These two JavaScript statements will produce different results:

var obj = getElementById("Demo")

var obj = getElementById("demo")

If possible, use the same naming convention (as JavaScript) in HTML.

Visit the HTML Style Guide.

190
www.Sohrabpoor.com

File Extensions
HTML files should have a .html extension (not .htm).

CSS files should have a .css extension.

JavaScript files should have a .js extension.

Use Lower Case File Names


Most web servers (Apache, Unix) are case sensitive about file names:

london.jpg cannot be accessed as London.jpg.

Other web servers (Microsoft, IIS) are not case sensitive:

london.jpg can be accessed as London.jpg or london.jpg.

If you use a mix of upper and lower case, you have to be extremely
consistent.

If you move from a case insensitive, to a case sensitive server, even small
errors can break your web site.

To avoid these problems, always use lower case file names (if possible).

Performance
Coding conventions are not used by computers. Most rules have little impact
on the execution of programs.

Indentation and extra spaces are not significant in small scripts.

For code in development, readability should be preferred. Larger production


scripts should be minified.

191
www.Sohrabpoor.com

JavaScript Best Practices


Avoid global variables, avoid new, avoid ==, avoid eval()

Avoid Global Variables


Minimize the use of global variables.

This includes all data types, objects, and functions.

Global variables and functions can be overwritten by other scripts.

Use local variables instead, and learn how to use closures.

Always Declare Local Variables


All variables used in a function should be declared as local variables.

Local variables must be declared with the var keyword, otherwise they will
become global variables.

Strict mode does not allow undeclared variables.

Declarations on Top
It is a good coding practice to put all declarations at the top of each script or
function.

This will:

 Give cleaner code


 Provide a single place to look for local variables
 Make it easier to avoid unwanted (implied) global variables
 Reduce the possibility of unwanted re-declarations

// Declare at the beginning


var firstName, lastName, price, discount, fullPrice;

192
www.Sohrabpoor.com

// Use later
firstName = "John";
lastName = "Doe";

price = 19.90;
discount = 0.10;

fullPrice = price * 100 / discount;

This also goes for loop variables:

// Declare at the beginning


var i;

// Use later
for (i = 0; i < 5; i++) {

By default, JavaScript moves all declarations to the top (JavaScript hoisting).

Initialize Variables
It is a good coding practice to initialize variables when you declare them.

This will:

 Give cleaner code


 Provide a single place to initialize variables
 Avoid undefined values

// Declare and initiate at the beginning


var firstName = "",
lastName = "",
price = 0,
discount = 0,
fullPrice = 0,
myArray = [],
myObject = {};

Initializing variables provides an idea of the intended use (and intended data
type).

193
www.Sohrabpoor.com

Never Declare Number, String, or Boolean


Objects
Always treat numbers, strings, or booleans as primitive values. Not as
objects.

Declaring these types as objects, slows down execution speed, and produces
nasty side effects:

Example
var x = "John";
var y = new String("John");
(x === y) // is false because x is a string and y is an object.

Try it Yourself »

Or even worse:

Example
var x = new String("John");
var y = new String("John");
(x == y) // is false because you cannot compare objects.

Try it Yourself »

Don't Use new Object()


 Use {} instead of new Object()
 Use "" instead of new String()
 Use 0 instead of new Number()
 Use false instead of new Boolean()
 Use [] instead of new Array()
 Use /()/ instead of new RegExp()
 Use function (){} instead of new Function()

Example
var x1 = {}; // new object
var x2 = ""; // new primitive string
var x3 = 0; // new primitive number
var x4 = false; // new primitive boolean
var x5 = []; // new array object

194
www.Sohrabpoor.com

var x6 = /()/; // new regexp object


var x7 = function(){}; // new function object

Try it Yourself »

Beware of Automatic Type Conversions


Beware that numbers can accidentally be converted to strings or NaN (Not a
Number).

JavaScript is loosely typed. A variable can contain different data types, and a
variable can change its data type:

Example
var x = "Hello"; // typeof x is a string
x = 5; // changes typeof x to a number

Try it Yourself »

When doing mathematical operations, JavaScript can convert numbers to


strings:

Example
var x = 5 + 7; // x.valueOf() is 12, typeof x is a number
var x = 5 + "7"; // x.valueOf() is 57, typeof x is a string
var x = "5" + 7; // x.valueOf() is 57, typeof x is a string
var x = 5 - 7; // x.valueOf() is -2, typeof x is a number
var x = 5 - "7"; // x.valueOf() is -2, typeof x is a number
var x = "5" - 7; // x.valueOf() is -2, typeof x is a number
var x = 5 - "x"; // x.valueOf() is NaN, typeof x is a number

Try it Yourself »

Subtracting a string from a string, does not generate an error but returns
NaN (Not a Number):

Example
"Hello" - "Dolly" // returns NaN

Try it Yourself »

195
www.Sohrabpoor.com

Use === Comparison


The == comparison operator always converts (to matching types) before
comparison.

The === operator forces comparison of values and type:

Example
0 == ""; // true
1 == "1"; // true
1 == true; // true

0 === ""; // false


1 === "1"; // false
1 === true; // false

Try it Yourself »

Use Parameter Defaults


If a function is called with a missing argument, the value of the missing
argument is set to undefined.

Undefined values can break your code. It is a good habit to assign default
values to arguments.

Example
function myFunction(x, y) {
if (y === undefined) {
y = 0;
}
}

Try it Yourself »

Read more about function parameters and arguments at Function Parameters

196
www.Sohrabpoor.com

End Your Switches with Defaults


Always end your switch statements with a default. Even if you think there is
no need for it.

Example
switch (new Date().getDay()) {
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
break;
default:
day = "Unknown";
}

Try it Yourself »

Avoid Using eval()


The eval() function is used to run text as code. In almost all cases, it should
not be necessary to use it.

Because it allows arbitrary code to be run, it also represents a security


problem.

197
www.Sohrabpoor.com

JavaScript Common Mistakes


This chapter points out some common JavaScript mistakes.

Accidentally Using the Assignment Operator


JavaScript programs may generate unexpected results if a programmer
accidentally uses an assignment operator (=), instead of a comparison
operator (==) in an if statement.

This if statement returns false (as expected) because x is not equal to 10:

var x = 0;
if (x == 10)

Try it Yourself »

This if statement returns true (maybe not as expected), because 10 is true:

var x = 0;
if (x = 10)

Try it Yourself »

This if statement returns false (maybe not as expected), because 0 is false:

var x = 0;
if (x = 0)

Try it Yourself »

An assignment always returns the value of the assignment.

Expecting Loose Comparison


In regular comparison, data type does not matter. This if statement returns
true:

var x = 10;
var y = "10";
if (x == y)

Try it Yourself »

198
www.Sohrabpoor.com

In strict comparison, data type does matter. This if statement returns false:

var x = 10;
var y = "10";
if (x === y)

Try it Yourself »

It is a common mistake to forget that switch statements use strict


comparison:

This case switch will display an alert:

var x = 10;
switch(x) {
case 10: alert("Hello");
}

Try it Yourself »

This case switch will not display an alert:

var x = 10;
switch(x) {
case "10": alert("Hello");
}

Try it Yourself »

Confusing Addition & Concatenation


Addition is about adding numbers.

Concatenation is about adding strings.

In JavaScript both operations use the same + operator.

Because of this, adding a number as a number will produce a different result


from adding a number as a string:

var x = 10 + 5; // the result in x is 15


var x = 10 + "5"; // the result in x is "105"

Try it Yourself »

When adding two variables, it can be difficult to anticipate the result:

199
www.Sohrabpoor.com

var x = 10;
var y = 5;
var z = x + y; // the result in z is 15

var x = 10;
var y = "5";
var z = x + y; // the result in z is "105"

Try it Yourself »

Misunderstanding Floats
All numbers in JavaScript are stored as 64-bits Floating point
numbers (Floats).

All programming languages, including JavaScript, have difficulties with


precise floating point values:

var x = 0.1;
var y = 0.2;
var z = x + y // the result in z will not be 0.3

Try it Yourself »

To solve the problem above, it helps to multiply and divide:

Example
var z = (x * 10 + y * 10) / 10; // z will be 0.3

Try it Yourself »

Breaking a JavaScript String


JavaScript will allow you to break a statement into two lines:

Example 1
var x =
"Hello World!";

Try it Yourself »

But, breaking a statement in the middle of a string will not work:

200
www.Sohrabpoor.com

Example 2
var x = "Hello
World!";

Try it Yourself »

You must use a "backslash" if you must break a statement in a string:

Example 3
var x = "Hello \
World!";

Try it Yourself »

Misplacing Semicolon
Because of a misplaced semicolon, this code block will execute regardless of
the value of x:

if (x == 19);
{
// code block
}

Try it Yourself »

Breaking a Return Statement


It is a default JavaScript behavior to close a statement automatically at the
end of a line.

Because of this, these two examples will return the same result:

Example 1
function myFunction(a) {
var power = 10
return a * power
}

Try it Yourself »

201
www.Sohrabpoor.com

Example 2
function myFunction(a) {
var power = 10;
return a * power;
}
Try it Yourself »

JavaScript will also allow you to break a statement into two lines.

Because of this, example 3 will also return the same result:

Example 3
function myFunction(a) {
var
power = 10;
return a * power;
}

Try it Yourself »

But, what will happen if you break the return statement in two lines like this:

Example 4
function myFunction(a) {
var
power = 10;
return
a * power;
}

Try it Yourself »

The function will return undefined!

Why? Because JavaScript thinks you meant:

Example 5
function myFunction(a) {
var
power = 10;
return;
a * power;
}

Try it Yourself »

202
www.Sohrabpoor.com

Explanation
If a statement is incomplete like:

var

JavaScript will try to complete the statement by reading the next line:

power = 10;

But since this statement is complete:

return

JavaScript will automatically close it like this:

return;

This happens because closing (ending) statements with semicolon is optional


in JavaScript.

JavaScript will close the return statement at the end of the line, because it is
a complete statement.

Never break a return statement.

Accessing Arrays with Named Indexes


Many programming languages support arrays with named indexes.

Arrays with named indexes are called associative arrays (or hashes).

JavaScript does not support arrays with named indexes.

In JavaScript, arrays use numbered indexes:

Example
var person = [];
person[0] = "John";
person[1] = "Doe";
person[2] = 46;
var x = person.length; // person.length will return 3
var y = person[0]; // person[0] will return "John"

Try it Yourself »

203
www.Sohrabpoor.com

In JavaScript, objects use named indexes.

If you use a named index, when accessing an array, JavaScript will redefine
the array to a standard object.

After the automatic redefinition, array methods and properties will produce
undefined or incorrect results:

Example:
var person = [];
person["firstName"] = "John";
person["lastName"] = "Doe";
person["age"] = 46;
var x = person.length; // person.length will return 0
var y = person[0]; // person[0] will return undefined

Try it Yourself »

Ending an Array Definition with a Comma


Incorrect:
points = [40, 100, 1, 5, 25, 10,];

Some JSON and JavaScript engines will fail, or behave unexpectedly.

Correct:
points = [40, 100, 1, 5, 25, 10];

Ending an Object Definition with a Comma


Incorrect:
person = {firstName:"John", lastName:"Doe", age:46,}

Some JSON and JavaScript engines will fail, or behave unexpectedly.

Correct:
person = {firstName:"John", lastName:"Doe", age:46}

204
www.Sohrabpoor.com

Undefined is Not Null


With JavaScript, null is for objects, undefined is for variables, properties,
and methods.

To be null, an object has to be defined, otherwise it will be undefined.

If you want to test if an object exists, this will throw an error if the object is
undefined:

Incorrect:
if (myObj !== null && typeof myObj !== "undefined")

Because of this, you must test typeof() first:

Correct:
if (typeof myObj !== "undefined" && myObj !== null)

Expecting Block Level Scope


JavaScript does not create a new scope for each code block.

It is true in many programming languages, but not true in JavaScript.

It is a common mistake, among new JavaScript developers, to believe that


this code returns undefined:

Example
for (var i = 0; i < 10; i++) {
// some code
}
return i;

Try it Yourself »

JavaScript Performance
How to speed up your JavaScript code.

205
www.Sohrabpoor.com

Reduce Activity in Loops


Loops are often used in programming.

Each statement in a loop, including the for statement, is executed for each
iteration of the loop.

Search for statements or assignments that can be placed outside the loop.

Bad Code:
var i;
for (i = 0; i < arr.length; i++) {

Better Code:
var i;
var l = arr.length;
for (i = 0; i < l; i++) {

The bad code accesses the length property of an array each time the loop is
iterated.

The better code accesses the length property outside the loop, and makes
the loop run faster.

Reduce DOM Access


Accessing the HTML DOM is very slow, compared to other JavaScript
statements.

If you expect to access a DOM element several times, access it once, and use
it as a local variable:

Example
var obj;
obj = document.getElementById("demo");
obj.innerHTML = "Hello";

Try it Yourself »

206
www.Sohrabpoor.com

Reduce DOM Size


Keep the number of elements in the HTML DOM small.

This will always improve page loading, and speed up rendering (page
display), especially on smaller devices.

Every attempt to search the DOM (like getElementsByTagName) will benefit


from a smaller DOM.

Avoid Unnecessary Variables


Don't create new variables if you don't plan to save values.

Often you can replace code like this:

var fullName = firstName + " " + lastName;


document.getElementById("demo").innerHTML = fullName;

With this:

document.getElementById("demo").innerHTML = firstName + " " + lastName

Delay JavaScript Loading


Putting your scripts at the bottom of the page body, lets the browser load the
page first.

While a script is downloading, the browser will not start any other downloads.
In addition all parsing and rendering activity might be blocked.

The HTTP specification defines that browsers should not download more than
two components in parallel.

An alternative is to use defer="true" in the script tag. The defer attribute


specifies that the script should be executed after the page has finished
parsing, but it only works for external scripts.

If possible, you can add your script to the page by code, after the page has
loaded:

207
www.Sohrabpoor.com

Example
<script>
window.onload = downScripts;

function downScripts() {
var element = document.createElement("script");
element.src = "myScript.js";
document.body.appendChild(element);
}
</script>

Avoid Using with


Avoid using the with keyword. It has a negative effect on speed. It also
clutters up JavaScript scopes.

The with keyword is not allowed in strict mode.

JavaScript Reserved Words


In JavaScript, some identifiers are reserved words and cannot be used as
variables or function names.

JavaScript Standards
ECMAScript 3 (ES3) was released in December 1999.

ECMAScript 4 (ES4) was abandoned.

ECMAScript 5 (ES5) was released in December 2009.

ECMAScript 6 (ES6) was released in June 2015, and is the latest official
version of JavaScript.

Time passes, and we are now beginning to see complete support for ES5/ES6
in all modern browsers.

208
www.Sohrabpoor.com

JavaScript Reserved Words


In JavaScript you cannot use these reserved words as variables, labels, or
function names:

abstract arguments boolean break byte

case catch char class* const

continue debugger default delete do

double else enum* eval export*

extends* false final finally float

for function goto if implements

import* in instanceof int interface

let long native new null

package private protected public return

short static super* switch synchronized

this throw throws transient true

try typeof var void volatile

209
www.Sohrabpoor.com

while with yield

Words marked with* are new in ECMAScript5

JavaScript Objects, Properties, and Methods


You should also avoid using the name of JavaScript built-in objects,
properties, and methods:

Array Date eval function hasOwnProperty

Infinity isFinite isNaN isPrototypeOf length

Math NaN name Number Object

prototype String toString undefined valueOf

Java Reserved Words


JavaScript is often used together with Java. You should avoid using some
Java objects and properties as JavaScript identifiers:

getClass java JavaArray javaClass JavaObject JavaPackage

210
www.Sohrabpoor.com

Windows Reserved Words


JavaScript can be used outside HTML. It can be used as the programming
language in many other applications.

In HTML you must (for portability you should) avoid using the name of HTML
and Windows objects and properties:

alert all anchor anchors area

assign blur button checkbox clearInterval

clearTimeout clientInformation close closed confirm

constructor crypto decodeURI decodeURICompone defaultStatus


nt

document element elements embed embeds

encodeURI encodeURICompone escape event fileUpload


nt

focus form forms frame innerHeight

innerWidth layer layers link location

mimeTypes navigate navigator frames frameRate

hidden history image images offscreenBufferin


g

211
www.Sohrabpoor.com

open opener option outerHeight outerWidth

packages pageXOffset pageYOffse parent parseFloat


t

parseInt password pkcs11 plugin prompt

propertyIsEnu radio reset screenX screenY


m

scroll secure select self setInterval

setTimeout status submit taint text

textarea top unescape untaint window

HTML Event Handlers


In addition you should avoid using the name of all HTML event handlers.

Examples:

onblur onclick onerror onfocus

onkeydown onkeypress onkeyup onmouseover

onload onmouseup onmousedown onsubmit

212
www.Sohrabpoor.com

JavaScript JSON
JSON is a format for storing and transporting data.

JSON is often used when data is sent from a server to a web page.

What is JSON?
 JSON stands for JavaScript Object Notation
 JSON is lightweight data interchange format
 JSON is language independent *
 JSON is "self-describing" and easy to understand

* The JSON syntax is derived from JavaScript object notation syntax, but the
JSON format is text only. Code for reading and generating JSON data can be
written in any programming language.

JSON Example
This JSON syntax defines an employees object: an array of 3 employee
records (objects):

JSON Example
{
"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]
}

213
www.Sohrabpoor.com

The JSON Format Evaluates to JavaScript


Objects
The JSON format is syntactically identical to the code for creating JavaScript
objects.

Because of this similarity, a JavaScript program can easily convert JSON data
into native JavaScript objects.

JSON Syntax Rules


 Data is in name/value pairs
 Data is separated by commas
 Curly braces hold objects
 Square brackets hold arrays

JSON Data - A Name and a Value


JSON data is written as name/value pairs, just like JavaScript object
properties.

A name/value pair consists of a field name (in double quotes), followed by a


colon, followed by a value:

"firstName":"John"

JSON names require double quotes. JavaScript names do not.

JSON Objects
JSON objects are written inside curly braces.

Just like in JavaScript, objects can contain multiple name/value pairs:

{"firstName":"John", "lastName":"Doe"}

214
www.Sohrabpoor.com

JSON Arrays
JSON arrays are written inside square brackets.

Just like in JavaScript, an array can contain objects:

"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]

In the example above, the object "employees" is an array. It contains three


objects.

Each object is a record of a person (with a first name and a last name).

Converting a JSON Text to a JavaScript


Object
A common use of JSON is to read data from a web server, and display the
data in a web page.

For simplicity, this can be demonstrated using a string as input (or read more
in our JSON tutorial):

First, create a JavaScript string containing JSON syntax:

var text = '{ "employees" : [' +


'{ "firstName":"John" , "lastName":"Doe" },' +
'{ "firstName":"Anna" , "lastName":"Smith" },' +
'{ "firstName":"Peter" , "lastName":"Jones" } ]}';

Then, use the JavaScript built-in function JSON.parse() to convert the string
into a JavaScript object:

var obj = JSON.parse(text);

Finally, use the new JavaScript object in your page:

215
www.Sohrabpoor.com

Example
<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML =
obj.employees[1].firstName + " " + obj.employees[1].lastName;
</script>

Try it Yourself »

You can read more about JSON in our JSON tutorial.

JavaScript Forms
JavaScript Form Validation
HTML form validation can be done by JavaScript.

If a form field (fname) is empty, this function alerts a message, and returns
false, to prevent the form from being submitted:

JavaScript Example
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == null || x == "") {
alert("Name must be filled out");
return false;
}
}

The function can be called when the form is submitted:

HTML Form Example


<form name="myForm" action="demo_form.asp" onsubmit="return
validateForm()" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>

Try it Yourself »

216
www.Sohrabpoor.com

JavaScript Can Validate Numeric Input


JavaScript is often used to validate numeric input:

Please input a number between 1 and 10

Submit
Try it Yourself »
<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Can Validate Input</h1>

<p>Please input a number between 1 and 10:</p>

<input id="numb">

<button type="button" onclick="myFunction()">Submit</button>

<p id="demo"></p>

<script>
function myFunction() {
var x, text;

// Get the value of the input field with id="numb"


x = document.getElementById("numb").value;

// If x is Not a Number or less than one or greater than 10


if (isNaN(x) || x < 1 || x > 10) {
text = "Input not valid";
} else {
text = "Input OK";
}
document.getElementById("demo").innerHTML = text;
}
</script>

</body>
</html>

Automatic HTML Form Validation


HTML form validation can be performed automatically by the browser:

If a form field (fname) is empty, the required attribute prevents this form
from being submitted:

217
www.Sohrabpoor.com

HTML Form Example


<form action="demo_form.asp" method="post">
<input type="text" name="fname" required>
<input type="submit" value="Submit">
</form>

Try it Yourself »
// Action:
<body>
Welcome
<%
response.write(request.querystring("fname"))
response.write(" " & request.querystring("lname"))
%>
</body>

Automatic HTML form validation does not work in Internet Explorer 9 or


earlier.

Data Validation
Data validation is the process of ensuring that computer input is clean,
correct, and useful.

Typical validation tasks are:

 has the user filled in all required fields?


 has the user entered a valid date?
 has the user entered text in a numeric field?

Most often, the purpose of data validation is to ensure correct input to a


computer application.

Validation can be defined by many different methods, and deployed in many


different ways.

Server side validation is performed by a web server, after input has been
sent to the server.

Client side validation is performed by a web browser, before input is sent


to a web server.

218
www.Sohrabpoor.com

HTML Constraint Validation


HTML5 introduced a new HTML validation concept called constraint
validation.

HTML constraint validation is based on:

 Constraint validation HTML Input Attributes


 Constraint validation CSS Pseudo Selectors
 Constraint validation DOM Properties and Methods

Constraint Validation HTML Input Attributes


Attribute Description

disabled Specifies that the input element should be disabled

max Specifies the maximum value of an input element

min Specifies the minimum value of an input element

pattern Specifies the value pattern of an input element

required Specifies that the input field requires an element

type Specifies the type of an input element

For a full list, go to HTML Input Attributes.

219
www.Sohrabpoor.com

Constraint Validation CSS Pseudo Selectors


Selector Description

:disabled Selects input elements with the "disabled" attribute specified

:invalid Selects input elements with invalid values

:optional Selects input elements with no "required" attribute specified

:required Selects input elements with the "required" attribute specified

:valid Selects input elements with valid values

For a full list, got to CSS Pseudo Classes.

JavaScript Validation API


Constraint Validation DOM Methods
Property Description

checkValidity() Returns true if an input element contains valid data.

setCustomValidity() Sets the validationMessage property of an input


element.

220
www.Sohrabpoor.com

If an input field contains invalid data, display a message:

The checkValidity() Method


<input id="id1" type="number" min="100" max="300" required>
<button onclick="myFunction()">OK</button>

<p id="demo"></p>

<script>
function myFunction() {
var inpObj = document.getElementById("id1");
if (inpObj.checkValidity() == false) {
document.getElementById("demo").innerHTML =
inpObj.validationMessage;
}
}
</script>

Try it Yourself »

Constraint Validation DOM Properties


Property Description

validity Contains boolean properties related to the validity of


an input element.

validationMessage Contains the message a browser will display when the


validity is false.

willValidate Indicates if an input element will be validated.

221
www.Sohrabpoor.com

Validity Properties
The validity property of an input element contains a number of properties
related to the validity of data:

Property Description

customError Set to true, if a custom validity message is set.

patternMismatch Set to true, if an element's value does not match its pattern
attribute.

rangeOverflow Set to true, if an element's value is greater than its max


attribute.

rangeUnderflow Set to true, if an element's value is less than its min attribute.

stepMismatch Set to true, if an element's value is invalid per its step


attribute.

tooLong Set to true, if an element's value exceeds its maxLength


attribute.

typeMismatch Set to true, if an element's value is invalid per its type


attribute.

valueMissing Set to true, if an element (with a required attribute) has no


value.

valid Set to true, if an element's value is valid.

222
www.Sohrabpoor.com

Examples
If the number in an input field is greater than 100 (the input's max
attribute), display a message:

The rangeOverflow Property


<input id="id1" type="number" max="100">
<button onclick="myFunction()">OK</button>

<p id="demo"></p>

<script>
function myFunction() {
var txt = "";
if (document.getElementById("id1").validity.rangeOverflow) {
txt = "Value too large";
}
document.getElementById("demo").innerHTML = txt;
}
</script>

Try it Yourself »

If the number in an input field is less than 100 (the input's min attribute),
display a message:

The rangeUnderflow Property


<input id="id1" type="number" min="100">
<button onclick="myFunction()">OK</button>

<p id="demo"></p>

<script>
function myFunction() {
var txt = "";
if (document.getElementById("id1").validity.rangeUnderflow) {
txt = "Value too small";
}
document.getElementById("demo").innerHTML = txt;
}
</script>

Try it Yourself »

223
www.Sohrabpoor.com

JavaScript Objects
JavaScript Objects
In JavaScript, objects are king. If you understand objects, you understand
JavaScript.

In JavaScript, almost "everything" is an object.

 Booleans can be objects (or primitive data treated as objects)


 Numbers can be objects (or primitive data treated as objects)
 Strings can be objects (or primitive data treated as objects)
 Dates are always objects
 Maths are always objects
 Regular expressions are always objects
 Arrays are always objects
 Functions are always objects
 Objects are objects

In JavaScript, all values, except primitive values, are objects.

Primitive values are: strings ("John Doe"), numbers (3.14), true, false, null,
and undefined.

Objects are Variables Containing Variables


JavaScript variables can contain single values:

Example
var person = "John Doe";

Try it Yourself »

Objects are variables too. But objects can contain many values.

The values are written as name : value pairs (name and value separated by
a colon).

Example
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};

Try it Yourself »

A JavaScript object is a collection of named values

224
www.Sohrabpoor.com

Object Properties
The named values, in JavaScript objects, are called properties.

Property Value

firstName John

lastName Doe

age 50

eyeColor blue

Objects written as name value pairs are similar to:

 Associative arrays in PHP


 Dictionaries in Python
 Hash tables in C
 Hash maps in Java
 Hashes in Ruby and Perl

Object Methods
Methods are actions that can be performed on objects.

Object properties can be both primitive values, other objects, and functions.

An object method is an object property containing a function definition.

225
www.Sohrabpoor.com

Property Value

firstName John

lastName Doe

age 50

eyeColor blue

fullName function() {return this.firstName + " " + this.lastName;}

JavaScript objects are containers for named values, called properties and
methods.

You will learn more about methods in the next chapters.

Creating a JavaScript Object


With JavaScript, you can define and create your own objects.

There are different ways to create new objects:

 Define and create a single object, using an object literal.


 Define and create a single object, with the keyword new.
 Define an object constructor, and then create objects of the
constructed type.

In ECMAScript 5, an object can also be created with the function


Object.create().

226
www.Sohrabpoor.com

Using an Object Literal


This is the easiest way to create a JavaScript Object.

Using an object literal, you both define and create an object in one
statement.

An object literal is a list of name:value pairs (like age:50) inside curly braces
{}.

The following example creates a new JavaScript object with four properties:

Example
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};

Try it Yourself »

Spaces and line breaks are not important. An object definition can span
multiple lines:

Example
var person = {
firstName:"John",
lastName:"Doe",
age:50,
eyeColor:"blue"
};

Try it Yourself »

Using the JavaScript Keyword new


The following example also creates a new JavaScript object with four
properties:

Example
var person = new Object();
person.firstName = "John";
person.lastName = "Doe";
person.age = 50;
person.eyeColor = "blue";

Try it Yourself »

227
www.Sohrabpoor.com

The two examples above do exactly the same. There is no need to use new
Object().
For simplicity, readability and execution speed, use the first one (the object
literal method).

Using an Object Constructor


The examples above are limited in many situations. They only create a single
object.

Sometimes we like to have an "object type" that can be used to create many
objects of one type.

The standard way to create an "object type" is to use an object constructor


function:

Example
function person(first, last, age, eye) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
}
var myFather = new person("John", "Doe", 50, "blue");
var myMother = new person("Sally", "Rally", 48, "green");

Try it yourself »

The above function (person) is an object constructor.

Once you have an object constructor, you can create new objects of the
same type:

var myFather = new person("John", "Doe", 50, "blue");


var myMother = new person("Sally", "Rally", 48, "green");

228
www.Sohrabpoor.com

The this Keyword


In JavaScript, the thing called this, is the object that "owns" the JavaScript
code.

The value of this, when used in a function, is the object that "owns" the
function.

The value of this, when used in an object, is the object itself.

The this keyword in an object constructor does not have a value. It is only a
substitute for the new object.

The value of this will become the new object when the constructor is used to
create an object.

Note that this is not a variable. It is a keyword. You cannot change the value
of this.

Built-in JavaScript Constructors


JavaScript has built-in constructors for native objects:

Example
var x1 = new Object(); // A new Object object
var x2 = new String(); // A new String object
var x3 = new Number(); // A new Number object
var x4 = new Boolean(); // A new Boolean object
var x5 = new Array(); // A new Array object
var x6 = new RegExp(); // A new RegExp object
var x7 = new Function(); // A new Function object
var x8 = new Date(); // A new Date object

Try it Yourself »

The Math() object is not in the list. Math is a global object. The new keyword
cannot be used on Math.

229
www.Sohrabpoor.com

Did You Know?


As you can see, JavaScript has object versions of the primitive data types
String, Number, and Boolean.

There is no reason to create complex objects. Primitive values execute much


faster.

And there is no reason to use new Array(). Use array literals instead: []

And there is no reason to use new RegExp(). Use pattern literals instead: /()/

And there is no reason to use new Function(). Use function expressions


instead: function () {}.

And there is no reason to use new Object(). Use object literals instead: {}

Example
var x1 = {}; // new object
var x2 = ""; // new primitive string
var x3 = 0; // new primitive number
var x4 = false; // new primitive boolean
var x5 = []; // new array object
var x6 = /()/ // new regexp object
var x7 = function(){}; // new function object

Try it Yourself »

JavaScript Objects are Mutable


Objects are mutable: They are addressed by reference, not by value.

If person is an object, the following statement will not create a copy of


person:

var x = person; // This will not create a copy of person.

The object x is not a copy of person. It is person. Both x and person is the
same object.

Any changes to x will also change person, because x and person are the
same object.

230
www.Sohrabpoor.com

Example
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"}

var x = person;
x.age = 10; // This will change both x.age and person.age

Try it Yourself »

Note: JavaScript variables are not mutable. Only JavaScript objects.

JavaScript Object Properties


Properties are the most important part of any JavaScript object.

JavaScript Properties
Properties are the values associated with a JavaScript object.

A JavaScript object is a collection of unordered properties.

Properties can usually be changed, added, and deleted, but some are read
only.

Accessing JavaScript Properties


The syntax for accessing the property of an object is:

objectName.property // person.age

or

objectName["property"] // person["age"]

or

objectName[expression] // x = "age"; person[x]

The expression must evaluate to a property name.

231
www.Sohrabpoor.com

Example 1
person.firstname + " is " + person.age + " years old.";

Try it Yourself »

Example 2
person["firstname"] + " is " + person["age"] + " years old.";

Try it Yourself »

JavaScript for...in Loop


The JavaScript for...in statement loops through the properties of an object.

Syntax
for (variable in object) {
code to be executed
}

The block of code inside of the for...in loop will be executed once for each
property.

Looping through the properties of an object:

Example
var person = {fname:"John", lname:"Doe", age:25};

for (x in person) {
txt += person[x];
}

Try it Yourself »

Adding New Properties


You can add new properties to an existing object by simply giving it a value.

Assume that the person object already exists - you can then give it new
properties:

232
www.Sohrabpoor.com

Example
person.nationality = "English";

Try it Yourself »

You cannot use reserved words for property (or method) names. JavaScript
naming rules apply.

Deleting Properties
The delete keyword deletes a property from an object:

Example
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
delete person.age; // or delete person["age"];

Try it Yourself »

The delete keyword deletes both the value of the property and the property
itself.

After deletion, the property cannot be used before it is added back again.

The delete operator is designed to be used on object properties. It has no


effect on variables or functions.

The delete operator should not be used on predefined JavaScript object


properties. It can crash your application.

Property Attributes
All properties have a name. In addition they also have a value.

The value is one of the property's attributes.

Other attributes are: enumerable, configurable, and writable.

These attributes define how the property can be accessed (is it readable?, is
it writable?)

233
www.Sohrabpoor.com

In JavaScript, all attributes can be read, but only the value attribute can be
changed (and only if the property is writable).

( ECMAScript 5 has methods for both getting and setting all property
attributes)

Prototype Properties
JavaScript objects inherit the properties of their prototype.

The delete keyword does not delete inherited properties, but if you delete a
prototype property, it will affect all objects inherited from the prototype.

JavaScript Object Methods


JavaScript Methods
JavaScript methods are the actions that can be performed on objects.

A JavaScript method is a property containing a function definition.

Property Value

firstName John

lastName Doe

age 50

eyeColor blue

fullName function() {return this.firstName + " " + this.lastName;}

Methods are functions stored as object properties.

234
www.Sohrabpoor.com

Accessing Object Methods


You create an object method with the following syntax:

methodName : function() { code lines }

You access an object method with the following syntax:

objectName.methodName()

You will typically describe fullName() as a method of the person object, and fullName as a
property.

The fullName property will execute (as a function) when it is invoked with ().

This example accesses the fullName() method of a person object:

Example
name = person.fullName();

Try it Yourself »

If you access the fullName property, without (), it will return the function definition:

Example
name = person.fullName;

Try it Yourself »

Using Built-In Methods


This example uses the toUpperCase() method of the String object, to convert a text to
uppercase:

var message = "Hello world!";


var x = message.toUpperCase();

The value of x, after execution of the code above will be:

HELLO WORLD!

235
www.Sohrabpoor.com

Adding New Methods


Defining methods to an object is done inside the constructor function:

Example
function person(firstName, lastName, age, eyeColor) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.eyeColor = eyeColor;
this.changeName = function (name) {
this.lastName = name;
};
}

The changeName() function assigns the value of name to the person's lastName property.

Now You Can Try:


myMother.changeName("Doe");
Try it Yourself »

JavaScript knows which person you are talking about by "substituting" this with myMother.

JavaScript Object Prototypes


Every JavaScript object has a prototype. The prototype is also an object.

All JavaScript objects inherit their properties and methods from their
prototype.

JavaScript Prototypes
All JavaScript objects inherit the properties and methods from their
prototype.

Objects created using an object literal, or with new Object(), inherit from a
prototype called Object.prototype.

Objects created with new Date() inherit the Date.prototype.

The Object.prototype is on the top of the prototype chain.

236
www.Sohrabpoor.com

All JavaScript objects (Date, Array, RegExp, Function, ....) inherit from the
Object.prototype.

Creating a Prototype
The standard way to create an object prototype is to use an object
constructor function:

Example
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
}

With a constructor function, you can use the new keyword to create new
objects from the same prototype:

Example
var myFather = new Person("John", "Doe", 50, "blue");
var myMother = new Person("Sally", "Rally", 48, "green");

Try it Yourself »

The constructor function is the prototype for Person objects.


It is considered good practice to name constructor function with an upper-
case first letter.

Adding Properties and Methods to Objects


Sometimes you want to add new properties (or methods) to an existing
object.

Sometimes you want to add new properties (or methods) to all existing
objects of a given type.

Sometimes you want to add new properties (or methods) to an object


prototype.

237
www.Sohrabpoor.com

Adding a Property to an Object


Adding a new property to an existing object is easy:

Example
myFather.nationality = "English";

Try it Yourself »

The property will be added to myFather. Not to myMother. Not to any other
person objects.

Adding a Method to an Object


Adding a new method to an existing object is also easy:

Example
myFather.name = function () {
return this.firstName + " " + this.lastName;
};

Try it Yourself »

The method will be added to myFather. Not to myMother.

Adding Properties to a Prototype


You cannot add a new property to a prototype the same way as you add a
new property to an existing object, because the prototype is not an existing
object.

Example
Person.nationality = "English";

Try it Yourself »

To add a new property to a constructor, you must add it to the constructor


function:

238
www.Sohrabpoor.com

Example
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
this.nationality = "English"
}

Try it Yourself »

Prototype properties can have prototype values (default values).

Adding Methods to a Prototype


Your constructor function can also define methods:

Example
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
this.name = function() {return this.firstName + " " + this.lastName;};
}

Try it Yourself »

Using the prototype Property


The JavaScript prototype property allows you to add new properties to an
existing prototype:

Example
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
}
Person.prototype.nationality = "English";

Try it Yourself »

239
www.Sohrabpoor.com

The JavaScript prototype property also allows you to add new methods to an
existing prototype:

Example
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
}
Person.prototype.name = function() {
return this.firstName + " " + this.lastName;
};

Try it Yourself »

Only modify your own prototypes. Never modify the prototypes of standard
JavaScript objects.

JavaScript Function Definitions


JavaScript functions are defined with the function keyword.

You can use a function declaration or a function expression.

Function Declarations
Earlier in this tutorial, you learned that functions are declared with the
following syntax:

function functionName(parameters) {
code to be executed
}

Declared functions are not executed immediately. They are "saved for later
use", and will be executed later, when they are invoked (called upon).

240
www.Sohrabpoor.com

Example
function myFunction(a, b) {
return a * b;
}

Try it Yourself »

Semicolons are used to separate executable JavaScript statements.


Since a function declaration is not an executable statement, it is not
common to end it with a semicolon.

Function Expressions
A JavaScript function can also be defined using an expression.

A function expression can be stored in a variable:

Example
var x = function (a, b) {return a * b};

Try it Yourself »

After a function expression has been stored in a variable, the variable can be
used as a function:

Example
var x = function (a, b) {return a * b};
var z = x(4, 3);

Try it Yourself »

The function above is actually an anonymous function (a function without


a name).

Functions stored in variables do not need function names. They are always
invoked (called) using the variable name.

The function above ends with a semicolon because it is a part of an


executable statement.

241
www.Sohrabpoor.com

The Function() Constructor


As you have seen in the previous examples, JavaScript functions are defined
with the function keyword.

Functions can also be defined with a built-in JavaScript function constructor


called Function().

Example
var myFunction = new Function("a", "b", "return a * b");

var x = myFunction(4, 3);

Try it Yourself »

You actually don't have to use the function constructor. The example above
is the same as writing:

Example
var myFunction = function (a, b) {return a * b};

var x = myFunction(4, 3);

Try it Yourself »

Most of the time, you can avoid using the new keyword in JavaScript.

Function Hoisting
Earlier in this tutorial, you learned about "hoisting".

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.

Because of this, JavaScript functions can be called before they are declared:

myFunction(5);

function myFunction(y) {
return y * y;
}

Functions defined using an expression are not hoisted.

242
www.Sohrabpoor.com

Self-Invoking Functions
Function expressions can be made "self-invoking".

A self-invoking expression is invoked (started) automatically, without being


called.

Function expressions will execute automatically if the expression is followed


by ().

You cannot self-invoke a function declaration.

You have to add parentheses around the function to indicate that it is a


function expression:

Example
(function () {
var x = "Hello!!"; // I will invoke myself
})();

Try it Yourself »

The function above is actually an anonymous self-invoking


function (function without name).

Functions Can Be Used as Values


JavaScript functions can be used as values:

Example
function myFunction(a, b) {
return a * b;
}

var x = myFunction(4, 3);

Try it Yourself »

JavaScript functions can be used in expressions:

243
www.Sohrabpoor.com

Example
function myFunction(a, b) {
return a * b;
}

var x = myFunction(4, 3) * 2;

Try it Yourself »

Functions are Objects


The typeof operator in JavaScript returns "function" for functions.

But, JavaScript functions can best be described as objects.

JavaScript functions have both properties and methods.

The arguments.length property returns the number of arguments received


when the function was invoked:

Example
function myFunction(a, b) {
return arguments.length;
}

Try it Yourself »

The toString() method returns the function as a string:

Example
function myFunction(a, b) {
return a * b;
}

var txt = myFunction.toString();

Try it Yourself »

A function defined as the property of an object, is called a method to the


object.
A function designed to create new objects, is called an object constructor.

244
www.Sohrabpoor.com

JavaScript Function Parameters


A JavaScript function does not perform any checking on parameter values
(arguments).

Function Parameters and Arguments


Earlier in this tutorial, you learned that functions can have parameters:

functionName(parameter1, parameter2, parameter3) {


code to be executed
}

Function parameters are the names listed in the function definition.

Function arguments are the real values passed to (and received by) the
function.

Parameter Rules
JavaScript function definitions do not specify data types for parameters.

JavaScript functions do not perform type checking on the passed arguments.

JavaScript functions do not check the number of arguments received.

Parameter Defaults
If a function is called with missing arguments (less than declared), the
missing values are set to: undefined

Sometimes this is acceptable, but sometimes it is better to assign a default


value to the parameter:

245
www.Sohrabpoor.com

Example
function myFunction(x, y) {
if (y === undefined) {
y = 0;
}
}

Try it Yourself »

If a function is called with too many arguments (more than declared),


these arguments can be reached using the arguments object.

The Arguments Object


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).

This way you can simply use a function to find (for instance) the highest
value in a list of numbers:

Example
x = findMax(1, 123, 500, 115, 44, 88);

function findMax() {
var i;
var max = -Infinity;
for (i = 0; i < arguments.length; i++) {
if (arguments[i] > max) {
max = arguments[i];
}
}
return max;
}

Try it Yourself »

246
www.Sohrabpoor.com

Or create a function to sum all input values:

Example
x = sumAll(1, 123, 500, 115, 44, 88);

function sumAll() {
var i, sum = 0;
for (i = 0; i < arguments.length; i++) {
sum += arguments[i];
}
return sum;
}

Try it Yourself »

Arguments are Passed by Value


The parameters, in a function call, are the function's arguments.

JavaScript arguments are passed by value: The function only gets to know
the values, not the argument's locations.

If a function changes an argument's value, it does not change the


parameter's original value.

Changes to arguments are not visible (reflected) outside the


function.

Objects are Passed by Reference


In JavaScript, object references are values.

Because of this, objects will behave like they are passed by reference:

If a function changes an object property, it changes the original value.

Changes to object properties are visible (reflected) outside the


function.

247
www.Sohrabpoor.com

JavaScript Function Invocation


JavaScript functions can be invoked in 4 different ways.

Each method differs in how this is initialized.

The this Keyword


In JavaScript, the thing called this, is the object that "owns" the current
code.

The value of this, when used in a function, is the object that "owns" the
function.

Note that this is not a variable. It is a keyword. You cannot change the value
of this.

Invoking a JavaScript Function


You have already learned that the code inside a JavaScript function will
execute when "something" invokes it.

The code in a function is not executed when the function is defined. It is


executed when the function is invoked.

Some people use the term "call a function" instead of "invoke a function".

It is also quite common to say "call upon a function", "start a function", or


"execute a function".

In this tutorial, we will use invoke, because a JavaScript function can be


invoked without being called.

248
www.Sohrabpoor.com

Invoking a Function as a Function


Example
function myFunction(a, b) {
return a * b;
}
myFunction(10, 2); // myFunction(10, 2) will return 20

Try it Yourself »

The function above does not belong to any object. But in JavaScript there is
always a default global object.

In HTML the default global object is the HTML page itself, so the function
above "belongs" to the HTML page.

In a browser the page object is the browser window. The function above
automatically becomes a window function.

myFunction() and window.myFunction() is the same function:

Example
function myFunction(a, b) {
return a * b;
}
window.myFunction(10, 2); // window.myFunction(10, 2) will also return
20

Try it Yourself »

This is a common way to invoke a JavaScript function, but not a very good
practice.
Global variables, methods, or functions can easily create name conflicts and
bugs in the global object.

The Global Object


When a function is called without an owner object, the value of this becomes
the global object.

In a web browser the global object is the browser window.

This example returns the window object as the value of this:

249
www.Sohrabpoor.com

Example
function myFunction() {
return this;
}
myFunction(); // Will return the window object

Try it Yourself »

Invoking a function as a global function, causes the value of this to be the


global object.
Using the window object as a variable can easily crash your program.

Invoking a Function as a Method


In JavaScript you can define function as object methods.

The following example creates an object (myObject), with two properties


(firstName and lastName), and a method (fullName):

Example
var myObject = {
firstName:"John",
lastName: "Doe",
fullName: function () {
return this.firstName + " " + this.lastName;
}
}
myObject.fullName(); // Will return "John Doe"

Try it Yourself »

The fullName method is a function. The function belongs to the


object. myObject is the owner of the function.

The thing called this, is the object that "owns" the JavaScript code. In this
case the value of this is myObject.

Test it! Change the fullName method to return the value of this:

250
www.Sohrabpoor.com

Example
var myObject = {
firstName:"John",
lastName: "Doe",
fullName: function () {
return this;
}
}
myObject.fullName(); // Will return [object Object] (the owner
object)

Try it Yourself »

Invoking a function as an object method, causes the value of this to be the


object itself.

Invoking a Function with a Function


Constructor
If a function invocation is preceded with the new keyword, it is a constructor
invocation.

It looks like you create a new function, but since JavaScript functions are
objects you actually create a new object:

Example
// This is a function constructor:
function myFunction(arg1, arg2) {
this.firstName = arg1;
this.lastName = arg2;
}

// This creates a new object


var x = new myFunction("John","Doe");
x.firstName; // Will return "John"

Try it Yourself »

A constructor invocation creates a new object. The new object inherits the
properties and methods from its constructor.

251
www.Sohrabpoor.com

The this keyword in the constructor does not have a value.


The value of this will be the new object created when the function is
invoked.

Invoking a Function with a Function Method


In JavaScript, functions are objects. JavaScript functions have properties and
methods.

call() and apply() are predefined JavaScript function methods. Both


methods can be used to invoke a function, and both methods must have the
owner object as first parameter.

Example
function myFunction(a, b) {
return a * b;
}
myObject = myFunction.call(myObject, 10, 2); // Will return 20

Try it Yourself »

Example
function myFunction(a, b) {
return a * b;
}
myArray = [10, 2];
myObject = myFunction.apply(myObject, myArray); // Will also return 20

Try it Yourself »

Both methods take an owner object as the first argument. The only
difference is that call() takes the function arguments separately, and apply()
takes the function arguments in an array.

In JavaScript strict mode, the first argument becomes the value of this in
the invoked function, even if the argument is not an object.

In "non-strict" mode, if the value of the first argument is null or undefined, it


is replaced with the global object.

With call() or apply() you can set the value of this, and invoke a function as
a new method of an existing object.

252
www.Sohrabpoor.com

JavaScript Closures
JavaScript variables can belong to the local or global scope.

Private variables can be made possible with closures.

Global Variables
A function can access all variables defined inside the function, like this:

Example
function myFunction() {
var a = 4;
return a * a;
}

Try it Yourself »

But a function can also access variables defined outside the function, like
this:

Example
var a = 4;
function myFunction() {
return a * a;
}

Try it Yourself »

In the last example, a is a global variable.

In a web page, global variables belong to the window object.

Global variables can be used (and changed) by all scripts in the page (and in
the window).

In the first example, a is a local variable.

A local variable can only be used inside the function where it is defined. It is
hidden from other functions and other scripting code.

253
www.Sohrabpoor.com

Global and local variables with the same name are different variables.
Modifying one, does not modify the other.

Variables created without the keyword var, are always global, even if they
are created inside a function.

Variable Lifetime
Global variables live as long as your application (your window / your web
page) lives.

Local variables have short lives. They are created when the function is
invoked, and deleted when the function is finished.

A Counter Dilemma
Suppose you want to use a variable for counting something, and you want
this counter to be available to all functions.

You could use a global variable, and a function to increase the counter:

Example
var counter = 0;

function add() {
counter += 1;
}

add();
add();
add();

// the counter is now equal to 3

Try it Yourself »

The counter should only be changed by the add() function.

The problem is, that any script on the page can change the counter, without
calling add().

254
www.Sohrabpoor.com

If I declare the counter inside the function, nobody will be able to change it
without calling add():

Example
function add() {
var counter = 0;
counter += 1;
}

add();
add();
add();

// the counter should now be 3, but it does not work !

Try it Yourself »

It did not work! Every time I call the add() function, the counter is set to 1.

A JavaScript inner function can solve this.

JavaScript Nested Functions


All functions have access to the global scope.

In fact, in JavaScript, all functions have access to the scope "above" them.

JavaScript supports nested functions. Nested functions have access to the


scope "above" them.

In this example, the inner function plus() has access to


the counter variable in the parent function:

Example
function add() {
var counter = 0;
function plus() {counter += 1;}
plus();
return counter;
}

Try it Yourself »

255
www.Sohrabpoor.com

This could have solved the counter dilemma, if we could reach


the plus() function from the outside.

We also need to find a way to execute counter = 0 only once.

We need a closure.

JavaScript Closures
Remember self-invoking functions? What does this function do?

Example
var add = (function () {
var counter = 0;
return function () {return counter += 1;}
})();

add();
add();
add();

// the counter is now 3

Try it Yourself »

Example Explained
The variable add is assigned the return value of a self-invoking function.

The self-invoking function only runs once. It sets the counter to zero (0), and
returns a function expression.

This way add becomes a function. The "wonderful" part is that it can access
the counter in the parent scope.

This is called a JavaScript closure. It makes it possible for a function to have


"private" variables.

The counter is protected by the scope of the anonymous function, and can
only be changed using the add function.

A closure is a function having access to the parent scope, even after the
parent function has closed.

256
www.Sohrabpoor.com

JavaScript HTML DOM


With the HTML DOM, JavaScript can access and change all the elements
of an HTML document.

The HTML DOM (Document Object Model)


When a web page is loaded, the browser creates a Document Object Model
of the page.

The HTML DOM model is constructed as a tree of Objects:

The HTML DOM Tree of Objects

With the object model, JavaScript gets all the power it needs to create
dynamic HTML:

 JavaScript can change all the HTML elements in the page


 JavaScript can change all the HTML attributes in the page
 JavaScript can change all the CSS styles in the page
 JavaScript can remove existing HTML elements and attributes
 JavaScript can add new HTML elements and attributes
 JavaScript can react to all existing HTML events in the page
 JavaScript can create new HTML events in the page

257
www.Sohrabpoor.com

What You Will Learn


In the next chapters of this tutorial you will learn:

 How to change the content of HTML elements


 How to change the style (CSS) of HTML elements
 How to react to HTML DOM events
 How to add and delete HTML elements

What is the DOM?


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.

258
www.Sohrabpoor.com

JavaScript - HTML DOM Methods


HTML DOM methods are actions you can perform (on HTML Elements).

HTML DOM properties are values (of HTML Elements) that you can set or
change.

The DOM Programming Interface


The HTML DOM can be accessed with JavaScript (and with other
programming languages).

In the DOM, all HTML elements are defined as objects.

The programming interface is the properties and methods of each object.

A property is a value that you can get or set (like changing the content of
an HTML element).

A method is an action you can do (like add or deleting an HTML element).

Example
The following example changes the content (the innerHTML) of the <p>
element with id="demo":

Example
<html>
<body>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = "Hello World!";
</script>

</body>
</html>

Try it Yourself »

259
www.Sohrabpoor.com

In the example above, getElementById is a method, while innerHTML is


a property.

The getElementById Method


The most common way to access an HTML element is to use the id of the
element.

In the example above the getElementById method used id="demo" to find


the element.

The innerHTML Property


The easiest way to get the content of an element is by using
the innerHTML property.

The innerHTML property is useful for getting or replacing the content of HTML
elements.

The innerHTML property can be used to get or change any HTML element,
including <html> and <body>.

JavaScript HTML DOM Document


The HTML DOM document object is the owner of all other objects in your
web page.

The HTML DOM Document Object


The document object represents your web page.

If you want to access any element in an HTML page, you always start with
accessing the document object.

Below are some examples of how you can use the document object to access
and manipulate HTML.

260
www.Sohrabpoor.com

Finding HTML Elements


Method Description

document.getElementById(id) Find an element by element id

document.getElementsByTagName(name) Find elements by tag name

document.getElementsByClassName(name) Find elements by class name

Changing HTML Elements


Method Description

element.innerHTML = new html content Change the inner HTML of an element

element.attribute = new value Change the attribute value of an HTML element

element.setAttribute(attribute, value) Change the attribute value of an HTML element

element.style.property = new style Change the style of an HTML element

261
www.Sohrabpoor.com

Adding and Deleting Elements


Method Description

document.createElement(element) Create an HTML element

document.removeChild(element) Remove an HTML element

document.appendChild(element) Add an HTML element

document.replaceChild(element) Replace an HTML element

document.write(text) Write into the HTML output stream

Adding Events Handlers


Method Description

document.getElementById(id).onclick = function(){code} Adding event handler code to an


onclick event

262
www.Sohrabpoor.com

Finding HTML Objects


The first HTML DOM Level 1 (1998), defined 11 HTML objects, object
collections, and properties. These are still valid in HTML5.

Later, in HTML DOM Level 3, more objects, collections, and properties were
added.

Property Description DOM

document.anchors Returns all <a> elements that have a name attribute 1

document.applets Returns all <applet> elements (Deprecated in HTML5) 1

document.baseURI Returns the absolute base URI of the document 3

document.body Returns the <body> element 1

document.cookie Returns the document's cookie 1

document.doctype Returns the document's doctype 3

document.documentElement Returns the <html> element 3

document.documentMode Returns the mode used by the browser 3

document.documentURI Returns the URI of the document 3

document.domain Returns the domain name of the document server 1

263
www.Sohrabpoor.com

document.domConfig Obsolete. Returns the DOM configuration 3

document.embeds Returns all <embed> elements 3

document.forms Returns all <form> elements 1

document.head Returns the <head> element 3

document.images Returns all <img> elements 1

document.implementation Returns the DOM implementation 3

document.inputEncoding Returns the document's encoding (character set) 3

document.lastModified Returns the date and time the document was updated 3

document.links Returns all <area> and <a> elements that have a href attribute 1

document.readyState Returns the (loading) status of the document 3

document.referrer Returns the URI of the referrer (the linking document) 1

document.scripts Returns all <script> elements 3

document.strictErrorChecking Returns if error checking is enforced 3

264
www.Sohrabpoor.com

document.title Returns the <title> element 1

document.URL Returns the complete URL of the document 1

JavaScript HTML DOM Elements


This page teaches you how to find and access HTML elements in an HTML
page.

Finding HTML Elements


Often, with JavaScript, you want to manipulate HTML elements.

To do so, you have to find the elements first. There are a couple of ways to
do this:

 Finding HTML elements by id


 Finding HTML elements by tag name
 Finding HTML elements by class name
 Finding HTML elements by CSS selectors
 Finding HTML elements by HTML object collections

Finding HTML Element by Id


The easiest way to find an HTML element in the DOM, is by using the
element id.

This example finds the element with id="intro":

Example
var myElement = document.getElementById("intro");

Try it Yourself »

265
www.Sohrabpoor.com

If the element is found, the method will return the element as an object (in
myElement).

If the element is not found, myElement will contain null.

Finding HTML Elements by Tag Name


This example finds all <p> elements:

Example
var x = document.getElementsByTagName("p");

Try it Yourself »

This example finds the element with id="main", and then finds all <p>
elements inside "main":

Example
var x = document.getElementById("main");
var y = x.getElementsByTagName("p");

Try it Yourself »

Finding HTML Elements by Class Name


If you want to find all HTML elements with the same class name, use
getElementsByClassName().

This example returns a list of all elements with class="intro".

Example
var x = document.getElementsByClassName("intro");

Try it Yourself »

Finding elements by class name does not work in Internet Explorer 8 and
earlier versions.

266
www.Sohrabpoor.com

Finding HTML Elements by CSS Selectors


If you want to find all HTML elements that matches a specified CSS selector
(id, class names, types, attributes, values of attributes, etc), use the
querySelectorAll() method.

This example returns a list of all <p> elements with class="intro".

Example
var x = document.querySelectorAll("p.intro");

Try it Yourself »

The querySelectorAll() method does not work in Internet Explorer 8 and


earlier versions.

Finding HTML Elements by HTML Object


Collections
This example finds the form element with id="frm1", in the forms collection,
and displays all element values:

Example
var x = document.forms["frm1"];
var text = "";
var i;
for (i = 0; i < x.length; i++) {
text += x.elements[i].value + "<br>";
}
document.getElementById("demo").innerHTML = text;

Try it Yourself »

The following HTML objects (and object collections) are also accessible:

 document.anchors
 document.body
 document.documentElement
 document.embeds
 document.forms
 document.head
 document.images

267
www.Sohrabpoor.com

 document.links
 document.scripts
 document.title

JavaScript HTML DOM - Changing


HTML
The HTML DOM allows JavaScript to change the content of HTML
elements.

Changing the HTML Output Stream


JavaScript can create dynamic HTML content:

Date: Fri Sep 16 2016 10:01:42 GMT+0430 (Iran Daylight Time)

In JavaScript, document.write() can be used to write directly to the HTML


output stream:

Example
<!DOCTYPE html>
<html>
<body>

<script>
document.write(Date());
</script>

</body>
</html>

Try it Yourself »

Never use document.write() after the document is loaded. It will overwrite


the document.

268
www.Sohrabpoor.com

Changing HTML Content


The easiest way to modify the content of an HTML element is by using
the innerHTML property.

To change the content of an HTML element, use this syntax:

document.getElementById(id).innerHTML = new HTML

This example changes the content of a <p> element:

Example
<html>
<body>

<p id="p1">Hello World!</p>

<script>
document.getElementById("p1").innerHTML = "New text!";
</script>

</body>
</html>

Try it Yourself »

This example changes the content of an <h1> element:

Example
<!DOCTYPE html>
<html>
<body>

<h1 id="header">Old Header</h1>

<script>
var element = document.getElementById("header");
element.innerHTML = "New Header";
</script>

</body>
</html>

Try it Yourself »

269
www.Sohrabpoor.com

Example explained:

 The HTML document above contains an <h1> element with


id="header"
 We use the HTML DOM to get the element with id="header"
 A JavaScript changes the content (innerHTML) of that element

Changing the Value of an Attribute


To change the value of an HTML attribute, use this syntax:

document.getElementById(id).attribute=new value

This example changes the value of the src attribute of an <img> element:

Example
<!DOCTYPE html>
<html>
<body>

<img id="myImage" src="smiley.gif">

<script>
document.getElementById("myImage").src = "landscape.jpg";
</script>

</body>
</html>

Try it Yourself »

Example explained:

 The HTML document above contains an <img> element with


id="myImage"
 We use the HTML DOM to get the element with id="myImage"
 A JavaScript changes the src attribute of that element from "smiley.gif"
to "landscape.jpg"

270
www.Sohrabpoor.com

JavaScript HTML DOM - Changing


CSS
The HTML DOM allows JavaScript to change the style of HTML elements.

Changing HTML Style


To change the style of an HTML element, use this syntax:

document.getElementById(id).style.property=new style

The following example changes the style of a <p> element:

Example
<html>
<body>

<p id="p2">Hello World!</p>

<script>
document.getElementById("p2").style.color = "blue";
</script>

<p>The paragraph above was changed by a script.</p>

</body>
</html>

Try it Yourself »

Using Events
The HTML DOM allows you to execute code when an event occurs.

Events are generated by the browser when "things happen" to HTML


elements:

 An element is clicked on
 The page has loaded
 Input fields are changed

271
www.Sohrabpoor.com

You will learn more about events in the next chapter of this tutorial.

This example changes the style of the HTML element with id="id1", when the
user clicks a button:

Example
<!DOCTYPE html>
<html>
<body>

<h1 id="id1">My Heading 1</h1>

<button type="button"
onclick="document.getElementById('id1').style.color = 'red'">
Click Me!</button>

</body>
</html>

Try it Yourself »

More Examples
Visibility How to make an element invisible. Do you want to show the
element or not?

HTML DOM Style Object Reference


For all HTML DOM style properties, look at our complete HTML DOM Style
Object Reference.

272
www.Sohrabpoor.com

JavaScript HTML DOM Animation


Learn to create HTML animations using JavaScript.

A Basic Web Page


To demonstrate how to create HTML animations with JavaScript, we will use
a simple web page:

Example
<!DOCTYPE html>
<html>
<body>

<h1>My First JavaScript Animation</h1>

<div id="animation">My animation will go here</div>

</body>
</html>

Try it Yourself »

Create an Animation Container


All animations should be relative to a container element.

Example
<div id ="container">
<div id ="animate">My animation will go here</div>
</div>

Style the Elements


The container element should be created with style = "position: relative".

273
www.Sohrabpoor.com

The animation element should be created with style = "position: absolute".

Example
#container {
width: 400px;
height: 400px;
position: relative;
background: yellow;
}
#animate {
width: 50px;
height: 50px;
position: absolute;
background: red;
}

Try it Yourself »

Animation Code
JavaScript animations are done by programming gradual changes in an
element's style.

The changes are called by a timer. When the timer interval is small, the
animation looks continuous.

The basic code is:

Example
var id = setInterval(frame, 5);

function frame() {
if (/* test for finished */) {
clearInterval(id);
} else {
/* code to change the element style */
}
}

274
www.Sohrabpoor.com

Create the Animation Using JavaScript


Example
function myMove() {
var elem = document.getElementById("animate");
var pos = 0;
var id = setInterval(frame, 5);
function frame() {
if (pos == 350) {
clearInterval(id);
} else {
pos++;
elem.style.top = pos + 'px';
elem.style.left = pos + 'px';
}
}
}

Try it Yourself »

JavaScript HTML DOM Events


HTML DOM allows JavaScript to react to HTML events:

Mouse Over Me , Click Me

Reacting to Events
A JavaScript can be executed when an event occurs, like when a user clicks
on an HTML element.

To execute code when a user clicks on an element, add JavaScript code to an


HTML event attribute:

onclick=JavaScript

Examples of HTML events:

 When a user clicks the mouse


 When a web page has loaded
 When an image has been loaded
 When the mouse moves over an element
 When an input field is changed
 When an HTML form is submitted
 When a user strokes a key

275
www.Sohrabpoor.com

In this example, the content of the <h1> element is changed when a user
clicks on it:

Example
<!DOCTYPE html>
<html>
<body>

<h1 onclick="this.innerHTML='Ooops!'">Click on this text!</h1>

</body>
</html>

Try it Yourself »

In this example, a function is called from the event handler:

Example
<!DOCTYPE html>
<html>
<body>

<h1 onclick="changeText(this)">Click on this text!</h1>

<script>
function changeText(id) {
id.innerHTML = "Ooops!";
}
</script>

</body>
</html>

Try it Yourself »

HTML Event Attributes


To assign events to HTML elements you can use event attributes.

Example
Assign an onclick event to a button element:

<button onclick="displayDate()">Try it</button>

Try it Yourself »

276
www.Sohrabpoor.com

In the example above, a function named displayDate will be executed when


the button is clicked.

Assign Events Using the HTML DOM


The HTML DOM allows you to assign events to HTML elements using
JavaScript:

Example
Assign an onclick event to a button element:

<script>
document.getElementById("myBtn").onclick = displayDate;
</script>

Try it Yourself »

In the example above, a function named displayDate is assigned to an HTML


element with the id="myBtn".

The function will be executed when the button is clicked.

The onload and onunload Events


The onload and onunload events are triggered when the user enters or
leaves the page.

The onload event can be used to check the visitor's browser type and
browser version, and load the proper version of the web page based on the
information.

The onload and onunload events can be used to deal with cookies.

Example
<body onload="checkCookies()">

Try it Yourself »

277
www.Sohrabpoor.com

The onchange Event


The onchange event is often used in combination with validation of input
fields.

Below is an example of how to use the onchange. The upperCase() function


will be called when a user changes the content of an input field.

Example
<input type="text" id="fname" onchange="upperCase()">

Try it Yourself »

The onmouseover and onmouseout Events


The onmouseover and onmouseout events can be used to trigger a function
when the user mouses over, or out of, an HTML element:

Mouse Over Me

Try it Yourself »

The onmousedown, onmouseup and onclick


Events
The onmousedown, onmouseup, and onclick events are all parts of a mouse-
click. First when a mouse-button is clicked, the onmousedown event is
triggered, then, when the mouse-button is released, the onmouseup event is
triggered, finally, when the mouse-click is completed, the onclick event is
triggered.

Click Me

Try it Yourself »

278
www.Sohrabpoor.com

More Examples
onmousedown and onmouseup
Change an image when a user holds down the mouse button.

onload
Display an alert box when the page has finished loading.

onfocus
Change the background-color of an input field when it gets focus.

Mouse Events
Change the color of an element when the cursor moves over it.

HTML DOM Event Object Reference


For a list of all HTML DOM events, look at our complete HTML DOM Event
Object Reference.

JavaScript HTML DOM EventListener


The addEventListener() method
Example
Add an event listener that fires when a user clicks a button:

document.getElementById("myBtn").addEventListener("click", displayDate);

Try it Yourself »

The addEventListener() method attaches an event handler to the specified


element.

The addEventListener() method attaches an event handler to an element


without overwriting existing event handlers.

You can add many event handlers to one element.

You can add many event handlers of the same type to one element, i.e two
"click" events.
279
www.Sohrabpoor.com

You can add event listeners to any DOM object not only HTML elements. i.e
the window object.

The addEventListener() method makes it easier to control how the event


reacts to bubbling.

When using the addEventListener() method, the JavaScript is separated from


the HTML markup, for better readability and allows you to add event listeners
even when you do not control the HTML markup.

You can easily remove an event listener by using the removeEventListener()


method.

Syntax
element.addEventListener(event, function, useCapture);

The first parameter is the type of the event (like "click" or "mousedown").

The second parameter is the function we want to call when the event occurs.

The third parameter is a boolean value specifying whether to use event


bubbling or event capturing. This parameter is optional.

Note that you don't use the "on" prefix for the event; use "click" instead of
"onclick".

Add an Event Handler to an Element


Example
Alert "Hello World!" when the user clicks on an element:

element.addEventListener("click", function(){ alert("Hello World!"); });

Try it Yourself »

You can also refer to an external "named" function:

280
www.Sohrabpoor.com

Example
Alert "Hello World!" when the user clicks on an element:

element.addEventListener("click", myFunction);

function myFunction() {
alert ("Hello World!");
}

Try it Yourself »

Add Many Event Handlers to the Same


Element
The addEventListener() method allows you to add many events to the same
element, without overwriting existing events:

Example
element.addEventListener("click", myFunction);
element.addEventListener("click", mySecondFunction);

Try it Yourself »

You can add events of different types to the same element:

Example
element.addEventListener("mouseover", myFunction);
element.addEventListener("click", mySecondFunction);
element.addEventListener("mouseout", myThirdFunction);

Try it Yourself »

Add an Event Handler to the Window Object


The addEventListener() method allows you to add event listeners on any
HTML DOM object such as HTML elements, the HTML document, the window
object, or other objects that support events, like the xmlHttpRequest object.

281
www.Sohrabpoor.com

Example
Add an event listener that fires when a user resizes the window:

window.addEventListener("resize", function(){
document.getElementById("demo").innerHTML = sometext;
});

Try it Yourself »

Passing Parameters
When passing parameter values, use an "anonymous function" that calls the
specified function with the parameters:

Example
element.addEventListener("click", function(){ myFunction(p1, p2); });

Try it Yourself »

Event Bubbling or Event Capturing?


There are two ways of event propagation in the HTML DOM, bubbling and
capturing.

Event propagation is a way of defining the element order when an event


occurs. If you have a <p> element inside a <div> element, and the user
clicks on the <p> element, which element's "click" event should be handled
first?

In bubbling the inner most element's event is handled first and then the
outer: the <p> element's click event is handled first, then the <div>
element's click event.

In capturing the outer most element's event is handled first and then the
inner: the <div> element's click event will be handled first, then the <p>
element's click event.

With the addEventListener() method you can specify the propagation type by
using the "useCapture" parameter:

addEventListener(event, function, useCapture);


282
www.Sohrabpoor.com

The default value is false, which will use the bubbling propagation, when the
value is set to true, the event uses the capturing propagation.

Example
document.getElementById("myP").addEventListener("click",
myFunction, true);
document.getElementById("myDiv").addEventListener("click",
myFunction, true);

Try it Yourself »

The removeEventListener() method


The removeEventListener() method removes event handlers that have been
attached with the addEventListener() method:

Example
element.removeEventListener("mousemove", myFunction);

Try it Yourself »

Browser Support
The numbers in the table specifies the first browser version that fully
supports these methods.

Method

addEventListener() 1.0 9.0 1.0 1.0 7.0

removeEventListener() 1.0 9.0 1.0 1.0 7.0

Note: The addEventListener() and removeEventListener() methods are not


supported in IE 8 and earlier versions and Opera 6.0 and earlier versions.
However, for these specific browser versions, you can use the attachEvent()
method to attach an event handlers to the element, and the detachEvent()
method to remove it:

283
www.Sohrabpoor.com

element.attachEvent(event, function);
element.detachEvent(event, function);

Example
Cross-browser solution:

var x = document.getElementById("myBtn");
if (x.addEventListener) { // For all major browsers,
except IE 8 and earlier
x.addEventListener("click", myFunction);
} else if (x.attachEvent) { // For IE 8 and earlier
versions
x.attachEvent("onclick", myFunction);
}

Try it Yourself »

HTML DOM Event Object Reference


For a list of all HTML DOM events, look at our complete HTML DOM Event
Object Reference.

JavaScript HTML DOM Navigation


With the HTML DOM, you can navigate the node tree using node
relationships.

DOM Nodes
According to the W3C HTML DOM standard, everything in an HTML document
is a node:

 The entire document is a document node


 Every HTML element is an element node
 The text inside HTML elements are text nodes
 Every HTML attribute is an attribute node
 All comments are comment nodes

284
www.Sohrabpoor.com

With the HTML DOM, all nodes in the node tree can be accessed by
JavaScript.

New nodes can be created, and all nodes can be modified or deleted.

Node Relationships
The nodes in the node tree have a hierarchical relationship to each other.

The terms parent, child, and sibling are used to describe the relationships.

 In a node tree, the top node is called the root (or root node)
 Every node has exactly one parent, except the root (which has no
parent)
 A node can have a number of children
 Siblings (brothers or sisters) are nodes with the same parent

<html>

<head>
<title>DOM Tutorial</title>
</head>

<body>
<h1>DOM Lesson one</h1>
<p>Hello world!</p>
</body>

</html>

285
www.Sohrabpoor.com

From the HTML above you can read:

 <html> is the root node


 <html> has no parents
 <html> is the parent of <head> and <body>
 <head> is the first child of <html>
 <body> is the last child of <html>

and:

 <head> has one child: <title>


 <title> has one child (a text node): "DOM Tutorial"
 <body> has two children: <h1> and <p>
 <h1> has one child: "DOM Lesson one"
 <p> has one child: "Hello world!"
 <h1> and <p> are siblings

Navigating Between Nodes


You can use the following node properties to navigate between nodes with
JavaScript:

 parentNode
 childNodes[nodenumber]
 firstChild
 lastChild
 nextSibling
 previousSibling

286
www.Sohrabpoor.com

Warning !
A common error in DOM processing is to expect an element node to contain
text.

In this example: <title>DOM Tutorial</title>, the element node <title>


does not contain text. It contains a text node with the value "DOM Tutorial".

The value of the text node can be accessed by the


node's innerHTML property, or the nodeValue.

Child Nodes and Node Values


In addition to the innerHTML property, you can also use the childNodes and
nodeValue properties to get the content of an element.

The following example collects the node value of an <h1> element and
copies it into a <p> element:

Example
<html>
<body>

<h1 id="intro">My First Page</h1>

<p id="demo">Hello!</p>

<script>
var myText = document.getElementById("intro").childNodes[0].nodeValue;
document.getElementById("demo").innerHTML = myText;
</script>

</body>
</html>

Try it Yourself »

In the example above, getElementById is a method, while childNodes and


nodeValue are properties.

In this tutorial we use the innerHTML property. However, learning the


method above is useful for understanding the tree structure and the
navigation of the DOM.

287
www.Sohrabpoor.com

Using the firstChild property is the same as using childNodes[0]:

Example
<html>
<body>

<h1 id="intro">My First Page</h1>

<p id="demo">Hello World!</p>

<script>
myText = document.getElementById("intro").firstChild.nodeValue;
document.getElementById("demo").innerHTML = myText;
</script>

</body>
</html>

Try it Yourself »

DOM Root Nodes


There are two special properties that allow access to the full document:

 document.body - The body of the document


 document.documentElement - The full document

Example
<html>
<body>

<p>Hello World!</p>
<div>
<p>The DOM is very useful!</p>
<p>This example demonstrates the <b>document.body</b> property.</p>
</div>

<script>
alert(document.body.innerHTML);
</script>

</body>
</html>

Try it Yourself »

288
www.Sohrabpoor.com

Example
<html>
<body>

<p>Hello World!</p>
<div>
<p>The DOM is very useful!</p>
<p>This example demonstrates
the <b>document.documentElement</b> property.</p>
</div>

<script>
alert(document.documentElement.innerHTML);
</script>

</body>
</html>

Try it Yourself »

The nodeName Property


The nodeName property specifies the name of a node.

 nodeName is read-only
 nodeName of an element node is the same as the tag name
 nodeName of an attribute node is the attribute name
 nodeName of a text node is always #text
 nodeName of the document node is always #document

Note: nodeName always contains the uppercase tag name of an HTML


element.

The nodeValue Property


The nodeValue property specifies the value of a node.

 nodeValue for element nodes is undefined


 nodeValue for text nodes is the text itself
 nodeValue for attribute nodes is the attribute value

289
www.Sohrabpoor.com

The nodeType Property


The nodeType property returns the type of node. nodeType is read only.

The most important node types are:

Element type NodeType

Element 1

Attribute 2

Text 3

Comment 8

Document 9

JavaScript HTML DOM Elements


(Nodes)
Adding and Removing Nodes (HTML Elements)

Creating New HTML Elements (Nodes)


To add a new element to the HTML DOM, you must create the element
(element node) first, and then append it to an existing element.

290
www.Sohrabpoor.com

Example
<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>

<script>
var para = document.createElement("p");
var node = document.createTextNode("This is new.");
para.appendChild(node);

var element = document.getElementById("div1");


element.appendChild(para);
</script>

Try it Yourself »

Example Explained
This code creates a new <p> element:

var para = document.createElement("p");

To add text to the <p> element, you must create a text node first. This code
creates a text node:

var node = document.createTextNode("This is a new paragraph.");

Then you must append the text node to the <p> element:

para.appendChild(node);

Finally you must append the new element to an existing element.

This code finds an existing element:

var element = document.getElementById("div1");

This code appends the new element to the existing element:

element.appendChild(para);

291
www.Sohrabpoor.com

Creating new HTML Elements - insertBefore()


The appendChild() method in the previous example, appended the new
element as the last child of the parent.

If you don't want that you can use the insertBefore() method:

Example
<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>

<script>
var para = document.createElement("p");
var node = document.createTextNode("This is new.");
para.appendChild(node);

var element = document.getElementById("div1");


var child = document.getElementById("p1");
element.insertBefore(para,child);
</script>

Try it Yourself »

Removing Existing HTML Elements


To remove an HTML element, you must know the parent of the element:

Example
<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>

<script>
var parent = document.getElementById("div1");
var child = document.getElementById("p1");
parent.removeChild(child);
</script>

Try it Yourself »

292
www.Sohrabpoor.com

The method node.remove() is implemented in the DOM 4 specification.


But because of poor browser support, you should not use it.

Example Explained
This HTML document contains a <div> element with two child nodes (two
<p> elements):

<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>

Find the element with id="div1":

var parent = document.getElementById("div1");

Find the <p> element with id="p1":

var child = document.getElementById("p1");

Remove the child from the parent:

parent.removeChild(child);

It would be nice to be able to remove an element without referring to the


parent.
But sorry. The DOM needs to know both the element you want to remove,
and its parent.

Here is a common workaround: Find the child you want to remove, and use
its parentNode property to find the parent:

var child = document.getElementById("p1");


child.parentNode.removeChild(child);

Replacing HTML Elements


To replace an element to the HTML DOM, use the replaceChild() method:

293
www.Sohrabpoor.com

Example
<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>

<script>
var para = document.createElement("p");
var node = document.createTextNode("This is new.");
para.appendChild(node);

var parent = document.getElementById("div1");


var child = document.getElementById("p1");
parent.replaceChild(para,child);
</script>

Try it Yourself »

JavaScript HTML DOM Node List


A node list is a collection of nodes

HTML DOM Node List


The getElementsByTagName() method returns a node list. A node list is an
array-like collection of nodes.

The following code selects all <p> nodes in a document:

Example
var x = document.getElementsByTagName("p");

The nodes can be accessed by an index number. To access the second <p>
node you can write:

y = x[1];

Try it Yourself »

Note: The index starts at 0.

294
www.Sohrabpoor.com

HTML DOM Node List Length


The length property defines the number of nodes in a node list:

Example
var myNodelist = document.getElementsByTagName("p");
document.getElementById("demo").innerHTML = myNodelist.length;

Try it Yourself »

Example explained:

1. Get all <p> elements in a node list


2. Display the length of the node list

The length property is useful when you want to loop through the nodes in a
node list:

Example
Change the background color of all <p> elements in a node list:

var myNodelist = document.getElementsByTagName("p");


var i;
for (i = 0; i < myNodelist.length; i++) {
myNodelist[i].style.backgroundColor = "red";
}

Try it Yourself »

A node list is not an array!


A node list may look like an array, but it is not. You can loop through the
node list and refer to its nodes like an array. However, you cannot use Array
Methods, like valueOf() or join() on the node list.

JavaScript Window - The Browser


Object Model
The Browser Object Model (BOM) allows JavaScript to "talk to" the
browser.

295
www.Sohrabpoor.com

The Browser Object Model (BOM)


There are no official standards for the Browser Object Model (BOM).

Since modern browsers have implemented (almost) the same methods and
properties for JavaScript interactivity, it is often referred to, as methods and
properties of the BOM.

The Window Object


The window object is supported by all browsers. It represents the browser's
window.

All global JavaScript objects, functions, and variables automatically become


members of the window object.

Global variables are properties of the window object.

Global functions are methods of the window object.

Even the document object (of the HTML DOM) is a property of the window
object:

window.document.getElementById("header");

is the same as:

document.getElementById("header");

Window Size
Two properties can be used to determine the size of the browser window.

Both properties return the sizes in pixels:

 window.innerHeight - the inner height of the browser window (in


pixels)
 window.innerWidth - the inner width of the browser window (in pixels)

The browser window (the browser viewport) is NOT including toolbars and
scrollbars.

296
www.Sohrabpoor.com

For Internet Explorer 8, 7, 6, 5:

 document.documentElement.clientHeight
 document.documentElement.clientWidth
 or
 document.body.clientHeight
 document.body.clientWidth

A practical JavaScript solution (covering all browsers):

Example
var w = window.innerWidth
|| document.documentElement.clientWidth
|| document.body.clientWidth;

var h = window.innerHeight
|| document.documentElement.clientHeight
|| document.body.clientHeight;

Try it Yourself »

The example displays the browser window's height and width: (NOT including
toolbars/scrollbars)

Other Window Methods


Some other methods:

 window.open() - open a new window


 window.close() - close the current window
 window.moveTo() -move the current window
 window.resizeTo() -resize the current window

JavaScript Window Screen


The window.screen object contains information about the user's screen.

Window Screen
The window.screen object can be written without the window prefix.

297
www.Sohrabpoor.com

Properties:

 screen.width
 screen.height
 screen.availWidth
 screen.availHeight
 screen.colorDepth
 screen.pixelDepth

Window Screen Width


The screen.width property returns the width of the visitor's screen in pixels.

Example
Display the width of the screen in pixels:

document.getElementById("demo").innerHTML =
"Screen Width: " + screen.width;

Result will be:

Screen Width: 1360

Try it Yourself »

Window Screen Height


The screen.height property returns the height of the visitor's screen in pixels.

Example
Display the height of the screen in pixels:

document.getElementById("demo").innerHTML =
"Screen Height: " + screen.height;

Result will be:

Screen Height: 768

Try it Yourself »

298
www.Sohrabpoor.com

Window Screen Available Width


The screen.availWidth property returns the width of the visitor's screen, in
pixels, minus interface features like the Windows Taskbar.

Example
Display the available width of the screen in pixels:

document.getElementById("demo").innerHTML =
"Available Screen Width: " + screen.availWidth;

Result will be:

Available Screen Width: 1360

Try it Yourself »

Window Screen Available Height


The screen.availHeight property returns the height of the visitor's screen, in
pixels, minus interface features like the Windows Taskbar.

Example
Display the available height of the screen in pixels:

document.getElementById("demo").innerHTML =
"Available Screen Height: " + screen.availHeight;

Result will be:

Available Screen Height: 728

Try it Yourself »

299
www.Sohrabpoor.com

Window Screen Color Depth


The screen.colorDepth property returns the number of bits used to display
one color.

All modern computers use 24 bit or 32 bit hardware for color resolution:

 24 bits = 16,777,216 different "True Colors"


 32 bits = 4,294,967,296 different "Deep Colors"

Older computers used 16 bits: 65,536 different "High Colors" resolution.

Very old computers, and old cell phones used 8 bits: 256 different "VGA
colors".

Example
Display the color depth of the screen in bits:

document.getElementById("demo").innerHTML =
"Screen Color Depth: " + screen.colorDepth;

Result will be:

Screen Color Depth: 24

Try it Yourself »

The #rrggbb (rgb) values used in HTML represents "True Colors"


(16,777,216 different colors)

Window Screen Pixel Depth


The screen.pixelDepth property returns the pixel depth of the screen.

Example
Display the pixel depth of the screen in bits:

document.getElementById("demo").innerHTML =
"Screen Pixel Depth: " + screen.pixelDepth;

300
www.Sohrabpoor.com

Result will be:

Screen Pixel Depth: 24

Try it Yourself »

For modern computers, Color Depth and Pixel Depth are equal.

JavaScript Window Location


The window.location object can be used to get the current page address
(URL) and to redirect the browser to a new page.

Window Location
The window.location object can be written without the window prefix.

Some examples:

 window.location.href returns the href (URL) of the current page


 window.location.hostname returns the domain name of the web host
 window.location.pathname returns the path and filename of the
current page
 window.location.protocol returns the web protocol used (http:// or
https://)
 window.location.assign loads a new document

Window Location Href


The window.location.href property returns the URL of the current page.

Example
Display the href (URL) of the current page:

document.getElementById("demo").innerHTML =
"Page location is " + window.location.href;

301
www.Sohrabpoor.com

Result is:

Page location is http://www.w3schools.com/js/js_window_location.asp

Try it Yourself »

Window Location Hostname


The window.location.hostname property returns the name of the internet
host (of the current page).

Example
Display the name of the host:

document.getElementById("demo").innerHTML =
"Page hostname is " + window.location.hostname;

Result is:

Page hostname is www.w3schools.com

Try it Yourself »

Window Location Pathname


The window.location.pathname property returns the pathname of the
current page.

Example
Display the path name of the current URL:

document.getElementById("demo").innerHTML =
"Page path is " + window.location.pathname;

Result is:

/js/js_window_location.asp

Try it Yourself »

302
www.Sohrabpoor.com

Window Location Protocol


The window.location.protocol property returns the web protocol of the
page.

Example
Display the web protocol:

document.getElementById("demo").innerHTML =
"Page protocol is " + window.location.protocol;

Result is:

Page protocol is http:

Try it Yourself »

Window Location Assign


The window.location.assign() method loads a new document.

Example
Load a new document:

<html>
<head>
<script>
function newDoc() {
window.location.assign("http://www.w3schools.com")
}
</script>
</head>
<body>

<input type="button" value="Load new document" onclick="newDoc()">

</body>
</html>

Try it Yourself »

303
www.Sohrabpoor.com

JavaScript Window History


The window.history object contains the browsers history.

Window History
The window.history object can be written without the window prefix.

To protect the privacy of the users, there are limitations to how JavaScript
can access this object.

Some methods:

 history.back() - same as clicking back in the browser


 history.forward() - same as clicking forward in the browser

Window History Back


The history.back() method loads the previous URL in the history list.

This is the same as clicking the Back button in the browser.

Example
Create a back button on a page:

<html>
<head>
<script>
function goBack() {
window.history.back()
}
</script>
</head>
<body>
<input type="button" value="Back" onclick="goBack()">
</body>
</html>

The output of the code above will be:

304
www.Sohrabpoor.com

Window History Forward


The history forward() method loads the next URL in the history list.

This is the same as clicking the Forward button in the browser.

Example
Create a forward button on a page:

<html>
<head>
<script>
function goForward() {
window.history.forward()
}
</script>
</head>
<body>

<input type="button" value="Forward" onclick="goForward()">

</body>
</html>

The output of the code above will be:

JavaScript Window Navigator


The window.navigator object contains information about the visitor's
browser.

Window Navigator
The window.navigator object can be written without the window prefix.

Some examples:

 navigator.appName
 navigator.appCodeName
 navigator.platform

305
www.Sohrabpoor.com

Navigator Cookie Enabled


The property cookieEnabled returns true if cookies are enabled, otherwise
false:

Example
<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML =
"Cookies Enabled is " + navigator.cookieEnabled;
</script>

Try it Yourself »

The Browser Names


The properties appName and appCodeName return the name of the
browser:

Example
<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML =
"Name is " + navigator.appName + ". Code name is " +
navigator.appCodeName;
</script>

Try it Yourself »

Did you know?


IE11, Chrome, Firefox, and Safari return appName "Netscape".

Chrome, Firefox, IE, Safari, and Opera all return appCodeName "Mozilla".

306
www.Sohrabpoor.com

The Browser Engine


The property product returns the engine name of the browser:

Example
<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = navigator.product;
</script>

Try it Yourself »

The Browser Version I


The property appVersion returns version information about the browser:

Example
<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = navigator.appVersion;
</script>

Try it Yourself »

The Browser Version II


The property userAgent also returns version information about the
browser:

Example
<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = navigator.userAgent;
</script>

Try it Yourself »

307
www.Sohrabpoor.com

Warning !!!
The information from the navigator object can often be misleading, and
should not be used to detect browser versions because:

 Different browsers can use the same name


 The navigator data can be changed by the browser owner
 Some browsers misidentify themselves to bypass site tests
 Browsers cannot report new operating systems, released later than the
browser

The Browser Platform


The property platform returns the browser platform (operating system):

Example
<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = navigator.platform;
</script>

Try it Yourself »

The Browser Language


The property language returns the browser's language:

Example
<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = navigator.language;
</script>

Try it Yourself »

308
www.Sohrabpoor.com

Is Java Enabled?
The method javaEnabled() returns true if Java is enabled:

Example
<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = navigator.javaEnabled();
</script>

Try it Yourself »

JavaScript Popup Boxes


JavaScript has three kind of popup boxes: Alert box, Confirm box, and
Prompt box.

Alert Box
An alert box is often used if you want to make sure information comes
through to the user.

When an alert box pops up, the user will have to click "OK" to proceed.

Syntax
window.alert("sometext");

The window.alert() method can be written without the window prefix.

Example
alert("I am an alert box!");
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
alert("I am an alert box!");
}
</script>
Try it Yourself »

309
www.Sohrabpoor.com

Confirm Box
A confirm box is often used if you want the user to verify or accept
something.

When a confirm box pops up, the user will have to click either "OK" or
"Cancel" to proceed.

If the user clicks "OK", the box returns true. If the user clicks "Cancel", the
box returns false.

Syntax
window.confirm("sometext");

The window.confirm() method can be written without the window prefix.

Example
var r = confirm("Press a button");
if (r == true) {
x = "You pressed OK!";
} else {
x = "You pressed Cancel!";
}

Try it Yourself »

Prompt Box
A prompt box is often used if you want the user to input a value before
entering a page.

When a prompt box pops up, the user will have to click either "OK" or
"Cancel" to proceed after entering an input value.

If the user clicks "OK" the box returns the input value. If the user clicks
"Cancel" the box returns null.

Syntax
window.prompt("sometext","defaultText");

The window.prompt() method can be written without the window prefix.

310
www.Sohrabpoor.com

Example
var person = prompt("Please enter your name", "Harry Potter");
if (person != null) {
document.getElementById("demo").innerHTML =
"Hello " + person + "! How are you today?";
}

Try it Yourself »

Line Breaks
To display line breaks inside a popup box, use a back-slash followed by the
character n.

Example
alert("Hello\nHow are you?");

Try it Yourself »

JavaScript Timing Events


Timing Events
The window object allows execution of code at specified time intervals.

These time intervals are called timing events.

The two key methods to use with JavaScript are:

 setTimeout(function, milliseconds)
Executes a function, after waiting a specified number of milliseconds.
 setInterval(function, milliseconds)
Same as setTimeout(), but repeats the execution of the function
continuously.

The setTimeout() and setInterval() are both methods of the HTML DOM
Window object.

311
www.Sohrabpoor.com

The setTimeout() Method


window.setTimeout(function, milliseconds);

The window.setTimeout() method can be written without the window


prefix.

The first parameter is a function to be executed.

The second parameter indicates the number of milliseconds before execution.

Example
Click a button. Wait 3 seconds, and the page will alert "Hello":

<button onclick="setTimeout(myFunction, 3000)">Try it</button>

<script>
function myFunction() {
alert('Hello');
}
</script>

Try it Yourself »

How to Stop the Execution?


The clearTimeout() method stops the execution of the function specified in
setTimeout().

window.clearTimeout(timeoutVariable)

The window.clearTimeout() method can be written without the window


prefix.

The clearTimeout() method uses the variable returned from setTimeout():

myVar = setTimeout(function, milliseconds);


clearTimeout(myVar);

If the function has not already been executed, you can stop the execution by
calling the clearTimeout() method:

312
www.Sohrabpoor.com

Example
Same example as above, but with an added "Stop" button:

<button onclick="myVar = setTimeout(myFunction, 3000)">Try it</button>

<button onclick="clearTimeout(myVar)">Stop it</button>

Try it Yourself »

The setInterval() Method


The setInterval() method repeats a given function at every given time-
interval.

window.setInterval(function, milliseconds);

The window.setInterval() method can be written without the window


prefix.

The first parameter is the function to be executed.

The second parameter indicates the length of the time-interval between each
execution.

This example executes a function called "myTimer" once every second (like a
digital watch).

Example
Display the current time:

var myVar = setInterval(myTimer, 1000);

function myTimer() {
var d = new Date();
document.getElementById("demo").innerHTML = d.toLocaleTimeString();
}

Try it Yourself »

There are 1000 milliseconds in one second.

313
www.Sohrabpoor.com

How to Stop the Execution?


The clearInterval() method stops the executions of the function specified in
the setInterval() method.

window.clearInterval(timerVariable)

The window.clearInterval() method can be written without the window


prefix.

The clearInterval() method uses the variable returned from setInterval():

myVar = setInterval(function, milliseconds);


clearInterval(myVar);

Example
Same example as above, but we have added a "Stop time" button:

<p id="demo"></p>

<button onclick="clearInterval(myVar)">Stop time</button>

<script>
var myVar = setInterval(myTimer, 1000);
function myTimer() {
var d = new Date();
document.getElementById("demo").innerHTML = d.toLocaleTimeString();
}
</script>

Try it Yourself »

More Examples
Another simple timing

A clock created with a timing event

314
www.Sohrabpoor.com

JavaScript Cookies
Cookies let you store user information in web pages.

What are Cookies?


Cookies are data, stored in small text files, on your computer.

When a web server has sent a web page to a browser, the connection is shut
down, and the server forgets everything about the user.

Cookies were invented to solve the problem "how to remember information


about the user":

 When a user visits a web page, his name can be stored in a cookie.
 Next time the user visits the page, the cookie "remembers" his name.

Cookies are saved in name-value pairs like:

username = John Doe

When a browser requests a web page from a server, cookies belonging to the
page is added to the request. This way the server gets the necessary data to
"remember" information about users.

Create a Cookie with JavaScript


JavaScript can create, read, and delete cookies with
the document.cookie property.

With JavaScript, a cookie can be created like this:

document.cookie = "username=John Doe";

You can also add an expiry date (in UTC time). By default, the cookie is
deleted when the browser is closed:

document.cookie = "username=John Doe; expires=Thu, 18 Dec 2013 12:00:00


UTC";

With a path parameter, you can tell the browser what path the cookie
belongs to. By default, the cookie belongs to the current page.

315
www.Sohrabpoor.com

document.cookie = "username=John Doe; expires=Thu, 18 Dec 2013 12:00:00


UTC; path=/";

Read a Cookie with JavaScript


With JavaScript, cookies can be read like this:

var x = document.cookie;

document.cookie will return all cookies in one string much like:


cookie1=value; cookie2=value; cookie3=value;

Change a Cookie with JavaScript


With JavaScript, you can change a cookie the same way as you create it:

document.cookie = "username=John Smith; expires=Thu, 18 Dec 2013 12:00:00


UTC; path=/";

The old cookie is overwritten.

Delete a Cookie with JavaScript


Deleting a cookie is very simple. Just set the expires parameter to a passed
date:

document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC";

Note that you don't have to specify a cookie value when you delete a cookie.

The Cookie String


The document.cookie property looks like a normal text string. But it is not.

Even if you write a whole cookie string to document.cookie, when you read it
out again, you can only see the name-value pair of it.

316
www.Sohrabpoor.com

If you set a new cookie, older cookies are not overwritten. The new cookie is
added to document.cookie, so if you read document.cookie again you will get
something like:

cookie1 = value; cookie2 = value;

Display All Cookies Create Cookie 1 Create Cookie 2 Delete Cookie 1 Delete
Cookie 2

If you want to find the value of one specified cookie, you must write a
JavaScript function that searches for the cookie value in the cookie string.

JavaScript Cookie Example


In the example to follow, we will create a cookie that stores the name of a
visitor.

The first time a visitor arrives to the web page, he will be asked to fill in his
name. The name is then stored in a cookie.

The next time the visitor arrives at the same page, he will get a welcome
message.

For the example we will create 3 JavaScript functions:

1. A function to set a cookie value


2. A function to get a cookie value
3. A function to check a cookie value

A Function to Set a Cookie


First, we create a function that stores the name of the visitor in a cookie
variable:

Example
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+ d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}

317
www.Sohrabpoor.com

Example explained:

The parameters of the function above are the name of the cookie (cname),
the value of the cookie (cvalue), and the number of days until the cookie
should expire (exdays).

The function sets a cookie by adding together the cookiename, the cookie
value, and the expires string.

A Function to Get a Cookie


Then, we create a function that returns the value of a specified cookie:

Example
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i = 0; i <ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length,c.length);
}
}
return "";
}

Function explained:

Take the cookiename as parameter (cname).

Create a variable (name) with the text to search for (cname + "=").

Split document.cookie on semicolons into an array called ca (ca =


document.cookie.split(';')).

Loop through the ca array (i=0;i<ca.length;i++), and read out each value
c=ca[i]).

If the cookie is found (c.indexOf(name) == 0), return the value of the cookie
(c.substring(name.length,c.length).

If the cookie is not found, return "".

318
www.Sohrabpoor.com

A Function to Check a Cookie


Last, we create the function that checks if a cookie is set.

If the cookie is set it will display a greeting.

If the cookie is not set, it will display a prompt box, asking for the name of
the user, and stores the username cookie for 365 days, by calling the
setCookie function:

Example
function checkCookie() {
var username=getCookie("username");
if (username!="") {
alert("Welcome again " + username);
} else {
username = prompt("Please enter your name:", "");
if (username != "" && username != null) {
setCookie("username", username, 365);
}
}
}

All Together Now


Example
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}

function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);

319
www.Sohrabpoor.com

}
}
return "";
}

function checkCookie() {
var user = getCookie("username");
if (user != "") {
alert("Welcome again " + user);
} else {
user = prompt("Please enter your name:", "");
if (user != "" && user != null) {
setCookie("username", user, 365);
}
}
}

Try it Yourself »

The example above runs the checkCookie() function when the page loads.

JavaScript Examples
What can JavaScript do?
JavaScript can change HTML content
JavaScript can change HTML attributes
JavaScript can change CSS style
JavaScript can hide HTML elements
JavaScript can show hidden HTML elements

Examples explained

JavaScript Output
Writing into an window alert box
Writing into the HTML output
Writing into an HTML element
Writing into the browser console

Output explained

320
www.Sohrabpoor.com

Where to Insert JavaScript


JavaScript in <head>
JavaScript in <body>
JavaScript in an external file

Placement explained

JavaScript Syntax
JavaScript statements
JavaScript numbers
JavaScript strings
JavaScript expressions
JavaScript keywords
JavaScript variables
JavaScript assignment
JavaScript operators
JavaScript comments
JavaScript is case sensitive

Syntax explained

JavaScript Statements
JavaScript statements are commands to the browser
JavaScript code is a sequence of statements
JavaScript statements are separated with semicolon
Multiple statement on one line is allowed
JavaScript statements can be grouped together in code blocks
You can break a code line after an operator or a comma.

Statements explained

321
www.Sohrabpoor.com

JavaScript Comments
Single line comments
Single line comments at the end of a line
Multiple lines comments
Single line comment to prevent execution
Multiple lines comment to prevent execution

Comments explained

JavaScript Variables
JavaScript variables
JavaScript variables as algebra
JavaScript numbers and strings
JavaScript var keyword.
Declaring many variables in one statement
Declaring many variables multiline
A variable without a value returns the value undefined
Re-declaring a variable will not destroy the value
Adding JavaScript numbers
Adding JavaScript strings
Adding strings and numbers

Variables explained

JavaScript Arithmetic
The addition (+) operator
The subtraction (-) operator
The multiplication (*) operator
The division (/) operator
The modulus (%) operator
The increment (++) operator
The decrement (--) operator

Arithmetic explained

322
www.Sohrabpoor.com

JavaScript Assignment
The = assignment operator
The += assignment operator
The -= assignment operator
The *= assignment operator
The /= assignment operator
The %= assignment operator

Assignment explained

JavaScript String Concatenation


Adding two strings together using the concatenating (+) operator
Adding two strings together with a space in the first string
Adding two strings together with a space in between
Adding two strings together using using the += operator
Adding strings and numbers

Concatenation explained

JavaScript Data Types


Declare (create) strings
Declare (create) numbers
Declare (create) an array
Declare (create) an object
Find the type of a variable
Adding two numbers and a string
Adding a string and two numbers
An undefined variable
An empty variable

Data types explained

323
www.Sohrabpoor.com

JavaScript Objects
Create a JavaScript variable
Create a JavaScript object
Create a person object (single line)
Create a person object (multiple lines)
Access object properties using .property
Access object properties using [property]
Access a function property as a method
Access a function property as a property

Objects explained

JavaScript Functions
A simple function
A function with an argument
A function with an argument 2
A function that returns a value
A function that converts Fahrenheit to Celsius
A function call without ()

Functions explained

JavaScript Events
An onclick event changes an HTML element
An onclick event changes its own element
An onclick event calls a function

Events explained

JavaScript Strings
Strings can be written with single or double quotes.
Show some string examples
Backslash before quotes accepts quotes as quotes.
Find the length of a string

324
www.Sohrabpoor.com

You can break text string with a backslash.


You cannot break code with a backslash.
Find the position of the first occurrence of a text in a string - indexOf()
Search for a text in a string and return the text if found - match()
Replace characters in a string - replace()
Convert string to upper case - toUpperCase()
Convert string to lower case - toLowerCase()
Split a string into an array - split()

Strings explained

JavaScript Numbers
Number are considered accurate only up to 15 digits
Floating point arithmetic is not always 100% accurate
But it helps to multiply and divide by 10
Constants, preceded by 0x, are interpreted as hexadecimal
The toString() method can output numbers as hex, octal, and binary
JavaScript will generate Infinity if you calculate a too large number
Division by zero generates Infinity
A number divided by a string is not a number

Numbers explained

JavaScript Maths
Use Math.random() to return a random number between 0 and 1
Use Math.round() to round a number
Use Math.ceil() to round a number (up)
Use Math.floor() to round a number (down)
Use Math.floor() and random() to return a random integer
Use Math.max() to return the number with the highest value
Use Math.min() to return the number with the lowest value
Convert Celsius to Fahrenheit

Maths explained

325
www.Sohrabpoor.com

JavaScript Dates
Use Date() to display today's date and time
Use getFullYear() display the year
Use getTime() to calculate the number of milliseconds since 1970
Use setFullYear() to set a specific date
Use toUTCString() to convert today's date (according to UTC) to a string
Use getDay() to display the weekday as a number
Use getDay() and an array to display the weekday as a name
Display a clock

Dates explained

JavaScript Arrays
Create an array
Join two arrays - concat()
Join three arrays - concat()
Join all elements of an array into a string - join()
Remove the last element of an array - pop()
Add new elements to the end of an array - push()
Reverse the order of the elements in an array - reverse()
Remove the first element of an array - shift()
Select elements from an array - slice()
Sort an array (alphabetically and ascending) - sort()
Sort numbers (numerically and ascending) - sort()
Sort numbers (numerically and descending) - sort()
Sort numbers (alphabetically and numerically) - sort()
Sort numbers in random order - sort()
Sort objects by numeric properties - sort()
Sort objects by string properties - sort()
Add an element to position 2 in an array - splice()
Convert an array to a string - toString()
Add new elements to the beginning of an array - unshift()

Arrays explained

326
www.Sohrabpoor.com

JavaScript Type Conversion


Display the typeof all variable types
Display the constructor of all variable types
Convert a number to a string using String()
Convert a number to a string using toString()
Find out if a variable is an array
Find out if a variable is an date

Type Conversion Explained

JavaScript Booleans
Display the value of Boolean(10 > 9)
Display the value of 10 > 9
Everything with a real value is true
The Boolean value of zero is false
The Boolean value of minus zero is false
The Boolean value of an empty string is false
The Boolean value of undefined is false
The Boolean value of null is false
The Boolean value of false is false
The Boolean value of NaN is false

Booleans explained

JavaScript Comparisons
Assign 5 to x, and display the value of (x == 8)
Assign 5 to x, and display the value of (x == 5)
Assign 5 to x, and display the value of (x === 5)
Assign 5 to x, and display the value of (x === "5")
Assign 5 to x, and display the value of (x != 8)
Assign 5 to x, and display the value of (x !== 5)
Assign 5 to x, and display the value of (x !== "5")
Assign 5 to x, and display the value of (x > 8)
Assign 5 to x, and display the value of (x < 8)
Assign 5 to x, and display the value of (x >= 8)
Assign 5 to x, and display the value of (x <= 8)

Comparisons explained

327
www.Sohrabpoor.com

JavaScript Conditionals
The if statement
The else statement
The else if statement
Random link
Switch statement

Conditionals explained

JavaScript Loops
For loop
Looping through HTML headers
While loop
Do While loop
Break a loop
Break and continue a loop
Use a for...in statement to loop through the elements of an object

Loops explained

JavaScript Error Handling


The try...catch statement
The try...catch statement with a confirm box
The onerror event

Errors explained

JavaScript Regular Expressions


Search for an expression in a string
Search for an expression and replace it

Regular Expressions Explained

328
www.Sohrabpoor.com

JavaScript Objects
Creating a JavaScript variable
Creating a JavaScript object
Creating a JavaScript object (single line)
Creating a JavaScript object (multiple lines)
Creating a JavaScript object using new
Creating JavaScript objects using a constructor
Creating built-in JavaScript objects
The best way to create JavaScript variables
JavaScript objects are mutable

Objects explained

JavaScript Object Properties


Accessing properties using .property
Accessing properties using [property]
Accessing properties using for in
Adding new properties to existing objects
Deleting properties from objects

Object Properties explained

JavaScript HTML DOM Examples


Examples of using JavaScript to access and manipulate DOM objects.

The Document Object


Display all name/value pairs of cookies in a document
Display the domain name of the server that loaded the document
Display the date and time the document was last modified
Display the URL of the document that loaded the current document
Display the title of a document
Display the full URL of a document
Replace the content of a document
Open a new window, and add some content
Display the number of elements with a specific name
Display the number of elements with a specific tag name

Document Object Explained

329
www.Sohrabpoor.com

The Anchors Collection


Find the number of anchors in a document
Find the innerHTML of the first anchor in a document

The Links Collection


Display the number of links in a document
Display the href attribute of the first link in a document

The Forms Collection


Find the number of forms in a document
Find the name of the first form in a document

The Images Collection


Return the number of images in a document
Return the id of the first image in a document

CSS Manipulation
Change the visibility of an HTML element
Change the background color of an HTML element

330
www.Sohrabpoor.com

JavaScript HTML Input Examples

Examples of using JavaScript to access and manipulate HTML input


objects.

Button Object
Disable a button
Find the name of a button
Find the type of a button
Find the value of a button
Find the text displayed on a button
Find the id of the form a button belongs to

Form Object
Submit a form
Reset a form

Find the value of each element in a form


Find the accepted character set of a form
Find the action attribute of a form
Find the value of the enctype attribute in a form
Find the number of elements in a form
Find the method for sending form data
Find the name of a form
Find the target of a form

Option and Select Objects


Disable and enable a dropdown list
Get the id of the form that contains the dropdown list
Get the number of options in the dropdown list
Turn the dropdown list into a multiline list
Select multiple options in a dropdown list

331
www.Sohrabpoor.com

Display the selected option in a dropdown list


Display all options from a dropdown list
Display the index of the selected option in a dropdown list
Change the text of the selected option
Remove options from a dropdown list

JavaScript HTML Objects Examples


Examples of using JavaScript to access and manipulate HTML objects.

Anchor Object
Find the value of the href attribute of a link
Find the value of the hreflang attribute of a link
Find the value of the id attribute a link
Find the value of the rel attribute of a link
Find the value of the target attribute of a link
Find the value of the type attribute of a link

Area Object
Find the alternate text of an image-map area
Find the coordinates of an area
Find the shape of an area
Find the href of an area
Find the protocol part of the href attribute of an area
Find the hostname part of the href attribute of an area
Find the port number part of the href attribute of an area
Find the pathname part of the href attribute of an area
Find the querystring part of the href attribute of an area
Find the hash part of the href attribute of an area
Find the value of the target attribute of an area

332
www.Sohrabpoor.com

Base Object
Find the base URL for all relative URLs on a page
Find the base target for all links on a page

IFrame Object
Change the background color of an iframe
Find the height of an iframe
Find the value of the name attribute of an iframe
Find the source (src) attribute of an iframe
Change the source (src) attribute of an iframe

Image Object
Find the alternate text of an image
Find the height of an image
Click to display a high-resolution version of an image
Find the source (src) of an image
Change the source of an image
Change the source of the lightbulb
Find the value of the usemap attribute of an image

Table Objects
Change the width of a table border
Change the padding of a table
Find the innerHTML of a cell
Create a caption for a table
Delete rows in a table
Add rows to a table
Change the content of a table cell

333
www.Sohrabpoor.com

JavaScript HTML DOM


Events Examples
Examples of using JavaScript to react to events

Input Events
onblur - When a user leaves an input field
onchange - When a user changes the content of an input field
onchange - When a user selects a dropdown value
onfocus - When an input field gets focus
onselect - When input text is selected
onsubmit - When a user clicks the submit button
onreset - When a user clicks the reset button
onkeydown - When a user is pressing/holding down a key
onkeypress - When a user is pressing/holding down a key
onkeyup - When the user releases a key
onkeyup - When the user releases a key
onkeydown vs onkeyup - Both

Mouse Events
onmouseover/onmouseout - When the mouse passes over an element
onmousedown/onmouseup - When pressing/releasing a mouse button
onmousedown - When mouse is clicked: Alert which element
onmousedown - When mouse is clicked: Alert which button
onmousemove/onmouseout - When moving the mouse pointer over/out of an
image
onmouseover/onmouseout - When moving the mouse over/out of an image
onmouseover an image map

Click Events
Acting to the onclick event
onclick - When button is clicked
ondblclick - When a text is double-clicked

334
www.Sohrabpoor.com

Load Events
onload - When the page has been loaded
onload - When an image has been loaded
onerror - When an error occurs when loading an image
onunload - When the browser closes the document
onresize - When the browser window is resized

Others
What is the keycode of the key pressed?
What are the coordinates of the cursor?
What are the coordinates of the cursor, relative to the screen?
Was the shift key pressed?
Which event type occurred?

Examples explained

JavaScript Browser Objects Examples


Examples of using JavaScript to access and manipulate the Browser
objects.

Window Object
Open a new window when clicking on a button
Open a new window and control its appearance
Blur and Focus a new window
Close the new window
Checks whether the new window has been closed or not
Write some text to the source (parent) window
Move the new window relative to its current position
Move the new window to the specified position
Print the current page
Resize a window by the specified pixels
Resize a window to a specified size
Scroll the content by the specified number of pixels
Scroll the content to a specified position

Window explained
335
www.Sohrabpoor.com

Screen Object
The visitor's screen: Width
The visitor's screen: Height
The visitor's screen: Available Width
The visitor's screen: Available Height
The visitor's screen: Color Depth
The visitor's screen: Pixel Depth

Screen explained

Location Object
Return the hostname and port of the current URL
Return the entire URL of the current page
Return the path name of the current URL
Return the protocol portion of the current URL
Load a new document
Replace the current document
Break out of a frame

Location explained

History Object
Display the number of URLs in the history list
Create a back button on a page
Create a forward button on a page
Load a specific URL from the history list

History explained

Navigator Object
Is cookies enabled in the visitor's browser?
What is the name of the visitor's browser?
What is the engine name of the visitor's browser?
What is the version information of the visitor's browser?

336
www.Sohrabpoor.com

What is user agent information of the visitor's browser?


What is the platform of the visitor's browser?
What is the language of the visitor's browser?
Is Java enabled in the visitor's browser?

Navigator explained

Popup Boxes
Display an alert box
Demonstrate line breaks in an alert box
Display a confirm box
Display a prompt box

Popup explained

Timing
Simple timing
Another simple timing
Timing event in an infinite loop
Timing event in an infinite loop - with a Stop button
A clock created with a timing event
Set and stop a timer with setInterval() and clearInterval()

Timing explained

Cookies
Create a welcome cookie

Cookies explained

337
www.Sohrabpoor.com

JavaScript Quiz Test


You can test your JavaScript skills with W3Schools' Quiz.

The Test
The test contains 25 questions and there is no time limit.

The test is not official, it's just a nice way to see how much you know, or
don't know, about JavaScript.

Count Your Score


You will get 1 point for each correct answer. At the end of the Quiz, your
total score will be displayed. Maximum score is 25 points.

Start the Quiz


Good luck!

Start the Quiz

W3Schools' Online Certification


The perfect solution for professionals who need to balance work, family, and
career building.

More than 10 000 certificates already issued!

Get Your Certificate »

The HTML Certificate documents your knowledge of HTML.

The CSS Certificate documents your knowledge of advanced CSS.

338
www.Sohrabpoor.com

The JavaScript Certificate documents your knowledge of JavaScript and HTML


DOM.

The jQuery Certificate documents your knowledge of jQuery.

The PHP Certificate documents your knowledge of PHP and SQL (MySQL).

The XML Certificate documents your knowledge of XML, XML DOM and XSLT.

The Bootstrap Certificate documents your knowledge of the Bootstrap


framework.

JavaScript String Reference


JavaScript Strings
A JavaScript string stores a series of characters like "John Doe".

A string can be any text inside double or single quotes:

var carname = "Volvo XC60";


var carname = 'Volvo XC60';

String indexes are zero-based: The first character is in position 0, the second
in 1, and so on.

For a tutorial about Strings, read our JavaScript String Tutorial.

String Properties and Methods


Primitive values, like "John Doe", cannot have properties or methods
(because they are not objects).

But with JavaScript, methods and properties are also available to primitive
values, because JavaScript treats primitive values as objects when executing
methods and properties.

339
www.Sohrabpoor.com

String Properties
Property Description

constructor Returns the string's constructor function

length Returns the length of a string

prototype Allows you to add properties and methods to an object

String Methods
Method Description

charAt() Returns the character at the specified index (position)

charCodeAt() Returns the Unicode of the character at the specified index

concat() Joins two or more strings, and returns a new joined strings

endsWith() Checks whether a string ends with specified string/characters

fromCharCode() Converts Unicode values to characters

includes() Checks whether a string contains the specified string/characters

340
www.Sohrabpoor.com

indexOf() Returns the position of the first found occurrence of a specified value in
a string

lastIndexOf() Returns the position of the last found occurrence of a specified value in
a string

localeCompare() Compares two strings in the current locale

match() Searches a string for a match against a regular expression, and returns
the matches

repeat() Returns a new string with a specified number of copies of an existing


string

replace() Searches a string for a specified value, or a regular expression, and


returns a new string where the specified values are replaced

search() Searches a string for a specified value, or regular expression, and


returns the position of the match

slice() Extracts a part of a string and returns a new string

split() Splits a string into an array of substrings

startsWith() Checks whether a string begins with specified characters

substr() Extracts the characters from a string, beginning at a specified start


position, and through the specified number of character

341
www.Sohrabpoor.com

substring() Extracts the characters from a string, between two specified indices

toLocaleLowerCase() Converts a string to lowercase letters, according to the host's locale

toLocaleUpperCase() Converts a string to uppercase letters, according to the host's locale

toLowerCase() Converts a string to lowercase letters

toString() Returns the value of a String object

toUpperCase() Converts a string to uppercase letters

trim() Removes whitespace from both ends of a string

valueOf() Returns the primitive value of a String object

All string methods return a new value. They do not change the original
variable.

String HTML Wrapper Methods


The HTML wrapper methods return the string wrapped inside the appropriate
HTML tag.

These are not standard methods, and may not work as expected in all
browsers.

342
www.Sohrabpoor.com

Method Description

anchor() Creates an anchor

big() Displays a string using a big font

blink() Displays a blinking string

bold() Displays a string in bold

fixed() Displays a string using a fixed-pitch font

fontcolor() Displays a string using a specified color

fontsize() Displays a string using a specified size

italics() Displays a string in italic

link() Displays a string as a hyperlink

small() Displays a string using a small font

strike() Displays a string with a strikethrough

sub() Displays a string as subscript text

343
www.Sohrabpoor.com

sup() Displays a string as superscript text

JavaScript Number Reference


JavaScript Numbers
JavaScript has only one type of number.

Numbers can be written with, or without, decimals:

Example
var x = 3.14; // A number with decimals
var y = 34; // A number without decimals

Extra large or extra small numbers can be written with scientific (exponent)
notation:

Example
var x = 123e5; // 12300000
var y = 123e-5; // 0.00123

For a tutorial about JavaScript numbers, read our JavaScript Number


Tutorial.

Number Properties
Property Description

constructor Returns the function that created JavaScript's Number prototype

MAX_VALUE Returns the largest number possible in JavaScript

344
www.Sohrabpoor.com

MIN_VALUE Returns the smallest number possible in JavaScript

NEGATIVE_INFINITY Represents negative infinity (returned on overflow)

NaN Represents a "Not-a-Number" value

POSITIVE_INFINITY Represents infinity (returned on overflow)

prototype Allows you to add properties and methods to an object

Number Methods
Method Description

isFinite() Checks whether a value is a finite number

isInteger() Checks whether a value is an integer

isNaN() Checks whether a value is Number.NaN

isSafeInteger() Checks whether a value is a safe integer

toExponential(x) Converts a number into an exponential notation

toFixed(x) Formats a number with x numbers of digits after the decimal point

345
www.Sohrabpoor.com

toPrecision(x) Formats a number to x length

toString() Converts a number to a string

valueOf() Returns the primitive value of a number

All number methods return a new value. They do not change the original
variable.

JavaScript Operators Reference


JavaScript operators are used to assign values, compare values, perform
arithmetic operations, and more.

JavaScript Arithmetic Operators


Arithmetic operators are used to perform arithmetic between variables
and/or values.

Given that y = 5, the table below explains the arithmetic operators:

Operator Description Example Result in y Result in x Try it

+ Addition x=y+2 y=5 x=7 Try it »

- Subtraction x=y-2 y=5 x=3 Try it »

* Multiplication x=y*2 y=5 x = 10 Try it »

346
www.Sohrabpoor.com

/ Division x=y/2 y=5 x = 2.5 Try it »

% Modulus x=y%2 y=5 x=1 Try it »


(division
remainder)

++ Increment x = ++y y=6 x=6 Try it »

x = y++ y=6 x=5 Try it »

-- Decrement x = --y y=4 x=4 Try it »

x = y-- y=4 x=5 Try it »

For a tutorial about arithmetic operators, read our JavaScript Arithmetic


Tutorial.

JavaScript Assignment Operators


Assignment operators are used to assign values to JavaScript variables.

Given that x = 10 and y = 5, the table below explains the assignment


operators:

Operator Example Same As Result in x Try it

= x=y x=y x=5 Try it »

+= x += y x=x+y x = 15 Try it »

347
www.Sohrabpoor.com

-= x -= y x=x-y x=5 Try it »

*= x *= y x=x*y x = 50 Try it »

/= x /= y x=x/y x=2 Try it »

%= x %= y x=x%y x=0 Try it »

For a tutorial about assignment operators, read our JavaScript Assignment


Tutorial.

JavaScript String Operators


The + operator, and the += operator can also be used to concatenate (add)
strings.

Given that text1 = "Good ", text2 = "Morning", and text3 = "", the
table below explains the operators:

Operator Example text1 text2 text3 Try it

+ text3 = text1 + text2 "Good " "Morning" "Good Morning" Try it »

+= text1 += text2 "Good "Morning" "" Try it »


Morning"

348
www.Sohrabpoor.com

Comparison Operators
Comparison operators are used in logical statements to determine equality or
difference between variables or values.

Given that x = 5, the table below explains the comparison operators:

Operator Description Comparing Returns Try it

== equal to x == 8 false Try it »

x == 5 true Try it »

=== equal value and equal type x === "5" false Try it »

x === 5 true Try it »

!= not equal x != 8 true Try it »

!== not equal value or not equal type x !== "5" true Try it »

x !== 5 false Try it »

> greater than x>8 false Try it »

< less than x<8 true Try it »

>= greater than or equal to x >= 8 false Try it »

349
www.Sohrabpoor.com

<= less than or equal to x <= 8 true Try it »

For a tutorial about comparison operators, read our JavaScript Comparisons


Tutorial.

Conditional (Ternary) Operator


The conditional operator assigns a value to a variable based on a condition.

Syntax Example Try it

variablename = (condition) ? value1:value2 voteable = (age < 18) ? "Too young":"Old enough"; Try it »

Example explained: If the variable "age" is a value below 18, the value of
the variable "voteable" will be "Too young", otherwise the value of voteable
will be "Old enough".

Logical Operators
Logical operators are used to determine the logic between variables or
values.

Given that x = 6 and y = 3, the table below explains the logical operators:

Operator Description Example Try it

&& and (x < 10 && y > 1) is true Try it »

|| or (x === 5 || y === 5) is false Try it »

350
www.Sohrabpoor.com

! not !(x === y) is true Try it »

JavaScript Bitwise Operators


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 x=5&1 0101 & 0001 0001 1

| OR x=5|1 0101 | 0001 0101 5

~ NOT x=~5 ~0101 1010 10

^ XOR x=5^1 0101 ^ 0001 0100 4

<< Left shift x = 5 << 1 0101 << 1 1010 10

>> Right shift x = 5 >> 1 0101 >> 1 0010 2

The examples above uses 4 bits unsigned examples. But JavaScript uses 32-
bit signed numbers.

Because of this, in JavaScript, ~ 5 will not return 10. It will return -6.

~00000000000000000000000000000101 will return


11111111111111111111111111111010

351
www.Sohrabpoor.com

The typeof Operator


The typeof operator returns the type of a variable, object, function or
expression:

Example
typeof "John" // Returns string
typeof 3.14 // Returns number
typeof NaN // Returns number
typeof false // Returns boolean
typeof [1, 2, 3, 4] // Returns object
typeof {name:'John', age:34} // Returns object
typeof new Date() // Returns object
typeof function () {} // Returns function
typeof myCar // Returns undefined (if myCar is not
declared)
typeof null // Returns object

Try it Yourself »

Please observe:

 The data type of NaN is number


 The data type of an array is object
 The data type of a date is object
 The data type of null is object
 The data type of an undefined variable is undefined

You cannot use typeof to define if a JavaScript object is an array (or a date).

The delete Operator


The delete operator deletes a property from an object:

Example
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
delete person.age; // or delete person["age"];

Try it Yourself »

The delete operator deletes both the value of the property and the property
itself.

352
www.Sohrabpoor.com

After deletion, the property cannot be used before it is added back again.

The delete operator is designed to be used on object properties. It has no


effect on variables or functions.

Note: The delete operator should not be used on predefined JavaScript


object properties. It can crash your application.

The in Operator
The in operator returns true if the specified property is in the specified
object, otherwise false:

Example
// Arrays
var cars = ["Saab", "Volvo", "BMW"];
"Saab" in cars // Returns false (specify the index number instead
of value)
0 in cars // Returns true
1 in cars // Returns true
4 in cars // Returns false (does not exist)
"length" in cars // Returns true (length is an Array property)

// Objects
var person = {firstName:"John", lastName:"Doe", age:50};
"firstName" in person // Returns true
"age" in person // Returns true

// Predefined objects
"PI" in Math // Returns true
"NaN" in Number // Returns true
"length" in String // Returns true

Try it Yourself »

The instanceof Operator


The instanceof operator returns true if the specified object is an instance of
the specified object:

353
www.Sohrabpoor.com

Example
var cars = ["Saab", "Volvo", "BMW"];

cars instanceof Array; // Returns true


cars instanceof Object; // Returns true
cars instanceof String; // Returns false
cars instanceof Number; // Returns false

Try it Yourself »

The void Operator


The void operator evaluates an expression and returns undefined. This
operator is often used to obtain the undefined primitive value, using
"void(0)" (useful when evaluating an expression without using the return
value).

Example
<a href="javascript:void(0);">
Useless link
</a>

<a href="javascript:void(document.body.style.backgroundColor='red');">
Click me to change the background color of body to red
</a>

Try it Yourself »

JavaScript Statements Reference

JavaScript Statements
In HTML, JavaScript statements are "instructions" to be "executed" by the
web browser.

This statement tells the browser to write "Hello Dolly." inside an HTML
element with id="demo":

354
www.Sohrabpoor.com

Example
document.getElementById("demo").innerHTML = "Hello Dolly.";

Try it Yourself »

For a tutorial about Statements, read our JavaScript Statements Tutorial.

JavaScript Statement Identifiers


JavaScript statements often start with a statement identifier to identify the
JavaScript action to be performed.

Statement identifiers are reserved words and cannot be used as variable


names (or any other things).

The following table lists all JavaScript statements:

Statement Description

break Exits a switch or a loop

continue Breaks one iteration (in the loop) if a specified condition


occurs, and continues with the next iteration in the loop

debugger Stops the execution of JavaScript, and calls (if available) the
debugging function

do ... while Executes a block of statements and repeats the block while a
condition is true

for Marks a block of statements to be executed as long as a


condition is true

355
www.Sohrabpoor.com

for ... in Marks a block of statements to be executed for each element


of an object (or array)

function Declares a function

if ... else ... Marks a block of statements to be executed depending on a


else if condition

return Stops the execution of a function and returns a value from


that function

switch Marks a block of statements to be executed depending on


different cases

throw Throws (generates) an error

try ... catch Marks the block of statements to be executed when an error
... finally occurs in a try block, and implements error handling

var Declares a variable

while Marks a block of statements to be executed while a condition


is true

356
www.Sohrabpoor.com

JavaScript Math Reference


Math Object
The Math object allows you to perform mathematical tasks.

Math is not a constructor. All properties/methods of Math can be called by using Math as an
object, without creating it.

Syntax
var x = Math.PI; // Returns PI
var y = Math.sqrt(16); // Returns the square root of 16

For a tutorial about the Math object, read our JavaScript Math Tutorial.

Math Object Properties


Property Description

E Returns Euler's number (approx. 2.718)

LN2 Returns the natural logarithm of 2 (approx. 0.693)

LN10 Returns the natural logarithm of 10 (approx. 2.302)

LOG2E Returns the base-2 logarithm of E (approx. 1.442)

LOG10E Returns the base-10 logarithm of E (approx. 0.434)

PI Returns PI (approx. 3.14)

357
www.Sohrabpoor.com

SQRT1_2 Returns the square root of 1/2 (approx. 0.707)

SQRT2 Returns the square root of 2 (approx. 1.414)

Math Object Methods


Method Description

abs(x) Returns the absolute value of x

acos(x) Returns the arccosine of x, in radians

asin(x) Returns the arcsine of x, in radians

atan(x) Returns the arctangent of x as a numeric value between -PI/2 and PI/2 radians

atan2(y,x) Returns the arctangent of the quotient of its arguments

ceil(x) Returns x, rounded upwards to the nearest integer

cos(x) Returns the cosine of x (x is in radians)

exp(x) Returns the value of Ex

floor(x) Returns x, rounded downwards to the nearest integer

358
www.Sohrabpoor.com

log(x) Returns the natural logarithm (base E) of x

max(x,y,z,...,n) Returns the number with the highest value

min(x,y,z,...,n) Returns the number with the lowest value

pow(x,y) Returns the value of x to the power of y

random() Returns a random number between 0 and 1

round(x) Rounds x to the nearest integer

sin(x) Returns the sine of x (x is in radians)

sqrt(x) Returns the square root of x

tan(x) Returns the tangent of an angle

JavaScript Date Reference


Date Object
The Date object is used to work with dates and times.

Date objects are created with new Date().

There are four ways of instantiating a date:

var d = new Date();


var d = new Date(milliseconds);

359
www.Sohrabpoor.com

var d = new Date(dateString);


var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);

For a tutorial about date and times, read our JavaScript Date Tutorial.

Date Object Properties


Property Description

constructor Returns the function that created the Date object's prototype

prototype Allows you to add properties and methods to an object

Date Object Methods


Method Description

getDate() Returns the day of the month (from 1-31)

getDay() Returns the day of the week (from 0-6)

getFullYear() Returns the year

getHours() Returns the hour (from 0-23)

getMilliseconds() Returns the milliseconds (from 0-999)

getMinutes() Returns the minutes (from 0-59)

360
www.Sohrabpoor.com

getMonth() Returns the month (from 0-11)

getSeconds() Returns the seconds (from 0-59)

getTime() Returns the number of milliseconds since midnight Jan 1 1970, and a
specified date

getTimezoneOffset() Returns the time difference between UTC time and local time, in minutes

getUTCDate() Returns the day of the month, according to universal time (from 1-31)

getUTCDay() Returns the day of the week, according to universal time (from 0-6)

getUTCFullYear() Returns the year, according to universal time

getUTCHours() Returns the hour, according to universal time (from 0-23)

getUTCMilliseconds() Returns the milliseconds, according to universal time (from 0-999)

getUTCMinutes() Returns the minutes, according to universal time (from 0-59)

getUTCMonth() Returns the month, according to universal time (from 0-11)

getUTCSeconds() Returns the seconds, according to universal time (from 0-59)

getYear() Deprecated. Use the getFullYear() method instead

361
www.Sohrabpoor.com

now() Returns the number of milliseconds since midnight Jan 1, 1970

parse() Parses a date string and returns the number of milliseconds since January 1,
1970

setDate() Sets the day of the month of a date object

setFullYear() Sets the year of a date object

setHours() Sets the hour of a date object

setMilliseconds() Sets the milliseconds of a date object

setMinutes() Set the minutes of a date object

setMonth() Sets the month of a date object

setSeconds() Sets the seconds of a date object

setTime() Sets a date to a specified number of milliseconds after/before January 1,


1970

setUTCDate() Sets the day of the month of a date object, according to universal time

setUTCFullYear() Sets the year of a date object, according to universal time

setUTCHours() Sets the hour of a date object, according to universal time

362
www.Sohrabpoor.com

setUTCMilliseconds() Sets the milliseconds of a date object, according to universal time

setUTCMinutes() Set the minutes of a date object, according to universal time

setUTCMonth() Sets the month of a date object, according to universal time

setUTCSeconds() Set the seconds of a date object, according to universal time

setYear() Deprecated. Use the setFullYear() method instead

toDateString() Converts the date portion of a Date object into a readable string

toGMTString() Deprecated. Use the toUTCString() method instead

toISOString() Returns the date as a string, using the ISO standard

toJSON() Returns the date as a string, formatted as a JSON date

toLocaleDateString() Returns the date portion of a Date object as a string, using locale conventions

toLocaleTimeString() Returns the time portion of a Date object as a string, using locale conventions

toLocaleString() Converts a Date object to a string, using locale conventions

toString() Converts a Date object to a string

363
www.Sohrabpoor.com

toTimeString() Converts the time portion of a Date object to a string

toUTCString() Converts a Date object to a string, according to universal time

UTC() Returns the number of milliseconds in a date since midnight of January 1,


1970, according to UTC time

valueOf() Returns the primitive value of a Date object

JavaScript Array Reference


Array Object
The Array object is used to store multiple values in a single variable:

var cars = ["Saab", "Volvo", "BMW"];

Array indexes are zero-based: The first element in the array is 0, the second
is 1, and so on.

For a tutorial about Arrays, read our JavaScript Array Tutorial.

Array Properties
Property Description

constructor Returns the function that created the Array object's prototype

length Sets or returns the number of elements in an array

364
www.Sohrabpoor.com

prototype Allows you to add properties and methods to an Array object

Array Methods
Method Description

concat() Joins two or more arrays, and returns a copy of the joined arrays

copyWithin() Copies array elements within the array, to and from specified positions

every() Checks if every element in an array pass a test

fill() Fill the elements in an array with a static value

filter() Creates a new array with every element in an array that pass a test

find() Returns the value of the first element in an array that pass a test

findIndex() Returns the index of the first element in an array that pass a test

forEach() Calls a function for each array element

indexOf() Search the array for an element and returns its position

isArray() Checks whether an object is an array

365
www.Sohrabpoor.com

join() Joins all elements of an array into a string

lastIndexOf() Search the array for an element, starting at the end, and returns its position

map() Creates a new array with the result of calling a function for each array element

pop() Removes the last element of an array, and returns that element

push() Adds new elements to the end of an array, and returns the new length

reduce() Reduce the values of an array to a single value (going left-to-right)

reduceRight() Reduce the values of an array to a single value (going right-to-left)

reverse() Reverses the order of the elements in an array

shift() Removes the first element of an array, and returns that element

slice() Selects a part of an array, and returns the new array

some() Checks if any of the elements in an array pass a test

sort() Sorts the elements of an array

splice() Adds/Removes elements from an array

366
www.Sohrabpoor.com

toString() Converts an array to a string, and returns the result

unshift() Adds new elements to the beginning of an array, and returns the new length

valueOf() Returns the primitive value of an array

JavaScript Boolean Reference


JavaScript Booleans
JavaScript booleans can have one of two values: true or false.

The Boolean() Function


You can use the Boolean() function to find out if an expression is true:

Example
Boolean(10 > 9) // returns true

Try it Yourself »

Or even easier:

Example
(10 > 9) // also returns true
10 > 9 // also returns true

Try it Yourself »

For a tutorial about booleans, read our JavaScript Boolean Tutorial.

367
www.Sohrabpoor.com

Boolean Properties
Property Description

constructor Returns the function that created JavaScript's Boolean prototype

prototype Allows you to add properties and methods to the Boolean prototype

Boolean Methods
Method Description

toString() Converts a boolean value to a string, and returns the result

valueOf() Returns the primitive value of a boolean

JavaScript RegExp Reference


RegExp Object
A regular expression is an object that describes a pattern of characters.

Regular expressions are used to perform pattern-matching and "search-and-


replace" functions on text.

Syntax
/pattern/modifiers;

Example
var patt = /w3schools/i

368
www.Sohrabpoor.com

Example explained:

 /w3schools/i is a regular expression.


 w3schools is a pattern (to be used in a search).
 i is a modifier (modifies the search to be case-insensitive).

For a tutorial about Regular Expressions, read our JavaScript RegExp


Tutorial.

Modifiers
Modifiers are used to perform case-insensitive and global searches:

Modifier Description

i Perform case-insensitive matching

g Perform a global match (find all matches rather than stopping after the first match)

m Perform multiline matching

Brackets
Brackets are used to find a range of characters:

Expression Description

[abc] Find any character between the brackets

[^abc] Find any character NOT between the brackets

369
www.Sohrabpoor.com

[0-9] Find any digit between the brackets

[^0-9] Find any digit NOT between the brackets

(x|y) Find any of the alternatives specified

Metacharacters
Metacharacters are characters with a special meaning:

Metacharacter Description

. Find a single character, except newline or line terminator

\w Find a word character

\W Find a non-word character

\d Find a digit

\D Find a non-digit character

\s Find a whitespace character

\S Find a non-whitespace character

\b Find a match at the beginning/end of a word

370
www.Sohrabpoor.com

\B Find a match not at the beginning/end of a word

\0 Find a NUL character

\n Find a new line character

\f Find a form feed character

\r Find a carriage return character

\t Find a tab character

\v Find a vertical tab character

\xxx Find the character specified by an octal number xxx

\xdd Find the character specified by a hexadecimal number dd

\uxxxx Find the Unicode character specified by a hexadecimal number xxxx

Quantifiers
Quantifier Description

n+ Matches any string that contains at least one n

371
www.Sohrabpoor.com

n* Matches any string that contains zero or more occurrences of n

n? Matches any string that contains zero or one occurrences of n

n{X} Matches any string that contains a sequence of X n's

n{X,Y} Matches any string that contains a sequence of X to Y n's

n{X,} Matches any string that contains a sequence of at least X n's

n$ Matches any string with n at the end of it

^n Matches any string with n at the beginning of it

?=n Matches any string that is followed by a specific string n

?!n Matches any string that is not followed by a specific string n

RegExp Object Properties


Property Description

constructor Returns the function that created the RegExp object's prototype

global Checks whether the "g" modifier is set

372
www.Sohrabpoor.com

ignoreCase Checks whether the "i" modifier is set

lastIndex Specifies the index at which to start the next match

multiline Checks whether the "m" modifier is set

source Returns the text of the RegExp pattern

RegExp Object Methods


Method Description

compile() Deprecated in version 1.5. Compiles a regular expression

exec() Tests for a match in a string. Returns the first match

test() Tests for a match in a string. Returns true or false

toString() Returns the string value of the regular expression

373
www.Sohrabpoor.com

JavaScript Global Reference


The JavaScript global properties and functions can be used with all the
built-in JavaScript objects.

JavaScript Global Properties


Property Description

Infinity A numeric value that represents positive/negative infinity

NaN "Not-a-Number" value

undefined Indicates that a variable has not been assigned a value

JavaScript Global Functions


Function Description

decodeURI() Decodes a URI

decodeURIComponent() Decodes a URI component

encodeURI() Encodes a URI

encodeURIComponent() Encodes a URI component

374
www.Sohrabpoor.com

escape() Deprecated in version


1.5. Use encodeURI() or encodeURIComponent() instead

eval() Evaluates a string and executes it as if it was script code

isFinite() Determines whether a value is a finite, legal number

isNaN() Determines whether a value is an illegal number

Number() Converts an object's value to a number

parseFloat() Parses a string and returns a floating point number

parseInt() Parses a string and returns an integer

String() Converts an object's value to a string

unescape() Deprecated in version


1.5. Use decodeURI() or decodeURIComponent() instead

Functions or Methods?
It makes sense to call the list above global functions rather than global
methods because the functions are called globally and not any objects.

Anyway, you can also call these functions methods, since they are methods
of the global object where they run. In a web browser, the global object is
the browser window. Then isNaN() is actually a window method:
window.isNaN().

375
www.Sohrabpoor.com

JavaScript Type Conversion


JavaScript Type Conversion Table
The table below shows the result of converting different JavaScript values to
Number, String, and Boolean:

Original Converted Converted Converted Try it


Value to Number to String to Boolean

false 0 "false" false Try it »

true 1 "true" true Try it »

0 0 "0" false Try it »

1 1 "1" true Try it »

"0" 0 "0" true Try it »

"1" 1 "1" true Try it »

NaN NaN "NaN" false Try it »

Infinity Infinity "Infinity" true Try it »

-Infinity -Infinity "-Infinity" true Try it »

376
www.Sohrabpoor.com

"" 0 "" false Try it »

"20" 20 "20" true Try it »

"twenty" NaN "twenty" true Try it »

[] 0 "" true Try it »

[20] 20 "20" true Try it »

[10,20] NaN "10,20" true Try it »

["twenty"] NaN "twenty" true Try it »

["ten","twenty"] NaN "ten,twenty" true Try it »

function(){} NaN "function(){}" true Try it »

{} NaN "[object true Try it »


Object]"

null 0 "null" false Try it »

undefined NaN "undefined" false Try it »

Note: Values in quotes ("") indicate string values. Values in red indicate
values (some) programmers might not expect.

377
www.Sohrabpoor.com

For a tutorial about JavaScript Type Conversion, read our JavaScript Type
Conversion Tutorial.

The Window Object


Window Object
The window object represents an open window in a browser.

If a document contain frames (<iframe> tags), the browser creates one


window object for the HTML document, and one additional window object for
each frame.

Note: There is no public standard that applies to the Window object, but all
major browsers support it.

Window Object Properties


Property Description

closed Returns a Boolean value indicating whether a window


has been closed or not

defaultStatus Sets or returns the default text in the statusbar of a


window

document Returns the Document object for the window (See


Document object)

frameElement Returns the <iframe> element in which the current


window is inserted

frames Returns all <iframe> elements in the current window

378
www.Sohrabpoor.com

history Returns the History object for the window (See


History object)

innerHeight Returns the inner height of a window's content area

innerWidth Returns the inner width of a window's content area

length Returns the number of <iframe> elements in the


current window

localStorage Returns a reference to the local storage object used


to store data. Stores data with no expiration date

location Returns the Location object for the window (See


Location object)

name Sets or returns the name of a window

navigator Returns the Navigator object for the window (See


Navigator object)

opener Returns a reference to the window that created the


window

outerHeight Returns the outer height of a window, including


toolbars/scrollbars

outerWidth Returns the outer width of a window, including


toolbars/scrollbars

379
www.Sohrabpoor.com

pageXOffset Returns the pixels the current document has been


scrolled (horizontally) from the upper left corner of
the window

pageYOffset Returns the pixels the current document has been


scrolled (vertically) from the upper left corner of the
window

parent Returns the parent window of the current window

screen Returns the Screen object for the window (See Screen
object)

screenLeft Returns the horizontal coordinate of the window


relative to the screen

screenTop Returns the vertical coordinate of the window relative


to the screen

screenX Returns the horizontal coordinate of the window


relative to the screen

screenY Returns the vertical coordinate of the window relative


to the screen

sessionStorage Returns a reference to the local storage object used


to store data. Stores data for one session (lost when
the browser tab is closed)

scrollX An alias of pageXOffset

380
www.Sohrabpoor.com

scrollY An alias of pageYOffset

self Returns the current window

status Sets or returns the text in the statusbar of a window

top Returns the topmost browser window

Window Object Methods


Method Description

alert() Displays an alert box with a message and an OK


button

atob() Decodes a base-64 encoded string

blur() Removes focus from the current window

btoa() Encodes a string in base-64

clearInterval() Clears a timer set with setInterval()

clearTimeout() Clears a timer set with setTimeout()

close() Closes the current window

381
www.Sohrabpoor.com

confirm() Displays a dialog box with a message and an OK and


a Cancel button

focus() Sets focus to the current window

getComputedStyle() Gets the current computed CSS styles applied to an


element

getSelection() Returns a Selection object representing the range of


text selected by the user

matchMedia() Returns a MediaQueryList object representing the


specified CSS media query string

moveBy() Moves a window relative to its current position

moveTo() Moves a window to the specified position

open() Opens a new browser window

print() Prints the content of the current window

prompt() Displays a dialog box that prompts the visitor for


input

resizeBy() Resizes the window by the specified pixels

resizeTo() Resizes the window to the specified width and height

382
www.Sohrabpoor.com

scroll() Deprecated. This method has been replaced by


the scrollTo() method.

scrollBy() Scrolls the document by the specified number of


pixels

scrollTo() Scrolls the document to the specified coordinates

setInterval() Calls a function or evaluates an expression at


specified intervals (in milliseconds)

setTimeout() Calls a function or evaluates an expression after a


specified number of milliseconds

stop() Stops the window from loading

The Navigator Object


Navigator Object
The navigator object contains information about the browser.

Note: There is no public standard that applies to the navigator object, but all
major browsers support it.

383
www.Sohrabpoor.com

Navigator Object Properties


Property Description

appCodeName Returns the code name of the browser

appName Returns the name of the browser

appVersion Returns the version information of the browser

cookieEnabled Determines whether cookies are enabled in the browser

geolocation Returns a Geolocation object that can be used to locate the user's
position

language Returns the language of the browser

onLine Determines whether the browser is online

platform Returns for which platform the browser is compiled

product Returns the engine name of the browser

userAgent Returns the user-agent header sent by the browser to the server

384
www.Sohrabpoor.com

Navigator Object Methods


Method Description

javaEnabled() Specifies whether or not the browser has Java enabled

taintEnabled() Removed in JavaScript version 1.2. Specifies whether the browser has
data tainting enabled

The Screen Object


Screen Object
The screen object contains information about the visitor's screen.

Note: There is no public standard that applies to the screen object, but all
major browsers support it.

Screen Object Properties


Property Description

availHeight Returns the height of the screen (excluding the Windows Taskbar)

availWidth Returns the width of the screen (excluding the Windows Taskbar)

colorDepth Returns the bit depth of the color palette for displaying images

height Returns the total height of the screen

385
www.Sohrabpoor.com

pixelDepth Returns the color resolution (in bits per pixel) of the screen

width Returns the total width of the screen

The History Object


History Object
The history object contains the URLs visited by the user (within a browser
window).

The history object is part of the window object and is accessed through the
window.history property.

Note: There is no public standard that applies to the history object, but all
major browsers support it.

History Object Properties


Property Description

length Returns the number of URLs in the history list

History Object Methods


Method Description

back() Loads the previous URL in the history list

forward() Loads the next URL in the history list

386
www.Sohrabpoor.com

go() Loads a specific URL from the history list

The Location Object


Location Object
The location object contains information about the current URL.

The location object is part of the window object and is accessed through the
window.location property.

Note: There is no public standard that applies to the location object, but all
major browsers support it.

Location Object Properties


Property Description

hash Sets or returns the anchor part (#) of a URL

host Sets or returns the hostname and port number of a URL

hostname Sets or returns the hostname of a URL

href Sets or returns the entire URL

origin Returns the protocol, hostname and port number of a URL

pathname Sets or returns the path name of a URL

387
www.Sohrabpoor.com

port Sets or returns the port number of a URL

protocol Sets or returns the protocol of a URL

search Sets or returns the querystring part of a URL

Location Object Methods


Method Description

assign() Loads a new document

reload() Reloads the current document

replace() Replaces the current document with a new one

The HTML DOM Document Object


HTML DOM Nodes
In the HTML DOM (Document Object Model), everything is a node:

 The document itself is a document node


 All HTML elements are element nodes
 All HTML attributes are attribute nodes
 Text inside HTML elements are text nodes
 Comments are comment nodes

388
www.Sohrabpoor.com

The Document Object


When an HTML document is loaded into a web browser, it becomes
a document object.

The document object is the root node of the HTML document and the "owner"
of all other nodes:
(element nodes, text nodes, attribute nodes, and comment nodes).

The document object provides properties and methods to access all node
objects, from within JavaScript.

Tip: The document is a part of the Window object and can be accessed as
window.document.

Browser Support
Object

Document Yes Yes Yes Yes Yes

The Document Object is supported in all major browsers.

Document Object Properties and Methods


The following properties and methods can be used on HTML documents:

Property / Method Description

document.activeElement Returns the currently focused element in the document

document.addEventListener() Attaches an event handler to the document

389
www.Sohrabpoor.com

document.adoptNode() Adopts a node from another document

document.anchors Returns a collection of all <a> elements in the document


that have a name attribute

document.applets Returns a collection of all <applet> elements in the


document

document.baseURI Returns the absolute base URI of a document

document.body Sets or returns the document's body (the <body>


element)

document.close() Closes the output stream previously opened with


document.open()

document.cookie Returns all name/value pairs of cookies in the document

document.createAttribute() Creates an attribute node

document.createComment() Creates a Comment node with the specified text

document.createDocumentFragment() Creates an empty DocumentFragment node

document.createElement() Creates an Element node

document.createTextNode() Creates a Text node

390
www.Sohrabpoor.com

document.doctype Returns the Document Type Declaration associated with


the document

document.documentElement Returns the Document Element of the document (the


<html> element)

document.documentMode Returns the mode used by the browser to render the


document

document.documentURI Sets or returns the location of the document

document.domain Returns the domain name of the server that loaded the
document

document.domConfig Obsolete. Returns the DOM configuration of the


document

document.embeds Returns a collection of all <embed> elements the


document

document.forms Returns a collection of all <form> elements in the


document

document.getElementById() Returns the element that has the ID attribute with the
specified value

document.getElementsByClassName() Returns a NodeList containing all elements with the


specified class name

391
www.Sohrabpoor.com

document.getElementsByName() Returns a NodeList containing all elements with a


specified name

document.getElementsByTagName() Returns a NodeList containing all elements with the


specified tag name

document.hasFocus() Returns a Boolean value indicating whether the


document has focus

document.head Returns the <head> element of the document

document.images Returns a collection of all <img> elements in the


document

document.implementation Returns the DOMImplementation object that handles


this document

document.importNode() Imports a node from another document

document.inputEncoding Returns the encoding, character set, used for the


document

document.lastModified Returns the date and time the document was last
modified

document.links Returns a collection of all <a> and <area> elements in


the document that have a href attribute

document.normalize() Removes empty Text nodes, and joins adjacent nodes

392
www.Sohrabpoor.com

document.normalizeDocument() Removes empty Text nodes, and joins adjacent nodes

document.open() Opens an HTML output stream to collect output from


document.write()

document.querySelector() Returns the first element that matches a specified CSS


selector(s) in the document

document.querySelectorAll() Returns a static NodeList containing all elements that


matches a specified CSS selector(s) in the document

document.readyState Returns the (loading) status of the document

document.referrer Returns the URL of the document that loaded the


current document

document.removeEventListener() Removes an event handler from the document (that has


been attached with the addEventListener() method)

document.renameNode() Renames the specified node

document.scripts Returns a collection of <script> elements in the


document

document.strictErrorChecking Sets or returns whether error-checking is enforced or


not

document.title Sets or returns the title of the document

393
www.Sohrabpoor.com

document.URL Returns the full URL of the HTML document

document.write() Writes HTML expressions or JavaScript code to a


document

document.writeln() Same as write(), but adds a newline character after each


statement

Warning !!!
In the W3C DOM Core, the Document object inherits all properties and
methods from the Node object.

Many of these properties and methods make no sense used on documents.

Avoid using these node object properties and methods on HTML


document objects:

Property / Method Reason for avoiding

document.attributes Documents don't have attributes

document.hasAttributes() Documents don't have attributes

document.nextSibling Documents don't have siblings

document.nodeName This is always #document

document.nodeType This is always 9 (DOCUMENT_NODE)

394
www.Sohrabpoor.com

document.nodeValue Documents don't have an node value

document.ownerDocument Documents don't have an owner document

document.ownerElement Documents don't have an owner element

document.parentNode Documents don't have a parent node

document.previousSibling Documents don't have siblings

document.textContent Documents don't have a text content

The HTML DOM Element Object


HTML DOM Nodes
In the HTML DOM (Document Object Model), everything is a node:

 The document itself is a document node


 All HTML elements are element nodes
 All HTML attributes are attribute nodes
 Text inside HTML elements are text nodes
 Comments are comment nodes

The Element Object


In the HTML DOM, the Element object represents an HTML element.

Element objects can have child nodes of type element nodes, text nodes, or
comment nodes.

395
www.Sohrabpoor.com

A NodeList object represents a list of nodes, like an HTML element's


collection of child nodes.

Elements can also have attributes. Attributes are attribute nodes (See next
chapter).

Browser Support
Object

Element Yes Yes Yes Yes Yes

NodeList Yes Yes Yes Yes Yes

The Element Object and the NodeList Object are supported in all major
browsers.

Properties and Methods


The following properties and methods can be used on all HTML elements:

Property / Method Description

element.accessKey Sets or returns the accesskey attribute of an element

element.addEventListener() Attaches an event handler to the specified element

element.appendChild() Adds a new child node, to an element, as the last child


node

element.attributes Returns a NamedNodeMap of an element's attributes

396
www.Sohrabpoor.com

element.blur() Removes focus from an element

element.childElementCount Returns the number of child elements an element has

element.childNodes Returns a collection of an element's child nodes (including


text and comment nodes)

element.children Returns a collection of an element's child element


(excluding text and comment nodes)

element.classList Returns the class name(s) of an element

element.className Sets or returns the value of the class attribute of an


element

element.click() Simulates a mouse-click on an element

element.clientHeight Returns the height of an element, including padding

element.clientLeft Returns the width of the left border of an element

element.clientTop Returns the width of the top border of an element

element.clientWidth Returns the width of an element, including padding

element.cloneNode() Clones an element

397
www.Sohrabpoor.com

element.compareDocumentPosition() Compares the document position of two elements

element.contains() Returns true if a node is a descendant of a node,


otherwise false

element.contentEditable Sets or returns whether the content of an element is


editable or not

element.dir Sets or returns the value of the dir attribute of an element

element.firstChild Returns the first child node of an element

element.firstElementChild Returns the first child element of an element

element.focus() Gives focus to an element

element.getAttribute() Returns the specified attribute value of an element node

element.getAttributeNode() Returns the specified attribute node

element.getElementsByClassName() Returns a collection of all child elements with the


specified class name

element.getElementsByTagName() Returns a collection of all child elements with the


specified tag name

element.getFeature() Returns an object which implements the APIs of a


specified feature

398
www.Sohrabpoor.com

element.hasAttribute() Returns true if an element has the specified attribute,


otherwise false

element.hasAttributes() Returns true if an element has any attributes, otherwise


false

element.hasChildNodes() Returns true if an element has any child nodes, otherwise


false

element.id Sets or returns the value of the id attribute of an element

element.innerHTML Sets or returns the content of an element

element.insertBefore() Inserts a new child node before a specified, existing, child


node

element.isContentEditable Returns true if the content of an element is editable,


otherwise false

element.isDefaultNamespace() Returns true if a specified namespaceURI is the default,


otherwise false

element.isEqualNode() Checks if two elements are equal

element.isSameNode() Checks if two elements are the same node

element.isSupported() Returns true if a specified feature is supported on the


element

399
www.Sohrabpoor.com

element.lang Sets or returns the value of the lang attribute of an


element

element.lastChild Returns the last child node of an element

element.lastElementChild Returns the last child element of an element

element.namespaceURI Returns the namespace URI of an element

element.nextSibling Returns the next node at the same node tree level

element.nextElementSibling Returns the next element at the same node tree level

element.nodeName Returns the name of a node

element.nodeType Returns the node type of a node

element.nodeValue Sets or returns the value of a node

element.normalize() Joins adjacent text nodes and removes empty text nodes
in an element

element.offsetHeight Returns the height of an element, including padding,


border and scrollbar

element.offsetWidth Returns the width of an element, including padding,


border and scrollbar

400
www.Sohrabpoor.com

element.offsetLeft Returns the horizontal offset position of an element

element.offsetParent Returns the offset container of an element

element.offsetTop Returns the vertical offset position of an element

element.ownerDocument Returns the root element (document object) for an


element

element.parentNode Returns the parent node of an element

element.parentElement Returns the parent element node of an element

element.previousSibling Returns the previous node at the same node tree level

element.previousElementSibling Returns the previous element at the same node tree level

element.querySelector() Returns the first child element that matches a specified


CSS selector(s) of an element

element.querySelectorAll() Returns all child elements that matches a specified CSS


selector(s) of an element

element.removeAttribute() Removes a specified attribute from an element

element.removeAttributeNode() Removes a specified attribute node, and returns the


removed node

401
www.Sohrabpoor.com

element.removeChild() Removes a child node from an element

element.replaceChild() Replaces a child node in an element

element.removeEventListener() Removes an event handler that has been attached with


the addEventListener() method

element.scrollHeight Returns the entire height of an element, including padding

element.scrollLeft Sets or returns the number of pixels an element's content


is scrolled horizontally

element.scrollTop Sets or returns the number of pixels an element's content


is scrolled vertically

element.scrollWidth Returns the entire width of an element, including padding

element.setAttribute() Sets or changes the specified attribute, to the specified


value

element.setAttributeNode() Sets or changes the specified attribute node

element.style Sets or returns the value of the style attribute of an


element

element.tabIndex Sets or returns the value of the tabindex attribute of an


element

element.tagName Returns the tag name of an element

402
www.Sohrabpoor.com

element.textContent Sets or returns the textual content of a node and its


descendants

element.title Sets or returns the value of the title attribute of an


element

element.toString() Converts an element to a string

nodelist.item() Returns the node at the specified index in a NodeList

nodelist.length Returns the number of nodes in a NodeList

The HTML DOM Attribute Object


HTML DOM Nodes
In the HTML DOM (Document Object Model), everything is a node:

 The document itself is a document node


 All HTML elements are element nodes
 All HTML attributes are attribute nodes
 Text inside HTML elements are text nodes
 Comments are comment nodes

The Attr Object


In the HTML DOM, the Attr object represents an HTML attribute.

An HTML attribute always belongs to an HTML element.

403
www.Sohrabpoor.com

The NamedNodeMap Object


In the HTML DOM, the NamedNodeMap object represents an unordered
collection of an elements attribute nodes.

Nodes in a NamedNodeMap can be accessed by name or by index (number).

Browser Support
Object

Attr Yes Yes Yes Yes Yes

NamedNodeMap Yes Yes Yes Yes Yes

The Attr Object and the NamedNodeMap Object is supported in all major
browsers.

Properties and Methods


Property / Method Description

attr.isId Returns true if the attribute is of type Id, otherwise it returns


false

attr.name Returns the name of an attribute

attr.value Sets or returns the value of the attribute

404
www.Sohrabpoor.com

attr.specified Returns true if the attribute has been specified, otherwise it


returns false

nodemap.getNamedItem() Returns a specified attribute node from a NamedNodeMap

nodemap.item() Returns the attribute node at a specified index in a


NamedNodeMap

nodemap.length Returns the number of attribute nodes in a NamedNodeMap

nodemap.removeNamedItem() Removes a specified attribute node

nodemap.setNamedItem() Sets the specified attribute node (by name)

DOM 4 Warning !!!


In the W3C DOM Core, the Attr (attribute) object inherits all properties and
methods from the Node object.

In DOM 4, the Attr object no longer inherits from Node.

For future code quality, you should avoid using node object
properties and methods on attribute objects:

405
www.Sohrabpoor.com

Property / Method Reason for avoiding

attr.appendChild() Attributes don't have child nodes

attr.attributes Attributes don't have attributes

attr.baseURI use document.baseURI instead

attr.childNodes Attributes don't have child nodes

attr.cloneNode() Get or set the attr.value instead

attr.firstChild Attributes don't have child nodes

attr.hasAttributes() Attributes don't have attributes

attr.hasChildNodes Attributes don't have child nodes

attr.insertBefore() Attributes don't have child nodes

attr.isEqualNode() Makes no sense

attr.isSameNode() Makes no sense

attr.isSupported() Is always true

406
www.Sohrabpoor.com

attr.lastChild Attributes don't have child nodes

attr.nextSibling Attributes don't have siblings

attr.nodeName Use attr.name instead

attr.nodeType This is always 2 (ATTRIBUTE_NODE)

attr.nodeValue Use attr.value instead

attr.normalize() Attributes cannot be normalized

attr.ownerDocument This is always your HTML document

attr.ownerElement This is the HTML element you used to access the attribute

attr.parentNode This is the HTML element you used to access the attribute

attr.previousSibling Attributes don't have siblings

attr.removeChild Attributes don't have child nodes

attr.replaceChild Attributes don't have child nodes

attr.textContent Use attr.value instead

407
www.Sohrabpoor.com

HTML DOM Events


HTML DOM Events
HTML DOM events allow JavaScript to register different event handlers on
elements in an HTML document.

Events are normally used in combination with functions, and the function will
not be executed before the event occurs (such as when a user clicks a
button).

Tip: The event model was standardized by the W3C in DOM Level 2.

HTML DOM Events


DOM: Indicates in which DOM Level the property was introduced.

Mouse Events
Event Description DOM

onclick The event occurs when the user clicks on an element 2

oncontextmenu The event occurs when the user right-clicks on an element to open a 3
context menu

ondblclick The event occurs when the user double-clicks on an element 2

onmousedown The event occurs when the user presses a mouse button over an 2
element

onmouseenter The event occurs when the pointer is moved onto an element 2

408
www.Sohrabpoor.com

onmouseleave The event occurs when the pointer is moved out of an element 2

onmousemove The event occurs when the pointer is moving while it is over an 2
element

onmouseover The event occurs when the pointer is moved onto an element, or 2
onto one of its children

onmouseout The event occurs when a user moves the mouse pointer out of an 2
element, or out of one of its children

onmouseup The event occurs when a user releases a mouse button over an 2
element

Keyboard Events
Event Description DOM

onkeydown The event occurs when the user is pressing a key 2

onkeypress The event occurs when the user presses a key 2

onkeyup The event occurs when the user releases a key 2

409
www.Sohrabpoor.com

Frame/Object Events
Event Description DOM

onabort The event occurs when the loading of a resource has been aborted 2

onbeforeunload The event occurs before the document is about to be unloaded 2

onerror The event occurs when an error occurs while loading an external file 2

onhashchange The event occurs when there has been changes to the anchor part of a 3
URL

onload The event occurs when an object has loaded 2

onpageshow The event occurs when the user navigates to a webpage 3

onpagehide The event occurs when the user navigates away from a webpage 3

onresize The event occurs when the document view is resized 2

onscroll The event occurs when an element's scrollbar is being scrolled 2

onunload The event occurs once a page has unloaded (for <body>) 2

410
www.Sohrabpoor.com

Form Events
Event Description DOM

onblur The event occurs when an element loses focus 2

onchange The event occurs when the content of a form element, the selection, or the 2
checked state have changed (for <input>, <keygen>, <select>, and <textarea>)

onfocus The event occurs when an element gets focus 2

onfocusin The event occurs when an element is about to get focus 2

onfocusout The event occurs when an element is about to lose focus 2

oninput The event occurs when an element gets user input 3

oninvalid The event occurs when an element is invalid 3

onreset The event occurs when a form is reset 2

onsearch The event occurs when the user writes something in a search field (for 3
<input="search">)

onselect The event occurs after the user selects some text (for <input> and <textarea>) 2

onsubmit The event occurs when a form is submitted 2

411
www.Sohrabpoor.com

Drag Events
Event Description DOM

ondrag The event occurs when an element is being dragged 3

ondragend The event occurs when the user has finished dragging an element 3

ondragenter The event occurs when the dragged element enters the drop target 3

ondragleave The event occurs when the dragged element leaves the drop target 3

ondragover The event occurs when the dragged element is over the drop target 3

ondragstart The event occurs when the user starts to drag an element 3

ondrop The event occurs when the dragged element is dropped on the drop target 3

Clipboard Events
Event Description DOM

oncopy The event occurs when the user copies the content of an element

oncut The event occurs when the user cuts the content of an element

onpaste The event occurs when the user pastes some content in an element

412
www.Sohrabpoor.com

Print Events
Event Description DOM

onafterprint The event occurs when a page has started printing, or if the print dialogue 3
box has been closed

onbeforeprint The event occurs when a page is about to be printed 3

Media Events
Event Description DOM

onabort The event occurs when the loading of a media is aborted 3

oncanplay The event occurs when the browser can start playing the media (when 3
it has buffered enough to begin)

oncanplaythrough The event occurs when the browser can play through the media 3
without stopping for buffering

ondurationchange The event occurs when the duration of the media is changed 3

onemptied The event occurs when something bad happens and the media file is 3
suddenly unavailable (like unexpectedly disconnects)

onended The event occurs when the media has reach the end (useful for 3
messages like "thanks for listening")

413
www.Sohrabpoor.com

onerror The event occurs when an error occurred during the loading of a 3
media file

onloadeddata The event occurs when media data is loaded 3

onloadedmetadata The event occurs when meta data (like dimensions and duration) are 3
loaded

onloadstart The event occurs when the browser starts looking for the specified 3
media

onpause The event occurs when the media is paused either by the user or 3
programmatically

onplay The event occurs when the media has been started or is no longer 3
paused

onplaying The event occurs when the media is playing after having been paused 3
or stopped for buffering

onprogress The event occurs when the browser is in the process of getting the 3
media data (downloading the media)

onratechange The event occurs when the playing speed of the media is changed 3

onseeked The event occurs when the user is finished moving/skipping to a new 3
position in the media

onseeking The event occurs when the user starts moving/skipping to a new 3
position in the media

414
www.Sohrabpoor.com

onstalled The event occurs when the browser is trying to get media data, but 3
data is not available

onsuspend The event occurs when the browser is intentionally not getting media 3
data

ontimeupdate The event occurs when the playing position has changed (like when 3
the user fast forwards to a different point in the media)

onvolumechange The event occurs when the volume of the media has changed 3
(includes setting the volume to "mute")

onwaiting The event occurs when the media has paused but is expected to 3
resume (like when the media pauses to buffer more data)

Animation Events
Event Description DOM

animationend The event occurs when a CSS animation has completed 3

animationiteration The event occurs when a CSS animation is repeated 3

animationstart The event occurs when a CSS animation has started 3

415
www.Sohrabpoor.com

Transition Events
Event Description DOM

transitionend The event occurs when a CSS transition has completed 3

Server-Sent Events
Event Description DOM

onerror The event occurs when an error occurs with the event source

onmessage The event occurs when a message is received through the event source

onopen The event occurs when a connection with the event source is opened

Misc Events
Event Description DOM

onmessage The event occurs when a message is received through or from an object 3
(WebSocket, Web Worker, Event Source or a child frame or a parent window)

onmousewheel Deprecated. Use the onwheel event instead

ononline The event occurs when the browser starts to work online 3

416
www.Sohrabpoor.com

onoffline The event occurs when the browser starts to work offline 3

onpopstate The event occurs when the window's history changes 3

onshow The event occurs when a <menu> element is shown as a context menu 3

onstorage The event occurs when a Web Storage area is updated 3

ontoggle The event occurs when the user opens or closes the <details> element 3

onwheel The event occurs when the mouse wheel rolls up or down over an element 3

Touch Events
Event Description DOM

ontouchcancel The event occurs when the touch is interrupted

ontouchend The event occurs when a finger is removed from a touch screen

ontouchmove The event occurs when a finger is dragged across the screen

ontouchstart The event occurs when a finger is placed on a touch screen

Event Object
Constants

417
www.Sohrabpoor.com

Constant Description DOM

CAPTURING_PHASE The current event phase is the capture phase (1) 1

AT_TARGET The current event is in the target phase, i.e. it is being evaluated at the 2
event target (2)

BUBBLING_PHASE The current event phase is the bubbling phase (3) 3

Properties

Property Description DOM

bubbles Returns whether or not a specific event is a bubbling event 2

cancelable Returns whether or not an event can have its default action prevented 2

currentTarget Returns the element whose event listeners triggered the event 2

defaultPrevented Returns whether or not the preventDefault() method was called for the 3
event

eventPhase Returns which phase of the event flow is currently being evaluated 2

isTrusted Returns whether or not an event is trusted 3

target Returns the element that triggered the event 2

418
www.Sohrabpoor.com

timeStamp Returns the time (in milliseconds relative to the epoch) at which the 2
event was created

type Returns the name of the event 2

view Returns a reference to the Window object where the event occured 2

Methods

Method Description DOM

preventDefault() Cancels the event if it is cancelable, meaning that the default action 2
that belongs to the event will not occur

stopImmediatePropagation() Prevents other listeners of the same event from being called 3

stopPropagation() Prevents further propagation of an event during event flow 2

MouseEvent Object
Property Description DOM

altKey Returns whether the "ALT" key was pressed when the mouse event was triggered 2

button Returns which mouse button was pressed when the mouse event was triggered 2

419
www.Sohrabpoor.com

buttons Returns which mouse buttons were pressed when the mouse event was triggered 3

clientX Returns the horizontal coordinate of the mouse pointer, relative to the current 2
window, when the mouse event was triggered

clientY Returns the vertical coordinate of the mouse pointer, relative to the current 2
window, when the mouse event was triggered

ctrlKey Returns whether the "CTRL" key was pressed when the mouse event was triggered 2

detail Returns a number that indicates how many times the mouse was clicked 2

metaKey Returns whether the "META" key was pressed when an event was triggered 2

pageX Returns the horizontal coordinate of the mouse pointer, relative to the document,
when the mouse event was triggered

pageY Returns the vertical coordinate of the mouse pointer, relative to the document,
when the mouse event was triggered

relatedTarget Returns the element related to the element that triggered the mouse event 2

screenX Returns the horizontal coordinate of the mouse pointer, relative to the screen, 2
when an event was triggered

screenY Returns the vertical coordinate of the mouse pointer, relative to the screen, when 2
an event was triggered

shiftKey Returns whether the "SHIFT" key was pressed when an event was triggered 2

420
www.Sohrabpoor.com

which Returns which mouse button was pressed when the mouse event was triggered 2

KeyboardEvent Object
Property Description DOM

altKey Returns whether the "ALT" key was pressed when the key event was triggered 2

ctrlKey Returns whether the "CTRL" key was pressed when the key event was triggered 2

charCode Returns the Unicode character code of the key that triggered the onkeypress event 2

key Returns the key value of the key represented by the event 3

keyCode Returns the Unicode character code of the key that triggered the onkeypress event, 2
or the Unicode key code of the key that triggered the onkeydown or onkeyup event

location Returns the location of a key on the keyboard or device 3

metaKey Returns whether the "meta" key was pressed when the key event was triggered 2

shiftKey Returns whether the "SHIFT" key was pressed when the key event was triggered 2

which Returns the Unicode character code of the key that triggered the onkeypress event, 2
or the Unicode key code of the key that triggered the onkeydown or onkeyup event

421
www.Sohrabpoor.com

HashChangeEvent Object
Property Description DOM

newURL Returns the URL of the document, after the hash has been changed

oldURL Returns the URL of the document, before the hash was changed

PageTransitionEvent Object
Property Description DOM

persisted Returns whether the webpage was cached by the browser

FocusEvent Object
Property Description DOM

relatedTarget Returns the element related to the element that triggered the event 3

AnimationEvent Object
Property Description DOM

animationName Returns the name of the animation

elapsedTime Returns the number of seconds an animation has been running

422
www.Sohrabpoor.com

TransitionEvent Object
Property Description DOM

propertyName Returns the name of the CSS property associated with the transition

elapsedTime Returns the number of seconds a transition has been running

WheelEvent Object
Property Description DOM

deltaX Returns the horizontal scroll amount of a mouse wheel (x-axis) 3

deltaY Returns the vertical scroll amount of a mouse wheel (y-axis) 3

deltaZ Returns the scroll amount of a mouse wheel for the z-axis 3

deltaMode Returns a number that represents the unit of measurements for delta values 3
(pixels, lines or pages)

HTML DOM Style Object


Style object
The Style object represents an individual style statement.

423
www.Sohrabpoor.com

Access a Style Object


The Style object can be accessed from the head section of the document, or
from specific HTML element(s).

Accessing style object(s) from the head section of the document:

Example
var x = document.getElementsByTagName("STYLE");

Try it Yourself »

Accessing a specified element's style object:

Example
var x = document.getElementById("myH1").style;

Try it Yourself »

Create a Style Object


You can create a <style> element by using the document.createElement()
method:

Example
var x = document.createElement("STYLE");

Try it Yourself »

You can also set the style properties of an existing element:

Example
document.getElementById("myH1").style.color = "red";

Try it Yourself »

Style Object Properties


The "CSS" column indicates in which CSS version the property is defined
(CSS1, CSS2, or CSS3).

424
www.Sohrabpoor.com

Property Description CSS

alignContent Sets or returns the alignment between the lines inside a flexible 3
container when the items do not use all available space

alignItems Sets or returns the alignment for items inside a flexible container 3

alignSelf Sets or returns the alignment for selected items inside a flexible 3
container

animation A shorthand property for all the animation properties below, except 3
the animationPlayState property

animationDelay Sets or returns when the animation will start 3

animationDirection Sets or returns whether or not the animation should play in reverse 3
on alternate cycles

animationDuration Sets or returns how many seconds or milliseconds an animation takes 3


to complete one cycle

animationFillMode Sets or returns what values are applied by the animation outside the 3
time it is executing

animationIterationCount Sets or returns the number of times an animation should be played 3

animationName Sets or returns a name for the @keyframes animation 3

animationTimingFunction Sets or returns the speed curve of the animation 3

425
www.Sohrabpoor.com

animationPlayState Sets or returns whether the animation is running or paused 3

background Sets or returns all the background properties in one declaration 1

backgroundAttachment Sets or returns whether a background-image is fixed or scrolls with 1


the page

backgroundColor Sets or returns the background-color of an element 1

backgroundImage Sets or returns the background-image for an element 1

backgroundPosition Sets or returns the starting position of a background-image 1

backgroundRepeat Sets or returns how to repeat (tile) a background-image 1

backgroundClip Sets or returns the painting area of the background 3

backgroundOrigin Sets or returns the positioning area of the background images 3

backgroundSize Sets or returns the size of the background image 3

backfaceVisibility Sets or returns whether or not an element should be visible when not 3
facing the screen

border Sets or returns borderWidth, borderStyle, and borderColor in one 1


declaration

426
www.Sohrabpoor.com

borderBottom Sets or returns all the borderBottom* properties in one declaration 1

borderBottomColor Sets or returns the color of the bottom border 1

borderBottomLeftRadius Sets or returns the shape of the border of the bottom-left corner 3

borderBottomRightRadius Sets or returns the shape of the border of the bottom-right corner 3

borderBottomStyle Sets or returns the style of the bottom border 1

borderBottomWidth Sets or returns the width of the bottom border 1

borderCollapse Sets or returns whether the table border should be collapsed into a 2
single border, or not

borderColor Sets or returns the color of an element's border (can have up to four 1
values)

borderImage A shorthand property for setting or returning all the borderImage* 3


properties

borderImageOutset Sets or returns the amount by which the border image area extends 3
beyond the border box

borderImageRepeat Sets or returns whether the image-border should be repeated, 3


rounded or stretched

borderImageSlice Sets or returns the inward offsets of the image-border 3

427
www.Sohrabpoor.com

borderImageSource Sets or returns the image to be used as a border 3

borderImageWidth Sets or returns the widths of the image-border 3

borderLeft Sets or returns all the borderLeft* properties in one declaration 1

borderLeftColor Sets or returns the color of the left border 1

borderLeftStyle Sets or returns the style of the left border 1

borderLeftWidth Sets or returns the width of the left border 1

borderRadius A shorthand property for setting or returning all the four 3


border*Radius properties

borderRight Sets or returns all the borderRight* properties in one declaration 1

borderRightColor Sets or returns the color of the right border 1

borderRightStyle Sets or returns the style of the right border 1

borderRightWidth Sets or returns the width of the right border 1

borderSpacing Sets or returns the space between cells in a table 2

borderStyle Sets or returns the style of an element's border (can have up to four 1
values)

428
www.Sohrabpoor.com

borderTop Sets or returns all the borderTop* properties in one declaration 1

borderTopColor Sets or returns the color of the top border 1

borderTopLeftRadius Sets or returns the shape of the border of the top-left corner 3

borderTopRightRadius Sets or returns the shape of the border of the top-right corner 3

borderTopStyle Sets or returns the style of the top border 1

borderTopWidth Sets or returns the width of the top border 1

borderWidth Sets or returns the width of an element's border (can have up to four 1
values)

bottom Sets or returns the bottom position of a positioned element 2

boxDecorationBreak Sets or returns the behaviour of the background and border of an 3


element at page-break, or, for in-line elements, at line-break.

boxShadow Attaches one or more drop-shadows to the box 3

boxSizing Allows you to define certain elements to fit an area in a certain way 3

captionSide Sets or returns the position of the table caption 2

clear Sets or returns the position of the element relative to floating objects 1

429
www.Sohrabpoor.com

clip Sets or returns which part of a positioned element is visible 2

color Sets or returns the color of the text 1

columnCount Sets or returns the number of columns an element should be divided 3


into

columnFill Sets or returns how to fill columns 3

columnGap Sets or returns the gap between the columns 3

columnRule A shorthand property for setting or returning all the columnRule* 3


properties

columnRuleColor Sets or returns the color of the rule between columns 3

columnRuleStyle Sets or returns the style of the rule between columns 3

columnRuleWidth Sets or returns the width of the rule between columns 3

columns A shorthand property for setting or returning columnWidth and 3


columnCount

columnSpan Sets or returns how many columns an element should span across 3

columnWidth Sets or returns the width of the columns 3

430
www.Sohrabpoor.com

content Used with the :before and :after pseudo-elements, to insert 2


generated content

counterIncrement Increments one or more counters 2

counterReset Creates or resets one or more counters 2

cursor Sets or returns the type of cursor to display for the mouse pointer 2

direction Sets or returns the text direction 2

display Sets or returns an element's display type 1

emptyCells Sets or returns whether to show the border and background of empty 2
cells, or not

filter Sets or returns image filters (visual effects, like blur and saturation) 3

flex Sets or returns the length of the item, relative to the rest 3

flexBasis Sets or returns the initial length of a flexible item 3

flexDirection Sets or returns the direction of the flexible items 3

flexFlow A shorthand property for the flexDirection and the flexWrap 3


properties

431
www.Sohrabpoor.com

flexGrow Sets or returns how much the item will grow relative to the rest 3

flexShrink Sets or returns how the item will shrink relative to the rest 3

flexWrap Sets or returns whether the flexible items should wrap or not 3

cssFloat Sets or returns the horizontal alignment of an element 1

font Sets or returns fontStyle, fontVariant, fontWeight, fontSize, 1


lineHeight, and fontFamily in one declaration

fontFamily Sets or returns the font family for text 1

fontSize Sets or returns the font size of the text 1

fontStyle Sets or returns whether the style of the font is normal, italic or 1
oblique

fontVariant Sets or returns whether the font should be displayed in small capital 1
letters

fontWeight Sets or returns the boldness of the font 1

fontSizeAdjust Preserves the readability of text when font fallback occurs 3

fontStretch Selects a normal, condensed, or expanded face from a font family 3

432
www.Sohrabpoor.com

hangingPunctuation Specifies whether a punctuation character may be placed outside the 3


line box

height Sets or returns the height of an element 1

hyphens Sets how to split words to improve the layout of paragraphs 3

icon Provides the author the ability to style an element with an iconic 3
equivalent

imageOrientation Specifies a rotation in the right or clockwise direction that a user 3


agent applies to an image

justifyContent Sets or returns the alignment between the items inside a flexible 3
container when the items do not use all available space.

left Sets or returns the left position of a positioned element 2

letterSpacing Sets or returns the space between characters in a text 1

lineHeight Sets or returns the distance between lines in a text 1

listStyle Sets or returns listStyleImage, listStylePosition, and listStyleType in 1


one declaration

listStyleImage Sets or returns an image as the list-item marker 1

listStylePosition Sets or returns the position of the list-item marker 1

433
www.Sohrabpoor.com

listStyleType Sets or returns the list-item marker type 1

margin Sets or returns the margins of an element (can have up to four 1


values)

marginBottom Sets or returns the bottom margin of an element 1

marginLeft Sets or returns the left margin of an element 1

marginRight Sets or returns the right margin of an element 1

marginTop Sets or returns the top margin of an element 1

maxHeight Sets or returns the maximum height of an element 2

maxWidth Sets or returns the maximum width of an element 2

minHeight Sets or returns the minimum height of an element 2

minWidth Sets or returns the minimum width of an element 2

navDown Sets or returns where to navigate when using the arrow-down 3


navigation key

navIndex Sets or returns the tabbing order for an element 3

434
www.Sohrabpoor.com

navLeft Sets or returns where to navigate when using the arrow-left 3


navigation key

navRight Sets or returns where to navigate when using the arrow-right 3


navigation key

navUp Sets or returns where to navigate when using the arrow-up 3


navigation key

opacity Sets or returns the opacity level for an element 3

order Sets or returns the order of the flexible item, relative to the rest 3

orphans Sets or returns the minimum number of lines for an element that 2
must be left at the bottom of a page when a page break occurs inside
an element

outline Sets or returns all the outline properties in one declaration 2

outlineColor Sets or returns the color of the outline around a element 2

outlineOffset Offsets an outline, and draws it beyond the border edge 3

outlineStyle Sets or returns the style of the outline around an element 2

outlineWidth Sets or returns the width of the outline around an element 2

overflow Sets or returns what to do with content that renders outside the 2
element box

435
www.Sohrabpoor.com

overflowX Specifies what to do with the left/right edges of the content, if it 3


overflows the element's content area

overflowY Specifies what to do with the top/bottom edges of the content, if it 3


overflows the element's content area

padding Sets or returns the padding of an element (can have up to four 1


values)

paddingBottom Sets or returns the bottom padding of an element 1

paddingLeft Sets or returns the left padding of an element 1

paddingRight Sets or returns the right padding of an element 1

paddingTop Sets or returns the top padding of an element 1

pageBreakAfter Sets or returns the page-break behavior after an element 2

pageBreakBefore Sets or returns the page-break behavior before an element 2

pageBreakInside Sets or returns the page-break behavior inside an element 2

perspective Sets or returns the perspective on how 3D elements are viewed 3

perspectiveOrigin Sets or returns the bottom position of 3D elements 3

436
www.Sohrabpoor.com

position Sets or returns the type of positioning method used for an element 2
(static, relative, absolute or fixed)

quotes Sets or returns the type of quotation marks for embedded quotations 2

resize Sets or returns whether or not an element is resizable by the user 3

right Sets or returns the right position of a positioned element 2

tableLayout Sets or returns the way to lay out table cells, rows, and columns 2

tabSize Sets or returns the length of the tab-character 3

textAlign Sets or returns the horizontal alignment of text 1

textAlignLast Sets or returns how the last line of a block or a line right before a 3
forced line break is aligned when text-align is "justify"

textDecoration Sets or returns the decoration of a text 1

textDecorationColor Sets or returns the color of the text-decoration 3

textDecorationLine Sets or returns the type of line in a text-decoration 3

textDecorationStyle Sets or returns the style of the line in a text decoration 3

textIndent Sets or returns the indentation of the first line of text 1

437
www.Sohrabpoor.com

textJustify Sets or returns the justification method used when text-align is 3


"justify"

textOverflow Sets or returns what should happen when text overflows the 3
containing element

textShadow Sets or returns the shadow effect of a text 3

textTransform Sets or returns the capitalization of a text 1

top Sets or returns the top position of a positioned element 2

transform Applies a 2D or 3D transformation to an element 3

transformOrigin Sets or returns the position of transformed elements 3

transformStyle Sets or returns how nested elements are rendered in 3D space 3

transition A shorthand property for setting or returning the four transition 3


properties

transitionProperty Sets or returns the CSS property that the transition effect is for 3

transitionDuration Sets or returns how many seconds or milliseconds a transition effect 3


takes to complete

transitionTimingFunction Sets or returns the speed curve of the transition effect 3

438
www.Sohrabpoor.com

transitionDelay Sets or returns when the transition effect will start 3

unicodeBidi Sets or returns whether the text should be overridden to support 2


multiple languages in the same document

verticalAlign Sets or returns the vertical alignment of the content in an element 1

visibility Sets or returns whether an element should be visible 2

whiteSpace Sets or returns how to handle tabs, line breaks and whitespace in a 1
text

width Sets or returns the width of an element 1

wordBreak Sets or returns line breaking rules for non-CJK scripts 3

wordSpacing Sets or returns the spacing between words in a text 1

wordWrap Allows long, unbreakable words to be broken and wrap to the next 3
line

widows Sets or returns the minimum number of lines for an element that 2
must be visible at the top of a page

zIndex Sets or returns the stack order of a positioned element 2

439
www.Sohrabpoor.com

HTML DOM Anchor Object


Anchor Object
The Anchor object represents an HTML <a> element.

Access an Anchor Object


You can access an <a> element by using getElementById():

Example
var x = document.getElementById("myAnchor");

Try it Yourself »

Create an Anchor Object


You can create an <a> element by using the document.createElement()
method:

Example
var x = document.createElement("A");

Try it Yourself »

Anchor Object Properties


= Property added in HTML5.

Property Description

charset Not supported in HTML5.


Sets or returns the value of the charset attribute of a link

download Sets or returns the value of the download attribute of a link

hash Sets or returns the anchor part of the href attribute value

440
www.Sohrabpoor.com

host Sets or returns the hostname and port part of the href attribute value

hostname Sets or returns the hostname part of the href attribute value

href Sets or returns the value of the href attribute of a link

hreflang Sets or returns the value of the hreflang attribute of a link

origin Returns the protocol, hostname and port part of the href attribute value

name Not supported in HTML5. Use element.id instead.


Sets or returns the value of the name attribute of a link

password Sets or returns the password part of the href attribute value

pathname Sets or returns the pathname part of the href attribute value

port Sets or returns the port part of the href attribute value

protocol Sets or returns the protocol part of the href attribute value

rel Sets or returns the value of the rel attribute of a link

rev Not supported in HTML5.


Sets or returns the value of the rev attribute of a link

search Sets or returns the querystring part of the href attribute value

441
www.Sohrabpoor.com

target Sets or returns the value of the target attribute of a link

text Sets or returns the text content of a link

type Sets or returns the value of the type attribute of a link

username Sets or returns the username part of the href attribute value

Standard Properties and Events


The Anchor object also supports the standard properties and events.

Related Pages
HTML tutorial: HTML links

HTML reference: HTML <a> tag

HTML DOM Abbreviation Object


Abbreviation Object
The Abbreviation object represents an HTML <abbr> element.

Access an Abbreviation Object


You can access an <abbr> element by using getElementById():

Example
var x = document.getElementById("myAbbr");

Try it Yourself »

442
www.Sohrabpoor.com

Create an Abbreviation Object


You can create an <abbr> element by using the document.createElement()
method:

Example
var x = document.createElement("ABBR");

Try it Yourself »

Standard Properties and Events


The Abbreviation object supports the standard properties and events.

Related Pages
HTML reference: HTML <abbr> tag

HTML DOM Address Object


Address Object
The Address object represents an HTML <address> element.

Access an Address Object


You can access an <address> element by using getElementById():

Example
var x = document.getElementById("myAdr");

Try it Yourself »

Create an Address Object


You can create an <address> element by using the
document.createElement() method:

443
www.Sohrabpoor.com

Example
var x = document.createElement("ADDRESS");

Try it Yourself »

Standard Properties and Events


The Address object supports the standard properties and events.

Related Pages
HTML reference: HTML <address> tag

HTML DOM Area Object


Area Object
The Area object represents an HTML <area> element.

Access an Area Object


You can access an <area> element by using getElementById():

Example
var x = document.getElementById("myArea");

Try it Yourself »

Create an Area Object


You can create an <area> element by using the document.createElement()
method:

Example
var x = document.createElement("AREA");

Try it Yourself »

444
www.Sohrabpoor.com

Area Object Properties


Property Description

alt Sets or returns the value of the alt attribute of an area

coords Sets or returns the value of the coords attribute of an area

hash Sets or returns the anchor part of the href attribute value

host Sets or returns the hostname and port part of the href attribute value

hostname Sets or returns the hostname part of the href attribute value

href Sets or returns the value of the href attribute of an area

noHref Not supported in HTML5.


Sets or returns the value of the nohref attribute of an area

origin Returns the protocol, hostname and port part of the href attribute value

password Sets or returns the password part of the href attribute value

pathname Sets or returns the pathname part of the href attribute value

port Sets or returns the port part of the href attribute value

445
www.Sohrabpoor.com

protocol Sets or returns the protocol part of the href attribute value

search Sets or returns the querystring part of the href attribute value

shape Sets or returns the value of the shape attribute of an area

target Sets or returns the value of the target attribute of an area

username Sets or returns the username part of the href attribute value

Standard Properties and Events


The Area object also supports the standard properties and events.

Related Pages
HTML reference: HTML <area> tag

HTML DOM Article Object


Article Object
The Article Object is new in HTML5.

The Article object represents an HTML <article> element.

Note: The <article> element is not supported in Internet Explorer 8 and


earlier versions.

446
www.Sohrabpoor.com

Access an Article Object


You can access an <article> element by using getElementById():

Example
var x = document.getElementById("myArticle");

Try it Yourself »

Create an Article Object


You can create an <article> element by using the document.createElement()
method:

Example
var x = document.createElement("ARTICLE");

Try it Yourself »

Standard Properties and Events


The Article object supports the standard properties and events.

Related Pages
HTML reference: HTML <article> tag

HTML DOM Aside Object

Aside Object
The Aside Object is new in HTML5.

The Aside object represents an HTML <aside> element.

447
www.Sohrabpoor.com

Note: The <aside> element is not supported in Internet Explorer 8 and


earlier versions.

Access an Aside Object


You can access an <aside> element by using getElementById():

Example
var x = document.getElementById("myAside");

Try it Yourself »

Create an Aside Object


You can create an <aside> element by using the document.createElement()
method:

Example
var x = document.createElement("ASIDE");

Try it Yourself »

Standard Properties and Events


The Aside object supports the standard properties and events.

Related Pages
HTML reference: HTML <aside> tag

HTML DOM Audio Object

Audio Object
The Audio Object is new in HTML5.

The Audio object represents an HTML <audio> element.

448
www.Sohrabpoor.com

Note: The <audio> element is not supported in Internet Explorer 8 and


earlier versions.

Access an Audio Object


You can access an <audio> element by using getElementById():

Example
var x = document.getElementById("myAudio");

Try it Yourself »

Create an Audio Object


You can create an <audio> element by using the document.createElement()
method:

Example
var x = document.createElement("AUDIO");

Try it Yourself »

Audio Object Properties


Property Description

audioTracks Returns an AudioTrackList object representing available audio tracks

autoplay Sets or returns whether the audio should start playing as soon as it is ready

buffered Returns a TimeRanges object representing the buffered parts of an audio

controller Returns the MediaController object representing the current media


controller of an audio

449
www.Sohrabpoor.com

controls Sets or returns whether an audio should have controls displayed


(play/pause etc)

crossOrigin Sets or returns the CORS settings of an audio

currentSrc Returns the URL of the current audio

currentTime Sets or returns the current playback position in an audio (in seconds)

defaultMuted Sets or returns whether the audio should be muted by default

defaultPlaybackRate Sets or returns whether the default playback speed of the audio

duration Returns the length of an audio(in seconds)

ended Returns whether the playback of the audio has ended

error Returns a MediaError object representing the error state of the audio

loop Sets or returns whether the audio should start playing over again, every
time it is finished

mediaGroup Sets or returns the name of the media group the audio(s) is a part of

muted Sets or returns whether the sound should be turned off

networkState Returns the current network state of an audio

450
www.Sohrabpoor.com

paused Sets or returns whether an audio is paused

playbackRate Sets or returns the speed of the audio playback

played Returns a TimeRanges object representing the played parts of the audio

preload Sets or returns the value of the preload attribute of an audio

readyState Returns the current ready state of an audio

seekable Returns a TimeRanges object representing the seekable parts of an audio

seeking Returns whether the user is currently seeking in the audio

src Sets or returns the value of the src attribute of an audio

textTracks Returns a TextTrackList object representing the available text tracks

volume Sets or returns the audio volume of an audio

451
www.Sohrabpoor.com

Audio Object Methods


Method Description

addTextTrack() Adds a new text track to the audio

canPlayType() Checks whether the browser can play the specified audio type

fastSeek() Seeks to a specified time in the audio player

getStartDate() Returns a new Date object, representing the current timeline offset

load() Re-loads the audio element

play() Starts playing the audio

pause() Pauses the currently playing audio

Standard Properties and Events


The Audio object also supports the standard properties and events.

HTML DOM Bold Object

Bold Object
The Bold object represents an HTML <b> element.

452
www.Sohrabpoor.com

Access a Bold Object


You can access a <b> element by using getElementById():

Example
var x = document.getElementById("myB");

Try it Yourself »

Create a Bold Object


You can create a <b> element by using the document.createElement()
method:

Example
var x = document.createElement("B");

Try it Yourself »

Standard Properties and Events


The Bold object supports the standard properties and events.

Related Pages
HTML tutorial: HTML Text Formatting Elements

HTML reference: HTML <b> tag

JavaScript reference: HTML DOM Strong Object

HTML DOM Base Object


Base Object
The Base object represents an HTML <base> element.

Access a Base Object


453
www.Sohrabpoor.com

You can access a <base> element by using getElementById():

Example
var x = document.getElementById("myBase");

Try it Yourself »

Create a Base Object


You can create a <base> element by using the document.createElement()
method:

Example
var x = document.createElement("BASE");

Try it Yourself »

Base Object Properties


Property Description

href Sets or returns the value of the href attribute in a base element

target Sets or returns the value of the target attribute in a base element

Standard Properties and Events


The Base object also supports the standard properties and events.

454
www.Sohrabpoor.com

HTML DOM Bdo Object


Bdo Object
The Bdo object represents an HTML <bdo> element.

Access a Bold Object


You can access a <bdo> element by using getElementById():

Example
var x = document.getElementById("myBdo");

Try it Yourself »

Create a Bdo Object


You can create a <bdo> element by using the document.createElement()
method:

Example
var x = document.createElement("BDO");

Try it Yourself »

Bdo Object Properties


Property Description

dir Sets or returns the value of the dir attribute of a <bdo>


element

Standard Properties and Events


The Bdo object supports the standard properties and events.

455
www.Sohrabpoor.com

HTML DOM Blockquote Object


Blockquote Object
The Blockquote object represents an HTML <blockquote> element.

Access a Blockquote Object


You can access a <blockquote> element by using getElementById():

Example
var x = document.getElementById("myBlockquote");

Try it Yourself »

Create a Blockquote Object


You can create a <blockquote> element by using the
document.createElement() method:

Example
var x = document.createElement("BLOCKQUOTE");

Try it Yourself »

Blockquote Object Properties


Property Description

cite Sets or returns the value of the cite attribute of a quotation

Standard Properties and Events


The Blockquote object also supports the standard properties and events.

456
www.Sohrabpoor.com

HTML DOM Body Object


Body Object
The Body object represents an HTML <body> element.

Access a Body Object


You can access a <body> element by using getElementsByTagName():

Example
var x = document.getElementsByTagName("BODY")[0];

Try it Yourself »

Tip: You can also access a <body> element by using


the document.body property.

Create a Body Object


You can create a <body> element by using the document.createElement()
method:

var x = document.createElement("BODY");

Body Object Properties


Property Description

aLink Not supported in HTML5. See CSS :active


Selector instead.
Sets or returns the color of an active link in a document

background Not supported in HTML5.


Use style.backgroundImage instead.
Sets or returns the background image for a document

457
www.Sohrabpoor.com

bgColor Not supported in HTML5.


Use style.backgroundColor instead.
Sets or returns the background color of a document

link Not supported in HTML5. See CSS :link Selector instead.


Sets or returns the color of unvisited links in a document

text Not supported in HTML5. Use style.color instead.


Sets or returns the color of the text in a document

vLink Not supported in HTML5. See CSS :visited


Selector instead.
Sets or returns the color of visited links in a document

Standard Properties and Events


The Body object also supports the standard properties and events.

HTML DOM BR Object


BR Object
The BR object represents an HTML <br> element.

Access a BR Object
You can access a <br> element by using getElementById():

Example
var x = document.getElementById("myBR");

Try it Yourself »

458
www.Sohrabpoor.com

Create a BR Object
You can create a <br> element by using the document.createElement()
method:

Example
var x = document.createElement("BR");

Try it Yourself »

BR Object Properties
Property Description

clear Not supported in HTML5. Use style.clear instead.


Sets or returns the flow of text around floating objects

Standard Properties and Events


The BR object also supports the standard properties and events.

HTML DOM Button Object


Button Object
The Button object represents an HTML <button> element.

Access a Button Object


You can access a <button> element by using getElementById():

Example
var x = document.getElementById("myBtn");

Try it Yourself »

459
www.Sohrabpoor.com

Create a Button Object


You can create a <button> element by using the document.createElement()
method:

Example
var x = document.createElement("BUTTON");

Try it Yourself »

Button Object Properties


= Property added in HTML5.

Property Description

autofocus Sets or returns whether a button should automatically get focus when the
page loads, or not

disabled Sets or returns whether a button is disabled, or not

form Returns a reference to the form that contains a button

formAction Sets or returns the value of the formaction attribute of a button

formEnctype Sets or returns the value of the formenctype attribute of a button

formMethod Sets or returns the value of the formmethod attribute of a button

formNoValidate Sets or returns whether the form-data should be validated or not, on


submission

460
www.Sohrabpoor.com

formTarget Sets or returns the value of the formtarget attribute of a button

name Sets or returns the value of the name attribute of a button

type Sets or returns the type of a button

value Sets or returns the value of the value attribute of a button

Standard Properties and Events


The Button object also supports the standard properties and events.

HTML DOM Canvas Object


Canvas Object
The Canvas Object is new in HTML5.

The HTML5 <canvas> tag is used to draw graphics, on the fly, with
JavaScript.

Access a Canvas Object


You can access a <canvas> element by using getElementById():

Example
var x = document.getElementById("myCanvas");

Try it Yourself »

Create a Canvas Object


You can create a <canvas> element by using the document.createElement()
method:

461
www.Sohrabpoor.com

Example
var x = document.createElement("CANVAS");

Try it Yourself »

Note: The <canvas> element has no drawing abilities of its own (it is only a
container for graphics) - you must use a script to actually draw the graphics.

The getContext() method returns an object that provides methods and


properties for drawing on the canvas.

This reference will cover the properties and methods of the getContext("2d")
object, which can be used to draw text, lines, boxes, circles, and more - on
the canvas.

Colors, Styles, and Shadows


Property Description

fillStyle Sets or returns the color, gradient, or pattern used to fill the drawing

strokeStyle Sets or returns the color, gradient, or pattern used for strokes

shadowColor Sets or returns the color to use for shadows

shadowBlur Sets or returns the blur level for shadows

shadowOffsetX Sets or returns the horizontal distance of the shadow from the shape

shadowOffsetY Sets or returns the vertical distance of the shadow from the shape

462
www.Sohrabpoor.com

Method Description

createLinearGradient() Creates a linear gradient (to use on canvas content)

createPattern() Repeats a specified element in the specified direction

createRadialGradient() Creates a radial/circular gradient (to use on canvas content)

addColorStop() Specifies the colors and stop positions in a gradient object

Line Styles
Property Description

lineCap Sets or returns the style of the end caps for a line

lineJoin Sets or returns the type of corner created, when two lines meet

lineWidth Sets or returns the current line width

miterLimit Sets or returns the maximum miter length

463
www.Sohrabpoor.com

Rectangles
Method Description

rect() Creates a rectangle

fillRect() Draws a "filled" rectangle

strokeRect() Draws a rectangle (no fill)

clearRect() Clears the specified pixels within a given rectangle

Paths
Method Description

fill() Fills the current drawing (path)

stroke() Actually draws the path you have defined

beginPath() Begins a path, or resets the current path

moveTo() Moves the path to the specified point in the canvas, without creating
a line

closePath() Creates a path from the current point back to the starting point

464
www.Sohrabpoor.com

lineTo() Adds a new point and creates a line from that point to the last
specified point in the canvas

clip() Clips a region of any shape and size from the original canvas

quadraticCurveTo() Creates a quadratic Bézier curve

bezierCurveTo() Creates a cubic Bézier curve

arc() Creates an arc/curve (used to create circles, or parts of circles)

arcTo() Creates an arc/curve between two tangents

isPointInPath() Returns true if the specified point is in the current path, otherwise
false

Transformations
Method Description

scale() Scales the current drawing bigger or smaller

rotate() Rotates the current drawing

translate() Remaps the (0,0) position on the canvas

465
www.Sohrabpoor.com

transform() Replaces the current transformation matrix for the drawing

setTransform() Resets the current transform to the identity matrix. Then


runs transform()

Text
Property Description

font Sets or returns the current font properties for text content

textAlign Sets or returns the current alignment for text content

textBaseline Sets or returns the current text baseline used when drawing text

Method Description

fillText() Draws "filled" text on the canvas

strokeText() Draws text on the canvas (no fill)

measureText() Returns an object that contains the width of the specified text

466
www.Sohrabpoor.com

Image Drawing
Method Description

drawImage() Draws an image, canvas, or video onto the canvas

Pixel Manipulation
Property Description

width Returns the width of an ImageData object

height Returns the height of an ImageData object

data Returns an object that contains image data of a specified ImageData object

Method Description

createImageData() Creates a new, blank ImageData object

getImageData() Returns an ImageData object that copies the pixel data for the specified
rectangle on a canvas

putImageData() Puts the image data (from a specified ImageData object) back onto the
canvas

467
www.Sohrabpoor.com

Compositing
Property Description

globalAlpha Sets or returns the current alpha or transparency value of the


drawing

globalCompositeOperation Sets or returns how a new image are drawn onto an existing image

Other
Method Description

save() Saves the state of the current context

restore() Returns previously saved path state and attributes

createEvent()

getContext()

toDataURL()

Standard Properties and Events


The canvas object also supports the standard properties and events.

468
www.Sohrabpoor.com

HTML DOM Caption Object


Caption Object
The Caption object represents an HTML <caption> element.

Access a Caption Object


You can access a <caption> element by using getElementById():

Example
var x = document.getElementById("myCaption");

Try it Yourself »

Create a Caption Object


You can create a <caption> element by using the document.createElement()
method:

Example
var x = document.createElement("CAPTION");

Try it Yourself »

Tip: You can also create a <caption> element by using


the createCaption method of the Table object.

Caption Object Properties


Property Description

align Not supported in HTML5. Use style.textAlign or style.captionSide instead.


Sets or returns the alignment of the caption

Standard Properties and Events


The Caption object also supports the standard properties and events.

469
www.Sohrabpoor.com

HTML DOM Cite Object


Cite Object
The Cite object represents an HTML <cite> element.

Access a Cite Object


You can access a <cite> element by using getElementById():

Example
var x = document.getElementById("myCite");

Try it Yourself »

Create a Cite Object


You can create a <cite> element by using the document.createElement()
method:

Example
var x = document.createElement("CITE");

Try it Yourself »

Standard Properties and Events


The Cite object also supports the standard properties and events.

HTML DOM Code Object


Code Object
The Code object represents an HTML <code> element.

Access a Code Object


You can access a <code> element by using getElementById():
470
www.Sohrabpoor.com

Example
var x = document.getElementById("myCode");

Try it Yourself »

Create a Code Object


You can create a <code> element by using the document.createElement()
method:

Example
var x = document.createElement("CODE");

Try it Yourself »

Standard Properties and Events


The Code object also supports the standard properties and events.

HTML DOM Column Object


Column Object
The Column object represents an HTML <col> element.

Access a Column Object


You can access a <col> element by using getElementById():

Example
var x = document.getElementById("myCol");

Try it Yourself »

Create a Column Object


You can create a <col> element by using the document.createElement()
method:

var x = document.createElement("COL");

471
www.Sohrabpoor.com

Column Object Properties


Property Description

span Sets or returns the value of the span attribute of a column

Standard Properties and Events


The Column object also supports the standard properties and events.

HTML DOM ColumnGroup Object


ColumnGroup Object
The ColumnGroup object represents an HTML <colgroup> element.

Access a ColumnGroup Object


You can access a <colgroup> element by using getElementById():

Example
var x = document.getElementById("myColgroup");

Try it Yourself »

Create a ColumnGroup Object


var x = document.createElement("COLGROUP");

472
www.Sohrabpoor.com

ColumnGroup Object Properties


Property Description

span Sets or returns the value of the span attribute of a column group

Standard Properties and Events


The ColumnGroup object also supports the standard properties and events.

HTML DOM Datalist Object


Datalist Object
The Datalist Object is new in HTML5.

The Datalist object represents an HTML <datalist> element.

Note: The <datalist> element is not supported in Internet Explorer 9 (and


earlier versions), or Safari.

Access a Datalist Object


You can access a <datalist> element by using getElementById():

Example
var x = document.getElementById("myDatalist");

Try it Yourself »

Create a Datalist Object


You can create a <datalist> element by using the document.createElement()
method:

473
www.Sohrabpoor.com

Example
var x = document.createElement("DATALIST");

Try it Yourself »

Datalist Object Collections


Collection Description

options Returns a collection of all the options in a datalist

Standard Properties and Events


The Datalist object also supports the standard properties and events.

HTML DOM DD Object


DD Object
The DD object represents an HTML <dd> element.

Access a DD Object
You can access a <dd> element by using getElementById():

Example
var x = document.getElementById("myDD");

Try it Yourself »

Create a DD Object
You can create a <dd> element by using the document.createElement()
method:

474
www.Sohrabpoor.com

Example
var x = document.createElement("DD");

Try it Yourself »

Standard Properties and Events


The DD object also supports the standard properties and events.

HTML DOM Del Object


Del Object
The Del object represents an HTML <del> element.

Access a Del Object


You can access a <del> element by using getElementById():

Example
var x = document.getElementById("myDel");

Try it Yourself »

Create a Del Object


You can create a <del> element by using the document.createElement()
method:

Example
var x = document.createElement("DEL");

Try it Yourself »

475
www.Sohrabpoor.com

Del Object Properties


Property Description

cite Sets or returns the value of the cite attribute of a deleted text

dateTime Sets or returns the value of the datetime attribute of a deleted text

Standard Properties and Events


The Del object also supports the standard properties and events.

HTML DOM Details Object


Details Object
The Details object represents an HTML <details> element.

Note: The <details> element is currently only supported in Chrome, Safari


6+ and Opera 15+.

Access a Details Object


You can access a <details> element by using getElementById():

Example
var x = document.getElementById("myDetails");

Try it Yourself »

Create a Details Object


You can create a <details> element by using the document.createElement()
method:

476
www.Sohrabpoor.com

Example
var x = document.createElement("DETAILS");

Try it Yourself »

Details Object Properties


Property Description

open Sets or returns whether the details should be visible (open)


to the user, or not

Standard Properties and Events


The Details object also supports the standard properties and events.

HTML DOM DFN Object


DFN Object
The DFN object represents an HTML <dfn> element.

Access a DFN Object


You can access a <dfn> element by using getElementById():

Example
var x = document.getElementById("myDFN");

Try it Yourself »

Create a DFN Object


You can create a <dfn> element by using the document.createElement()
method:

477
www.Sohrabpoor.com

Example
var x = document.createElement("DFN");

Try it Yourself »

Standard Properties and Events


The DFN object also supports the standard properties and events.

HTML DOM Dialog Object


Dialog Object
The Dialog Object is new in HTML5.

The Dialog object represents an HTML <dialog> element.

Note: The <dialog> element is currently only supported in Chrome 37+,


Safari 6+ and Opera 24+.

Access a Dialog Object


You can access a <dialog> element by using getElementById():

Example
var x = document.getElementById("myDialog");

Try it Yourself »

Create a Dialog Object


You can create a <dialog> element by using the document.createElement()
method:

Example
var x = document.createElement("DIALOG");

Try it Yourself »

478
www.Sohrabpoor.com

Dialog Object Properties


Property Description

open Sets or returns whether a dialog should be open or not

returnValue Sets or returns the dialog's return value

Dialog Object Methods


Method Description

close() Closes the dialog

show() Shows the dialog

showModal() Shows the dialog and makes it the top-most modal dialog

Standard Properties and Events


The Dialog object also supports the standard properties and events.

HTML DOM Div Object


Div Object
The Div object represents an HTML <div> element.

479
www.Sohrabpoor.com

Access a Div Object


You can access a <div> element by using getElementById():

Example
var x = document.getElementById("myDIV");

Try it Yourself »

Create a Div Object


You can create a <div> element by using the document.createElement()
method:

Example
var x = document.createElement("DIV");

Try it Yourself »

Div Object Properties


Property Description

align Not supported in HTML5. Use style.textAlign instead.


Sets or returns the value of the align attribute of the <div>
element

Standard Properties and Events


The Div object also supports the standard properties and events.

480
www.Sohrabpoor.com

HTML DOM DList Object


DList Object
The DList object represents an HTML <dl> element.

Access a DList Object


You can access a <dl> element by using getElementById():

Example
var x = document.getElementById("myDL");

Try it Yourself »

Create a DList Object


You can create a <dl> element by using the document.createElement()
method:

Example
var x = document.createElement("DL");

Try it Yourself »

Standard Properties and Events


The DList object supports the standard properties and events.

HTML DOM DT Object


DT Object
The DT object represents an HTML <dt> element.

Access a DT Object
You can access a <dt> element by using getElementById():

481
www.Sohrabpoor.com

Example
var x = document.getElementById("myDT");

Try it Yourself »

Create a DT Object
You can create a <dt> element by using the document.createElement()
method:

Example
var x = document.createElement("DT");

Try it Yourself »

Standard Properties and Events


The DT object also supports the standard properties and events.

HTML DOM Emphasized Object


Emphasized Object
The Emphasized object represents an HTML <em> element.

Access an Emphasized Object


You can access an <em> element by using getElementById():

Example
var x = document.getElementById("myEm");

Try it Yourself »

Create an Emphasized Object


You can create an <em> element by using the document.createElement()
method:

482
www.Sohrabpoor.com

Example
var x = document.createElement("EM");

Try it Yourself »

Standard Properties and Events


The Emphasized object supports the standard properties and events.

HTML DOM Embed Object


Embed Object
The Embed Object is new in HTML5.

The Embed object represents an HTML <embed> element.

Access an Embed Object


You can access an <embed> element by using getElementById():

Example
var x = document.getElementById("myEmbed");

Try it Yourself »

Create an Embed Object


You can create an <embed> element by using the
document.createElement() method:

Example
var x = document.createElement("EMBED");

Try it Yourself »

483
www.Sohrabpoor.com

Embed Object Properties


Property Description

height Sets or returns the value of the height attribute in an embed element

src Sets or returns the value of the src attribute in an embed element

type Sets or returns the value of the type attribute in an embed element

width Sets or returns the value of the width attribute in an embed element

Standard Properties and Events


The Embed object also supports the standard properties and events.

HTML DOM Fieldset Object


Fieldset Object
The Fieldset object represents an HTML <fieldset> element.

Access a Fieldset Object


You can access a <fieldset> element by using getElementById():

Example
var x = document.getElementById("myFieldset");

Try it Yourself »

Tip: You can also access a Fieldset object by searching through


the elements collection of a form.

484
www.Sohrabpoor.com

Create a Fieldset Object


You can create a <fieldset> element by using the document.createElement()
method:

Example
var x = document.createElement("FIELDSET");

Try it Yourself »

Fieldset Object Properties


= Property added in HTML5.

Property Description

disabled Sets or returns whether a fieldset is disabled, or not

form Returns a reference to the form that contains the fieldset

name Sets or returns the value of the name attribute of a fieldset

type Returns which type of form element the fieldset is

Standard Properties and Events


The Fieldset object also supports the standard properties and events.

485
www.Sohrabpoor.com

HTML DOM Figcaption Object


Figcaption Object
The Figcaption Object is new in HTML5.

The Figcaption object represents an HTML <figcaption> element.

Access a Figcaption Object


You can access a <figcaption> element by using getElementById():

Example
var x = document.getElementById("myFigCap");

Try it Yourself »

Create a Figcaption Object


You can create a <figcaption> element by using the
document.createElement() method:

Example
var x = document.createElement("FIGCAPTION");

Try it Yourself »

Standard Properties and Events


The Figcaption object also supports the standard properties and events.

HTML DOM Figure Object


Figure Object
The Figure Object is new in HTML5.

The Figure object represents an HTML <figure> element.

486
www.Sohrabpoor.com

Access a Figure Object


You can access a <figure> element by using getElementById():

Example
var x = document.getElementById("myFigure");

Try it Yourself »

Create a Figure Object


You can create a <figure> element by using the document.createElement()
method:

Example
var x = document.createElement("FIGURE");

Try it Yourself »

Standard Properties and Events


The Figure object also supports the standard properties and events.

HTML DOM Footer Object

Footer Object
The Footer Object is new in HTML5.

The Footer object represents an HTML <footer> element.

Note: The <footer> element is not supported in Internet Explorer 8 and


earlier versions.

Access a Footer Object


You can access a <footer> element by using getElementById():

487
www.Sohrabpoor.com

Example
var x = document.getElementById("myFooter");

Try it Yourself »

Create a Footer Object


You can create a <footer> element by using the document.createElement()
method:

Example
var x = document.createElement("FOOTER");

Try it Yourself »

Standard Properties and Events


The Footer object also supports the standard properties and events.

HTML DOM Form Object


Form Object
The Form object represents an HTML <form> element.

Access a Form Object


You can access a <form> element by using getElementById():

Example
var x = document.getElementById("myForm");

Try it Yourself »

Tip: You can also access a <form> element by using the forms collection.

Create a Form Object


You can create a <form> element by using the document.createElement()
method:

488
www.Sohrabpoor.com

Example
var x = document.createElement("FORM");

Try it Yourself »

Form Object Collections


Collection Description

elements Returns a collection of all elements in a form

Form Object Properties


= Property added in HTML5.

Property Description

acceptCharset Sets or returns the value of the accept-charset attribute in a form

action Sets or returns the value of the action attribute in a form

autocomplete Sets or returns the value of the autocomplete attribute in a form

encoding Alias of enctype

enctype Sets or returns the value of the enctype attribute in a form

length Returns the number of elements in a form

method Sets or returns the value of the method attribute in a form

489
www.Sohrabpoor.com

name Sets or returns the value of the name attribute in a form

noValidate Sets or returns whether the form-data should be validated or not, on submission

target Sets or returns the value of the target attribute in a form

Form Object Methods


Method Description

reset() Resets a form

submit() Submits a form

Standard Properties and Events


The Form object also supports the standard properties and events.

HTML DOM Head Object


Head Object
The Head object represents an HTML <head> element.

Access a Head Object


You can access a <head> element by using getElementsByTagName():

var x = document.getElementsByTagName("HEAD")[0];

490
www.Sohrabpoor.com

Create a Head Object


You can create a <head> element by using the document.createElement()
method:

var x = document.createElement("HEAD");

Standard Properties and Events


The Head object also supports the standard properties and events.

HTML DOM Header Object


Header Object
The Header Object is new in HTML5.

The Header object represents an HTML <header> element.

Note: The <header> element is not supported in Internet Explorer 8 and


earlier versions.

Access a Header Object


You can access a <header> element by using getElementById():

Example
var x = document.getElementById("myHeader");

Try it Yourself »

Create a Header Object


You can create a <header> element by using the document.createElement()
method:

Example
var x = document.createElement("HEADER");

Try it Yourself »

491
www.Sohrabpoor.com

Standard Properties and Events


The Header object also supports the standard properties and events.

Related Pages
HTML tutorial: HTML5 Semantic Elements

HTML reference: HTML <header> tag

JavaScript reference: HTML DOM Footer Object

HTML DOM Heading Object


Heading Object
The Heading object represents an HTML heading element: <h1> to <h6>.

Access a Heading Object


You can access a heading element by using getElementById():

Example
var x = document.getElementById("myHeading");

Try it Yourself »

Create a Heading Object


You can create a heading element by using the document.createElement()
method:

Example
var x = document.createElement("H1");

Try it Yourself »

492
www.Sohrabpoor.com

Heading Object Properties


Property Description

align Not supported in HTML5. Use style.textAlign instead.


Sets or returns the value of the align attribute of the heading element

Standard Properties and Events


The Heading object also supports the standard properties and events.

HTML DOM HR Object


HR Object
The HR object represents an HTML <hr> element.

Access a HR Object
You can access a <hr> element by using getElementById():

Example
var x = document.getElementById("myHR");

Try it Yourself »

Create a HR Object
You can create a <hr> element by using the document.createElement()
method:

Example
var x = document.createElement("HR");

Try it Yourself »

493
www.Sohrabpoor.com

HR Object Properties
Property Description

align Not supported in HTML5. Use style.textAlign instead.


Sets or returns the alignment of a horizontal line

color Not supported in HTML5. Use style.color instead.


Sets or returns the color of a horizontal line

noshade Not supported in HTML5.


Sets or returns whether a horizontal line should render in one solid color
(noshaded)

size Not supported in HTML5. Use style.height instead.


Sets or returns the height of a horizontal line

width Not supported in HTML5. Use style.width instead.


Sets or returns the width of a horizontal line

DOM HTML Object


HTML Object
The HTML object represents an HTML <html> element.

Access a HTML Object


You can access the <html> element by using getElementsByTagName():

494
www.Sohrabpoor.com

Example
var x = document.getElementsByTagName("HTML")[0];

Try it Yourself »

Tip: You can also access the <html> element by using


the document.documentElement property.

Standard Properties and Events


The HTML object also supports the standard properties and events.

Related Pages
HTML tutorial: HTML Introduction

HTML reference: HTML <html> tag

HTML DOM Italic Object


Italic Object
The Italic object represents an HTML <i> element.

Access an Italic Object


You can access an <i> element by using getElementById():

Example
var x = document.getElementById("myItalic");

Try it Yourself »

Create an Italic Object


You can create an <i> element by using the document.createElement()
method:

495
www.Sohrabpoor.com

Example
var x = document.createElement("I");

Try it Yourself »

Standard Properties and Events


The Italic object supports the standard properties and events.

Related Pages
HTML tutorial: HTML Text Formatting Elements

HTML reference: HTML <i> tag

JavaScript reference: HTML DOM Emphasized Object

HTML DOM IFrame Object


IFrame Object
The IFrame object represents an HTML <iframe> element.

Access an IFrame Object


You can access an <iframe> element by using getElementById():

Example
var x = document.getElementById("myFrame");

Try it Yourself »

Tip: You can also access an <iframe> element by using


the window.frames property.

Create an IFrame Object


You can create an <iframe> element by using the document.createElement()
method:

496
www.Sohrabpoor.com

Example
var x = document.createElement("IFRAME");

Try it Yourself »

IFrame Object Properties


= Property added in HTML5.

Property Description

align Not supported in HTML5. Use style.cssFloat instead.


Sets or returns the value of the align attribute in an
iframe

contentDocument Returns the document object generated by an iframe

contentWindow Returns the window object generated by an iframe

frameBorder Not supported in HTML5. Use style.border instead.


Sets or returns the value of the frameborder attribute
in an iframe

height Sets or returns the value of the height attribute in an


iframe

longDesc Not supported in HTML5.


Sets or returns the value of the longdesc attribute in an
iframe

marginHeight Not supported in HTML5. Use style.margin instead.


Sets or returns the value of the marginheight attribute
in an iframe

497
www.Sohrabpoor.com

marginWidth Not supported in HTML5. Use style.margin instead.


Sets or returns the value of the marginwidth attribute
in an iframe

name Sets or returns the value of the name attribute in an


iframe

sandbox Returns the value of the sandbox attribute in an iframe

scrolling Not supported in HTML5.


Sets or returns the value of the scrolling attribute in an
iframe

seamless Sets or returns whether an iframe should look like it is


a part of the containing document (no borders or
scrollbars), or not

src Sets or returns the value of the src attribute in an


iframe

srcdoc Sets or returns the value of the srcdoc attribute in an


iframe

width Sets or returns the value of the width attribute in an


iframe

Standard Properties and Events


The IFrame object also supports the standard properties and events.

498
www.Sohrabpoor.com

HTML DOM Image Object


Image Object
The Image object represents an HTML <img> element.

Access an Image Object


You can access an <img> element by using getElementById():

Example
var x = document.getElementById("myImg");

Try it Yourself »

Tip: You can also access an <img> element by using the images collection.

Create an Image Object


You can create an <img> element by using the document.createElement()
method:

Example
var x = document.createElement("IMG");

Try it Yourself »

Image Object Properties


Property Description

align Not supported in HTML5. Use style.cssFloat instead.


Sets or returns the value of the align attribute of an image

alt Sets or returns the value of the alt attribute of an image

499
www.Sohrabpoor.com

border Not supported in HTML5. Use style.border instead.


Sets or returns the value of the border attribute of an image

complete Returns whether or not the browser is finished loading an image

crossOrigin Sets or returns the CORS settings of an image

height Sets or returns the value of the height attribute of an image

hspace Not supported in HTML5. Use style.margin instead.


Sets or returns the value of the hspace attribute of an image

isMap Sets or returns whether an image should be part of a server-side image-map,


or not

longDesc Not supported in HTML5.


Sets or returns the value of the longdesc attribute of an image

name Not supported in HTML5. Use id instead.


Sets or returns the value of the name attribute of an image

naturalHeight Returns the original height of an image

naturalWidth Returns the original width of an image

src Sets or returns the value of the src attribute of an image

useMap Sets or returns the value of the usemap attribute of an image

500
www.Sohrabpoor.com

vspace Not supported in HTML5. Use style.margin instead.


Sets or returns the value of the vspace attribute of an image

width Sets or returns the value of the width attribute of an image

Standard Properties and Events


The Image object also supports the standard properties and events.

HTML DOM Ins Object


Ins Object
The Ins object represents an HTML <ins> element.

Access an Ins Object


You can access an <ins> element by using getElementById():

Example
var x = document.getElementById("myIns");

Try it Yourself »

Create an Ins Object


You can create an <ins> element by using the document.createElement()
method:

Example
var x = document.createElement("INS");

Try it Yourself »

501
www.Sohrabpoor.com

Ins Object Properties


Property Description

cite Sets or returns the value of the cite attribute of an inserted text

dateTime Sets or returns the value of the datetime attribute of an inserted text

Standard Properties and Events


The Ins object also supports the standard properties and events.

HTML DOM Input Button Object


Input Button Object
The Input Button object represents an HTML <input> element with
type="button".

Access an Input Button Object


You can access an <input> element with type="button" by using
getElementById():

Example
var x = document.getElementById("myBtn");

Try it Yourself »

Tip: You can also access <input type="button"> by searching through


the elements collection of a form.

502
www.Sohrabpoor.com

Create an Input Button Object


You can create an <input> element with type="button" by using the
document.createElement() method:

Example
var x = document.createElement("INPUT");
x.setAttribute("type", "button");

Try it Yourself »

Input Button Object Properties


= Property added in HTML5.

Property Description

autofocus Sets or returns whether an input button should automatically get focus when
the page loads

defaultValue Sets or returns the default value of an input button

disabled Sets or returns whether an input button is disabled, or not

form Returns a reference to the form that contains the input button

name Sets or returns the value of the name attribute of an input button

type Returns which type of form element the input button is

value Sets or returns the value of the value attribute of an input button

503
www.Sohrabpoor.com

Standard Properties and Events


The Input Button object also supports the standard properties and events.

HTML DOM Input Checkbox Object


Input Checkbox Object
The Input Checkbox object represents an HTML <input> element with
type="checkbox".

Access an Input Checkbox Object


You can access an <input> element with type="checkbox" by using
getElementById():

Example
var x = document.getElementById("myCheck");

Try it Yourself »

Tip: You can also access <input type="checkbox"> by searching through


the elements collection of a form.

Create an Input Checkbox Object


You can create an <input> element with type="checkbox" by using the
document.createElement() method:

Example
var x = document.createElement("INPUT");
x.setAttribute("type", "checkbox");

Try it Yourself »

Input Checkbox Object Properties


= Property added in HTML5.

504
www.Sohrabpoor.com

Property Description

autofocus Sets or returns whether a checkbox should automatically get focus when the
page loads

checked Sets or returns the checked state of a checkbox

defaultChecked Returns the default value of the checked attribute

defaultValue Sets or returns the default value of a checkbox

disabled Sets or returns whether a checkbox is disabled, or not

form Returns a reference to the form that contains the checkbox

indeterminate Sets or returns the indeterminate state of the checkbox

name Sets or returns the value of the name attribute of a checkbox

required Sets or returns whether the checkbox must be checked before submitting a
form

type Returns which type of form element the checkbox is

value Sets or returns the value of the value attribute of a checkbox

505
www.Sohrabpoor.com

Standard Properties and Events


The Input Checkbox object also supports the standard properties and events.

HTML DOM Input Color Object


Input Color Object
The Input Color Object is new in HTML5.

The Input Color object represents an HTML <input> element with


type="color".

Note: <input> elements with type="color" are not supported in Internet


Explorer or Safari.

Access an Input Color Object


You can access an <input> element with type="color" by using
getElementById():

Example
var x = document.getElementById("myColor");

Try it Yourself »

Tip: You can also access <input type="color"> by searching through


the elements collection of a form.

Create an Input Color Object


You can create an <input> element with type="color" by using the
document.createElement() method:

Example
var x = document.createElement("INPUT");
x.setAttribute("type", "color");

Try it Yourself »

506
www.Sohrabpoor.com

Input Color Object Properties


Property Description

autocomplete Sets or returns the value of the autocomplete attribute of a color picker

autofocus Sets or returns whether a color picker should automatically get focus when the
page loads

defaultValue Sets or returns the default value of a color picker

disabled Sets or returns whether a color picker is disabled, or not

form Returns a reference to the form that contains the color picker

list Returns a reference to the <datalist> element that contains the color picker

name Sets or returns the value of the name attribute of a color picker

type Returns which type of form element the color picker is

value Sets or returns the value of the value attribute of a color picker

Standard Properties and Events


The Input Color object also supports the standard properties and events.

507
www.Sohrabpoor.com

HTML DOM Input Date Object


Input Date Object
The Input Date Object is new in HTML5.

The Input Date object represents an HTML <input> element with type="date".

Note: <input> elements with type="date" do not show as any date field/calendar in Firefox.

Access an Input Date Object


You can access an <input> element with type="date" by using getElementById():

Example
var x = document.getElementById("myDate");
Try it Yourself »

Tip: You can also access <input type="date"> by searching through the elements collection
of a form.

Create an Input Date Object


You can create an <input> element with type="date" by using the document.createElement()
method:

Example
var x = document.createElement("INPUT");
x.setAttribute("type", "date");
Try it Yourself »

Input Date Object Properties


Property Description

autocomplete Sets or returns the value of the autocomplete attribute of a date field

508
www.Sohrabpoor.com

autofocus Sets or returns whether a date field should automatically get focus when the
page loads

defaultValue Sets or returns the default value of a date field

disabled Sets or returns whether a date field is disabled, or not

form Returns a reference to the form that contains the date field

list Returns a reference to the datalist that contains the date field

max Sets or returns the value of the max attribute of the date field

min Sets or returns the value of the min attribute of the date field

name Sets or returns the value of the name attribute of a date field

readOnly Sets or returns whether the date field is read-only, or not

required Sets or returns whether the date field must be filled out before submitting a
form

step Sets or returns the value of the step attribute of the date field

type Returns which type of form element the date field is

value Sets or returns the value of the value attribute of a date field

509
www.Sohrabpoor.com

Input Date Object Methods


Method Description

stepDown() Decrements the value of the date field by a specified number

stepUp() Increments the value of the date field by a specified number

Standard Properties and Events


The Input Date object also supports the standard properties and events.

HTML DOM Input Datetime Object


Input Datetime Object
The Input Datetime Object is new in HTML5.

The Input Datetime object represents an HTML <input> element with


type="datetime".

Note: <input> elements with type="datetime" do not show as any datetime


field/calendar in any of the major browsers, except Safari.

Access an Input Datetime Object


You can access an <input> element with type="datetime" by using
getElementById():

Example
var x = document.getElementById("myDatetime");

Try it Yourself »

Tip: You can also access <input type="datetime"> by searching through


the elements collection of a form.

510
www.Sohrabpoor.com

Create an Input Datetime Object


You can create an <input> element with type="datetime" by using the
document.createElement() method:

Example
var x = document.createElement("INPUT");
x.setAttribute("type", "datetime");

Try it Yourself »

Input Datetime Object Properties


Property Description

autocomplete Sets or returns the value of the autocomplete attribute of a datetime field

autofocus Sets or returns whether a datetime field should automatically get focus when
the page loads

defaultValue Sets or returns the default value of a datetime field

disabled Sets or returns whether a datetime field is disabled, or not

form Returns a reference to the form that contains the datetime field

list Returns a reference to the datalist that contains the datetime field

max Sets or returns the value of the max attribute of the datetime field

min Sets or returns the value of the min attribute of the datetime field

511
www.Sohrabpoor.com

name Sets or returns the value of the name attribute of a datetime field

readOnly Sets or returns whether the datetime field is read-only, or not

required Sets or returns whether the datetime field must be filled out before
submitting a form

step Sets or returns the value of the step attribute of the datetime field

type Returns which type of form element the datetime field is

value Sets or returns the value of the value attribute of a datetime field

Input Datetime Object Methods


Method Description

stepDown() Decrements the value of the datetime field by a specified number

stepUp() Increments the value of the datetime field by a specified number

Standard Properties and Events


The Input Datetime object also supports the standard properties and events.

512
www.Sohrabpoor.com

HTML DOM Input


DatetimeLocal Object
Input DatetimeLocal Object
The Input DatetimeLocal Object is new in HTML5.

The Input DatetimeLocal object represents an HTML <input> element with


type="datetime-local".

Note: <input> elements with type="datetime-local" do not show as any


datetime field/calendar in Firefox.

Access an Input DatetimeLocal Object


You can access an <input> element with type="datetime-local" by using
getElementById():

Example
var x = document.getElementById("myLocalDate");

Try it Yourself »

Tip: You can also access <input type="datetime-local"> by searching


through the elements collection of a form.

Create an Input DatetimeLocal Object


You can create an <input> element with type="datetime-local" by using the
document.createElement() method:

Example
var x = document.createElement("INPUT");
x.setAttribute("type", "datetime-local");

Try it Yourself »

513
www.Sohrabpoor.com

Input DatetimeLocal Object Properties


Property Description

autocomplete Sets or returns the value of the autocomplete attribute of a local datetime field

autofocus Sets or returns whether a local datetime field should automatically get focus
upon page load

defaultValue Sets or returns the default value of a local datetime field

disabled Sets or returns whether a local datetime field is disabled, or not

form Returns a reference to the form that contains the local datetime field

list Returns a reference to the datalist that contains the local datetime field

max Sets or returns the value of the max attribute of the local datetime field

min Sets or returns the value of the min attribute of the local datetime field

name Sets or returns the value of the name attribute of a local datetime field

readOnly Sets or returns whether the local datetime field is read-only, or not

required Sets or returns whether the local datetime field must be filled out before
submitting a form

514
www.Sohrabpoor.com

step Sets or returns the value of the step attribute of the local datetime field

type Returns which type of form element the local datetime field is

value Sets or returns the value of the value attribute of a local datetime field

Input DatetimeLocal Object Methods


Method Description

stepDown() Decrements the value of the datetime field by a specified number

stepUp() Increments the value of the datetime field by a specified number

Standard Properties and Events


The Input DatetimeLocal object also supports the
standard properties and events.

HTML DOM Input Email Object


Input Email Object
The Input Email Object is new in HTML5.

The Input Email object represents an HTML <input> element with


type="email".

Note: <input> elements with type="email" are not supported in Internet


Explorer 9 (and earlier versions), or Safari.

515
www.Sohrabpoor.com

Access an Input Email Object


You can access an <input> element with type="email" by using
getElementById():

Example
var x = document.getElementById("myEmail");

Try it Yourself »

Tip: You can also access <input type="email"> by searching through


the elements collection of a form.

Create an Input Email Object


You can create an <input> element with type="email" by using the
document.createElement() method:

Example
var x = document.createElement("INPUT");
x.setAttribute("type", "email");

Try it Yourself »

Input Email Object Properties


Property Description

autocomplete Sets or returns the value of the autocomplete attribute of an email field

autofocus Sets or returns whether an email field should automatically get focus when
the page loads

defaultValue Sets or returns the default value of an email field

disabled Sets or returns whether an email field is disabled, or not

516
www.Sohrabpoor.com

form Returns a reference to the form that contains the email field

list Returns a reference to the datalist that contains the email field

maxLength Sets or returns the value of the maxlength attribute of an email field

multiple Sets or returns whether a user is allowed to enter more than one email
address in the email field

name Sets or returns the value of the name attribute of an email field

pattern Sets or returns the value of the pattern attribute of an email field

placeholder Sets or returns the value of the placeholder attribute of an email field

readOnly Sets or returns whether the email field is read-only, or not

required Sets or returns whether the email field must be filled out before submitting a
form

size Sets or returns the value of the size attribute of the email field

type Returns which type of form element the email field is

value Sets or returns the value of the value attribute of an email field

517
www.Sohrabpoor.com

Standard Properties and Events


The Input Email object also supports the standard properties and events.

HTML DOM Input FileUpload Object


Input FileUpload Object
The Input FileUpload object represents an HTML <input> element with
type="file".

Access an Input FileUpload Object


You can access an <input> element with type="file" by using
getElementById():

Example
var x = document.getElementById("myFile");

Try it Yourself »

Tip: You can also access <input type="file"> by searching through


the elements collection of a form.

Create an Input FileUpload Object


You can create an <input> element with type="file" by using the
document.createElement() method:

Example
var x = document.createElement("INPUT");
x.setAttribute("type", "file");

Try it Yourself »

Input FileUpload Object Properties


= Property added in HTML5.

518
www.Sohrabpoor.com

Property Description

accept Sets or returns the value of the accept attribute of the file upload button

autofocus Sets or returns whether a file upload button should automatically get focus upon
page load

defaultValue Sets or returns the default value of the file upload button

disabled Sets or returns whether the file upload button is disabled, or not

files Returns a FileList object that represents the file or files selected with the file
upload button

form Returns a reference to the form that contains the file upload button

multiple Sets or returns whether a user is allowed to select more than one file in the file
upload field

name Sets or returns the value of the name attribute of the file upload button

required Sets or returns whether a file in the file upload field must be selected before
submitting a form

type Returns which type of form element the file upload button is

value Returns the path or the name of the selected file

519
www.Sohrabpoor.com

Standard Properties and Events


The Input FileUpload object also supports the
standard properties and events.

HTML DOM Input Hidden Object


Input Hidden Object
The Input Hidden object represents an HTML <input> element with
type="hidden".

Access an Input Hidden Object


You can access an <input> element with type="hidden" by using
getElementById():

Example
var x = document.getElementById("myInput");

Try it Yourself »

Tip: You can also access <input type="hidden"> by searching through


the elements collection of a form.

Create an Input Hidden Object


You can create an <input> element with type="hidden" by using the
document.createElement() method:

Example
var x = document.createElement("INPUT");
x.setAttribute("type", "hidden");

Try it Yourself »

Input Hidden Object Properties

520
www.Sohrabpoor.com

Property Description

defaultValue Sets or returns the default value of the hidden input field

form Returns a reference to the form that contains the hidden input field

name Sets or returns the value of the name attribute of the hidden input field

type Returns which type of form element a hidden input field is

value Sets or returns the value of the value attribute of the hidden input field

Standard Properties and Events


The Input Hidden object also supports the standard properties and events.

HTML DOM Input Image Object


Input Image Object
The Input Image object represents an HTML <input> element with
type="image".

Access an Input Image Object


You can access an <input> element with type="image" by using
getElementById():

var x = document.getElementById("myImage");

Tip: You can also access <input type="image"> by searching through


the elements collection of a form.

521
www.Sohrabpoor.com

Create an Input Image Object


You can create an <input> element with type="image" by using the
document.createElement() method:

var x = document.createElement("INPUT");
x.setAttribute("type", "image");

Input Image Object Properties


= Property added in HTML5.

Property Description

alt Sets or returns the value of the alt attribute of an input image

autofocus Sets or returns whether an input image should automatically get focus when
the page loads

defaultValue Sets or returns the default value of an input image

disabled Sets or returns whether an input image is disabled, or not

form Returns a reference to the form that contains the input image

formAction Sets or returns the value of the formaction attribute of an input image

formEnctype Sets or returns the value of the formenctype attribute of an input image

formMethod Sets or returns the value of the formmethod attribute of an input image

522
www.Sohrabpoor.com

formNoValidate Sets or returns whether the form-data should be validated or not, on


submission

formTarget Sets or returns the value of the formtarget attribute an input image

height Sets or returns the value of the height attribute of the input image

name Sets or returns the value of the name attribute of an input image

src Sets or returns the value of the src attribute of the input image

type Returns which type of form element the input image is

value Sets or returns the value of the value attribute of an input image

width Sets or returns the value of the width attribute of the input image

Standard Properties and Events


The Input Image object also supports the standard properties and events.

523
www.Sohrabpoor.com

HTML DOM Input Month Object


Input Month Object
The Input Month Object is new in HTML5.

The Input Month object represents an HTML <input> element with


type="month".

Note: <input> elements with type="month" do not show as any date


field/calendar in Firefox.

Access an Input Month Object


You can access an <input> element with type="month" by using
getElementById():

Example
var x = document.getElementById("myMonth");

Try it Yourself »

Tip: You can also access <input type="month"> by searching through


the elements collection of a form.

Create an Input Month Object


You can create an <input> element with type="month" by using the
document.createElement() method:

Example
var x = document.createElement("INPUT");
x.setAttribute("type", "month");

Try it Yourself »

524
www.Sohrabpoor.com

Input Month Object Properties


Property Description

autocomplete Sets or returns the value of the autocomplete attribute of a month field

autofocus Sets or returns whether a month field should automatically get focus when
the page loads

defaultValue Sets or returns the default value of a month field

disabled Sets or returns whether a month field is disabled, or not

form Returns a reference to the form that contains the month field

list Returns a reference to the datalist that contains the month field

max Sets or returns the value of the max attribute of the month field

min Sets or returns the value of the min attribute of the month field

name Sets or returns the value of the name attribute of a month field

readOnly Sets or returns whether the month field is read-only, or not

required Sets or returns whether the month field must be filled out before submitting
a form

525
www.Sohrabpoor.com

step Sets or returns the value of the step attribute of the month field

type Returns which type of form element the month field is

value Sets or returns the value of the value attribute of a month field

Input Month Object Methods


Method Description

stepDown() Decrements the value of the month field by a specified number

stepUp() Increments the value of the month field by a specified number

Standard Properties and Events


The Input Month object also supports the standard properties and events.

HTML DOM Input Number Object


Input Number Object
The Input Number Object is new in HTML5.

The Input Number object represents an HTML <input> element with


type="number".

Note: <input> elements with type="number" are not supported in Internet


Explorer 9 and earlier versions.

526
www.Sohrabpoor.com

Access an Input Number Object


You can access an <input> element with type="number" by using
getElementById():

Example
var x = document.getElementById("myNumber");

Try it Yourself »

Tip: You can also access <input type="number"> by searching through


the elements collection of a form.

Create an Input Number Object


You can create an <input> element with type="number" by using the
document.createElement() method:

Example
var x = document.createElement("INPUT");
x.setAttribute("type", "number");

Try it Yourself »

Input Number Object Properties


Property Description

autocomplete Sets or returns the value of the autocomplete attribute of a number field

autofocus Sets or returns whether a number field should automatically get focus when
the page loads

defaultValue Sets or returns the default value of a number field

disabled Sets or returns whether a number field is disabled, or not

527
www.Sohrabpoor.com

form Returns a reference to the form that contains the number field

list Returns a reference to the datalist that contains the number field

max Sets or returns the value of the max attribute of a number field

min Sets or returns the value of the min attribute of a number field

name Sets or returns the value of the name attribute of a number field

placeholder Sets or returns the value of the placeholder attribute of a number field

readOnly Sets or returns whether the number field is read-only, or not

required Sets or returns whether the number field must be filled out before submitting
a form

step Sets or returns the value of the step attribute of a number field

type Returns which type of form element the number field is

value Sets or returns the value of the value attribute of a number field

528
www.Sohrabpoor.com

Input Number Object Methods


Method Description

stepDown() Decrements the value of the input number by a specified number

stepUp() Increments the value of the input number by a specified number

Standard Properties and Events


The Input Number object also supports the standard properties and events.

HTML DOM Input Password Object


Input Password Object
The Input Password object represents an HTML <input> element with
type="password".

Access an Input Password Object


You can access an <input> element with type="password" by using
getElementById():

Example
var x = document.getElementById("myPsw");

Try it Yourself »

Tip: You can also access <input type="password"> by searching through


the elements collection of a form.

529
www.Sohrabpoor.com

Create an Input Password Object


You can create an <input> element with type="password" by using the
document.createElement() method:

Example
var x = document.createElement("INPUT");
x.setAttribute("type", "password");

Try it Yourself »

Input Password Object Properties


= Property added in HTML5.

Property Description

autocomplete Sets or returns the value of the autocomplete attribute of a password field

autofocus Sets or returns whether a password field should automatically get focus when
the page loads

defaultValue Sets or returns the default value of a password field

disabled Sets or returns whether the password field is disabled, or not

form Returns a reference to the form that contains the password field

maxLength Sets or returns the value of the maxlength attribute of a password field

name Sets or returns the value of the name attribute of a password field

530
www.Sohrabpoor.com

pattern Sets or returns the value of the pattern attribute of a password field

placeholder Sets or returns the value of the placeholder attribute of a password field

readOnly Sets or returns whether a password field is read-only, or not

required Sets or returns whether the password field must be filled out before
submitting a form

size Sets or returns the value of the size attribute of a password field

type Returns which type of form element a password field is

value Sets or returns the value of the value attribute of the password field

Input Password Object Methods


Method Description

select() Selects the content of a password field

Standard Properties and Events


The Input Password object also supports the standard properties and events.

531
www.Sohrabpoor.com

HTML DOM Input Radio Object


Input Radio Object
The Input Radio object represents an HTML <input> element with
type="radio".

Access an Input Radio Object


You can access an <input> element with type="radio" by using
getElementById():

Example
var x = document.getElementById("myRadio");

Try it Yourself »

Tip: You can also access <input type="radio"> by searching through


the elements collection of a form.

Create an Input Radio Object


You can create an <input> element with type="radio" by using the
document.createElement() method:

Example
var x = document.createElement("INPUT");
x.setAttribute("type", "radio");

Try it Yourself »

Input Radio Object Properties


= Property added in HTML5.

Property Description

autofocus Sets or returns whether a radio button should automatically get focus when the
page loads

532
www.Sohrabpoor.com

checked Sets or returns the checked state of a radio button

defaultChecked Returns the default value of the checked attribute

defaultValue Sets or returns the default value of a radio button

disabled Sets or returns whether the radio button is disabled, or not

form Returns a reference to the form that contains the radio button

name Sets or returns the value of the name attribute of a radio button

required Sets or returns whether the radio button must be checked before submitting a
form

type Returns which type of form element the radio button is

value Sets or returns the value of the value attribute of the radio button

Standard Properties and Events


The Input Radio object also supports the standard properties and events.

533
www.Sohrabpoor.com

HTML DOM Input Range Object


Input Range Object
The Input Range Object is new in HTML5.

The Input Range object represents an HTML <input> element with type="range".

Note: <input> elements with type="range" are not supported in Internet Explorer 9 and
earlier versions.

Access an Input Range Object


You can access an <input> element with type="range" by using getElementById():

Example
var x = document.getElementById("myRange");
Try it Yourself »

Tip: You can also access <input type="range"> by searching through the elements collection
of a form.

Create an Input Range Object


You can create an <input> element with type="range" by using the document.createElement()
method:

Example
var x = document.createElement("INPUT");
x.setAttribute("type", "range");
Try it Yourself »

534
www.Sohrabpoor.com

Input Range Object Properties


Property Description

autocomplete Sets or returns the value of the autocomplete attribute of a slider control

autofocus Sets or returns whether a slider control should automatically get focus when
the page loads

defaultValue Sets or returns the default value of a slider control

disabled Sets or returns whether a slider control is disabled, or not

form Returns a reference to the form that contains the slider control

list Returns a reference to the datalist that contains the slider control

max Sets or returns the value of the max attribute of the slider control

min Sets or returns the value of the min attribute of the slider control

name Sets or returns the value of the name attribute of a slider control

step Sets or returns the value of the step attribute of the slider control

type Returns which type of form element the slider control is

535
www.Sohrabpoor.com

value Sets or returns the value of the value attribute of a slider control

Input Range Object Methods


Method Description

stepDown() Decrements the value of the slider control by a specified number

stepUp() Increments the value of the slider control by a specified number

Standard Properties and Events


The Input Range object also supports the standard properties and events.

HTML DOM Input Reset Object


Input Reset Object
The Input Reset object represents an HTML <input> element with
type="reset".

Access an Input Reset Object


You can access an <input> element with type="reset" by using
getElementById():

Example
var x = document.getElementById("myReset");

Try it Yourself »

536
www.Sohrabpoor.com

Tip: You can also access <input type="reset"> by searching through


the elements collection of a form.

Create an Input Reset Object


You can create an <input> element with type="reset" by using the
document.createElement() method:

Example
var x = document.createElement("INPUT");
x.setAttribute("type", "reset");

Try it Yourself »

Input Reset Object Properties


= Property added in HTML5.

Property Description

autofocus Sets or returns whether a reset button should automatically get focus when the
page loads

defaultValue Sets or returns the default value of a reset button

disabled Sets or returns whether the reset button is disabled, or not

form Returns a reference to the form that contains the reset button

name Sets or returns the value of the name attribute of a reset button

type Returns which type of form element the reset button is

value Sets or returns the value of the value attribute of the reset button

537
www.Sohrabpoor.com

Standard Properties and Events


The Input Reset object also supports the standard properties and events.

HTML DOM Input Search Object


Input Search Object
The Input Search Object is new in HTML5.

The Input Search object represents an HTML <input> element with type="search".

Access an Input Search Object


You can access an <input> element with type="search" by using getElementById():

Example
var x = document.getElementById("mySearch");

Try it Yourself »

Tip: You can also access <input type="search"> by searching through


the elements collection of a form.

Create an Input Search Object


You can create an <input> element with type="search" by using the
document.createElement() method:

Example
var x = document.createElement("INPUT");
x.setAttribute("type", "search");

Try it Yourself »

538
www.Sohrabpoor.com

Input Search Object Properties


Property Description

autocomplete Sets or returns the value of the autocomplete attribute of a search field

autofocus Sets or returns whether a search field should automatically get focus when the
page loads

defaultValue Sets or returns the default value of a search field

disabled Sets or returns whether a search field is disabled, or not

form Returns a reference to the form that contains the search field

list Returns a reference to the datalist that contains the search field

maxLength Sets or returns the value of the maxlength attribute of a search field

name Sets or returns the value of the name attribute of a search field

pattern Sets or returns the value of the pattern attribute of a search field

placeholder Sets or returns the value of the placeholder attribute of a search field

readOnly Sets or returns whether the search field is read-only, or not

539
www.Sohrabpoor.com

required Sets or returns whether the search field must be filled out before submitting a
form

size Sets or returns the value of the size attribute of the search field

type Returns which type of form element the search field is

value Sets or returns the value of the value attribute of a search field

Standard Properties and Events


The Input Search object also supports the standard properties and events.

HTML DOM Input Submit Object


Input Submit Object
The Input Submit object represents an HTML <input> element with
type="submit".

Access an Input Submit Object


You can access an <input> element with type="submit" by using
getElementById():

Example
var x = document.getElementById("mySubmit");

Try it Yourself »

Tip: You can also access <input type="submit"> by searching through


the elements collection of a form.

540
www.Sohrabpoor.com

Create an Input Submit Object


You can create an <input> element with type="submit" by using the
document.createElement() method:

Example
var x = document.createElement("INPUT");
x.setAttribute("type", "submit");

Try it Yourself »

Input Submit Object Properties


= Property added in HTML5.

Property Description

autofocus Sets or returns whether a submit button should automatically get focus when
the page loads

defaultValue Sets or returns the default value of a submit button

disabled Sets or returns whether the submit button is disabled, or not

form Returns a reference to the form that contains the submit button

formAction Sets or returns the value of the formaction attribute of a submit button

formEnctype Sets or returns the value of the formenctype attribute of a submit button

formMethod Sets or returns the value of the formmethod attribute of a submit button

541
www.Sohrabpoor.com

formNoValidate Sets or returns whether the form-data should be validated or not, on


submission

formTarget Sets or returns the value of the formtarget attribute of a submit button

name Sets or returns the value of the name attribute of a submit button

type Returns which type of form element the submit button is

value Sets or returns the value of the value attribute of the submit button

Standard Properties and Events


The Input Submit object also supports the standard properties and events.

HTML DOM Input Text Object


Input Text Object
The Input Text object represents an HTML <input> element with
type="text".

Access an Input Text Object


You can access an <input> element with type="text" by using
getElementById():

Example
var x = document.getElementById("myText");

Try it Yourself »

Tip: You can also access <input type="text"> by searching through


the elements collection of a form.

542
www.Sohrabpoor.com

Create an Input Text Object


You can create an <input> element with type="text" by using the
document.createElement() method:

Example
var x = document.createElement("INPUT");
x.setAttribute("type", "text");

Try it Yourself »

Input Text Object Properties


= Property added in HTML5.

Property Description

autocomplete Sets or returns the value of the autocomplete attribute of a text field

autofocus Sets or returns whether a text field should automatically get focus when the
page loads

defaultValue Sets or returns the default value of a text field

disabled Sets or returns whether the text field is disabled, or not

form Returns a reference to the form that contains the text field

list Returns a reference to the datalist that contains the text field

maxLength Sets or returns the value of the maxlength attribute of a text field

543
www.Sohrabpoor.com

name Sets or returns the value of the name attribute of a text field

pattern Sets or returns the value of the pattern attribute of a text field

placeholder Sets or returns the value of the placeholder attribute of a text field

readOnly Sets or returns whether a text field is read-only, or not

required Sets or returns whether the text field must be filled out before submitting a
form

size Sets or returns the value of the size attribute of a text field

type Returns which type of form element a text field is

value Sets or returns the value of the value attribute of the text field

Standard Properties and Events


The Input Text object also supports the standard properties and events.

HTML DOM Input Time Object


Input Time Object
The Input Time Object is new in HTML5.

The Input Time object represents an HTML <input> element with type="time".

Note: <input> elements with type="time" do not show as any time field in Firefox.

544
www.Sohrabpoor.com

Access an Input Time Object


You can access an <input> element with type="time" by using getElementById():

Example
var x = document.getElementById("myTime");

Try it Yourself »

Tip: You can also access <input type="time"> by searching through the elements collection
of a form.

Create an Input Time Object


You can create an <input> element with type="time" by using the document.createElement()
method:

Example
var x = document.createElement("INPUT");
x.setAttribute("type", "time");

Try it Yourself »

Input Time Object Properties


Property Description

autocomplete Sets or returns the value of the autocomplete attribute of a time field

autofocus Sets or returns whether a time field should automatically get focus when the
page loads

defaultValue Sets or returns the default value of a time field

disabled Sets or returns whether a time field is disabled, or not

545
www.Sohrabpoor.com

form Returns a reference to the form that contains the time field

list Returns a reference to the datalist that contains the time field

max Sets or returns the value of the max attribute of the time field

min Sets or returns the value of the min attribute of the time field

name Sets or returns the value of the name attribute of a time field

readOnly Sets or returns whether the time field is read-only, or not

required Sets or returns whether the time field must be filled out before submitting a
form

step Sets or returns the value of the step attribute of the time field

type Returns which type of form element the time field is

value Sets or returns the value of the value attribute of a time field

546
www.Sohrabpoor.com

Input Time Object Methods


Method Description

stepDown() Decrements the value of the time field by a specified number

stepUp() Increments the value of the time field by a specified number

Standard Properties and Events


The Input Time object also supports the standard properties and events.

HTML DOM Input URL Object


Input URL Object
The Input URL Object is new in HTML5.

The Input URL object represents an HTML <input> element with type="url".

Note: <input> elements with type="url" are not supported in Internet


Explorer 9 (and earlier versions), or Safari.

Access an Input URL Object


You can access an <input> element with type="url" by using
getElementById():

Example
var x = document.getElementById("myUrl");

Try it Yourself »

Tip: You can also access <input type="url"> by searching through


the elements collection of a form.

547
www.Sohrabpoor.com

Create an Input URL Object


You can create an <input> element with type="url" by using the
document.createElement() method:

Example
var x = document.createElement("INPUT");
x.setAttribute("type", "url");

Try it Yourself »

Input URL Object Properties


Property Description

autocomplete Sets or returns the value of the autocomplete attribute of a URL field

autofocus Sets or returns whether a URL field should automatically get focus when the
page loads

defaultValue Sets or returns the default value of a URL field

disabled Sets or returns whether a URL field is disabled, or not

form Returns a reference to the form that contains the URL field

list Returns a reference to the datalist that contains the URL field

maxLength Sets or returns the value of the maxlength attribute of a URL field

name Sets or returns the value of the name attribute of a URL field

548
www.Sohrabpoor.com

pattern Sets or returns the value of the pattern attribute of a URL field

placeholder Sets or returns the value of the placeholder attribute of a URL field

readOnly Sets or returns whether the URL field is read-only, or not

required Sets or returns whether the URL field must be filled out before submitting a
form

size Sets or returns the value of the size attribute of the URL field

type Returns which type of form element the URL field is

value Sets or returns the value of the value attribute of a URL field

Standard Properties and Events


The Input URL object also supports the standard properties and events.

HTML DOM Input Week Object


Input Week Object
The Input Week Object is new in HTML5.

The Input Week object represents an HTML <input> element with


type="week".

Note: <input> elements with type="week" are not supported in Internet


Explorer or Firefox.

549
www.Sohrabpoor.com

Access an Input Week Object


You can access an <input> element with type="week" by using
getElementById():

Example
var x = document.getElementById("myWeek");

Try it Yourself »

Tip: You can also access <input type="week"> by searching through


the elements collection of a form.

Create an Input Week Object


You can create an <input> element with type="week" by using the
document.createElement() method:

Example
var x = document.createElement("INPUT");
x.setAttribute("type", "week");

Try it Yourself »

Input Week Object Properties


Property Description

autocomplete Sets or returns the value of the autocomplete attribute of a week field

autofocus Sets or returns whether a week field should automatically get focus when the
page loads

defaultValue Sets or returns the default value of a week field

disabled Sets or returns whether a week field is disabled, or not

550
www.Sohrabpoor.com

form Returns a reference to the form that contains the week field

list Returns a reference to the datalist that contains the week field

max Sets or returns the value of the max attribute of the week field

min Sets or returns the value of the min attribute of the week field

name Sets or returns the value of the name attribute of a week field

readOnly Sets or returns whether the week field is read-only, or not

required Sets or returns whether the week field must be filled out before submitting a
form

step Sets or returns the value of the step attribute of the week field

type Returns which type of form element the week field is

value Sets or returns the value of the value attribute of a week field

551
www.Sohrabpoor.com

Input Week Object Methods


Method Description

stepDown() Decrements the value of the week field by a specified number

stepUp() Increments the value of the week field by a specified number

Standard Properties and Events


The Input Week object also supports the standard properties and events.

HTML DOM Kbd Object


Kbd Object
The Kbd object represents an HTML <kbd> element.

Access a Kbd Object


You can access a <kbd> element by using getElementById():

Example
var x = document.getElementById("myKbd");

Try it Yourself »

Create a Kbd Object


You can create a <kbd> element by using the document.createElement()
method:

Example
var x = document.createElement("KBD");

552
www.Sohrabpoor.com

Try it Yourself »

Standard Properties and Events


The Kbd object supports the standard properties and events.

HTML DOM Keygen Object


Keygen Object
The Keygen Object is new in HTML5.

The Keygen object represents an HTML <keygen> element.

Note: The <keygen> element is not supported in Internet Explorer / Edge.

Access a Keygen Object


You can access a <keygen> element by using getElementById():

Example
var x = document.getElementById("myKeygen");

Try it Yourself »

Create a Keygen Object


You can create a <keygen> element by using the document.createElement()
method:

Example
var x = document.createElement("KEYGEN");

Try it Yourself »

553
www.Sohrabpoor.com

Keygen Object Properties


Property Description

autofocus Sets or returns whether a keygen field automatically gets focus when the page
loads, or not

challenge Sets or returns the value of the challenge attribute of a keygen field

disabled Sets or returns whether a keygen field is disabled, or not

form Returns a reference to the form that contains the keygen field

keytype Sets or returns the value of the keytype attribute of a keygen field

name Sets or returns the value of the name attribute of a keygen field

type Returns which type of form element the keygen field is

Standard Properties and Events


The Keygen object also supports the standard properties and events.

554
www.Sohrabpoor.com

HTML DOM Label Object


Label Object
The Label object represents an HTML <label> element.

Access a Label Object


You can access a <label> element by using getElementById():

Example
var x = document.getElementById("myLabel");

Try it Yourself »

Create a Label Object


You can create a <label> element by using the document.createElement()
method:

Example
var x = document.createElement("LABEL");

Try it Yourself »

Label Object Properties


Property Description

control Returns the labeled control

form Returns a reference to the form that contains the label

htmlFor Sets or returns the value of the for attribute of a label

555
www.Sohrabpoor.com

Standard Properties and Events


The Label object also supports the standard properties and events.

HTML DOM Legend Object


Legend Object
The Legend object represents an HTML <legend> element.

Access a Legend Object


You can access a <legend> element by using getElementById():

Example
var x = document.getElementById("myLegend");

Try it Yourself »

Create a Legend Object


You can create a <legend> element by using the document.createElement()
method:

Example
var x = document.createElement("LEGEND");

Try it Yourself »

Legend Object Properties


Property Description

form Returns a reference to the form that contains the legend

556
www.Sohrabpoor.com

Standard Properties and Events


The Legend object also supports the standard properties and events.

HTML DOM Li Object


Li Object
The Li object represents an HTML <li> element.

Access a Li Object
You can access a <li> element by using getElementById():

Example
var x = document.getElementById("myLi");

Try it Yourself »

Create a Li Object
You can create a <li> element by using the document.createElement()
method:

Example
var x = document.createElement("LI");

Try it Yourself »

Li Object Properties
Property Description

value Sets or returns the value of the value attribute of a list item

557
www.Sohrabpoor.com

Standard Properties and Events


The Li object also supports the standard properties and events.

HTML DOM Link Object


Link Object
The Link object represents an HTML <link> element.

Access a Link Object


You can access a <link> element by using getElementById():

Example
var x = document.getElementById("myLink");

Try it Yourself »

Create a Link Object


You can create a <link> element by using the document.createElement()
method:

Example
var x = document.createElement("LINK");

Try it Yourself »

558
www.Sohrabpoor.com

Link Object Properties


= Property added in HTML5.

Property Description

charset Not supported in HTML5.


Sets or returns the character encoding of the linked document

crossOrigin Sets or returns the the CORS settings of the linked document

disabled Sets or returns whether the linked document is disabled, or not

href Sets or returns the URL of the linked document

hreflang Sets or returns the language code of the linked document

media Sets or returns the media type for the link element

rel Sets or returns the relationship between the current document and the linked
document

rev Not supported in HTML5.


Sets or returns the reverse relationship from the linked document to the current
document

sizes Returns the value of the sizes attribute of the linked resource

type Sets or returns the content type of the linked document

559
www.Sohrabpoor.com

Standard Properties and Events


The Link object also supports the standard properties and events.

HTML DOM Map Object


Map Object
The Map object represents an HTML <map> element.

Access a Map Object


You can access a <map> element by using getElementById():

Example
var x = document.getElementById("myMap");

Try it Yourself »

Create a Map Object


You can create a <map> element by using the document.createElement()
method:

Example
var x = document.createElement("MAP");

Try it Yourself »

Map Object Collections


Collection Description

areas Returns a collection of all <area> elements in an image-map

560
www.Sohrabpoor.com

images Returns a collection of all <img> and <object> elements associated with the
image-map

Map Object Properties


Property Description

name Sets or returns the value of the name attribute of an image-map

Standard Properties and Events


The Map object also supports the standard properties and events.

HTML DOM Mark Object


Mark Object
The Mark Object is new in HTML5.

The Mark object represents an HTML <mark> element.

Note: The <mark> element is not supported in Internet Explorer 8 and


earlier versions.

Access a Mark Object


You can access a <mark> element by using getElementById():

Example
var x = document.getElementById("myMark");

Try it Yourself »

561
www.Sohrabpoor.com

Create a Mark Object


You can create a <mark> element by using the document.createElement()
method:

Example
var x = document.createElement("MARK");

Try it Yourself »

Standard Properties and Events


The Mark object supports the standard properties and events.

HTML DOM Menu Object


Menu Object
The Menu object represents an HTML <menu> element.

Note: The <menu> element is currently NOT supported in any of the major
browsers.

Access a Menu Object


You can access a <menu> element by using getElementById():

var x = document.getElementById("myMenu");

Create a Menu Object


You can create a <menu> element by using the document.createElement()
method:

var x = document.createElement("MENU");

562
www.Sohrabpoor.com

Menu Object Properties


Property Description

label Sets or returns the value of the label attribute of the menu

type Sets or returns the value of the type attribute of the menu

Standard Properties and Events


The Menu object also supports the standard properties and events.

HTML DOM MenuItem Object


MenuItem Object
The MenuItem Object is new in HTML5.

The MenuItem object represents an HTML <menuitem> element.

Note: The <menuitem> element is currently ONLY supported in Firefox.

Access a MenuItem Object


You can access a <menuitem> element by using getElementById():

var x = document.getElementById("myMenuItem");

Create a MenuItem Object


You can create a <menuitem> element by using the
document.createElement() method:

var x = document.createElement("MENUITEM");

563
www.Sohrabpoor.com

MenuItem Object Properties


Property Description

checked Sets or returns whether the menu item should be checked

command Sets or returns the value of the command attribute of the menu item

default Sets or returns whether the menu item should be the default command

disabled Sets or returns whether the menu item should be disabled

icon Sets or returns an image that represents the menu item

label Sets or returns the value of the label attribute of the menu item

radiogroup Sets or returns the value of the radiogroup attribute of the menu item

type Sets or returns the value of the type attribute of the menu item

Standard Properties and Events


The MenuItem object also supports the standard properties and events.

564
www.Sohrabpoor.com

HTML DOM Meta Object


Meta Object
The Meta object represents an HTML <meta> element.

Access a Meta Object


You can access a <meta> element by using getElementsByTagName():

var x = document.getElementsByTagName("META")[0];

Try it Yourself »

Create a Meta Object


You can create a <meta> element by using the document.createElement()
method:

Example
var x = document.createElement("META");

Try it Yourself »

Meta Object Properties


Property Description

content Sets or returns the value of the content attribute of a meta element

httpEquiv Sets or returns an HTTP header for the information in the content attribute

name Sets or returns a name for the information in the content attribute

scheme Not supported in HTML5.


Sets or returns how the value of the content attribute should be interpreted

565
www.Sohrabpoor.com

Standard Properties and Events


The Meta object also supports the standard properties and events.

HTML DOM Meter Object


Meter Object
The Meter Object is new in HTML5.

The Meter object represents an HTML <meter> element.

Note: The <meter> element is not supported in Internet Explorer / Edge or


Safari 5 (and earlier versions).

Access a Meter Object


You can access a <meter> element by using getElementById():

Example
var x = document.getElementById("myMeter");

Try it Yourself »

Create a Meter Object


You can create a <meter> element by using the document.createElement()
method:

Example
var x = document.createElement("METER");

Try it Yourself »

566
www.Sohrabpoor.com

Meter Object Properties


Property Description

high Sets or returns the value of the high attribute in a gauge

labels Returns a list of <label> elements that are labels for the gauge

low Sets or returns the value of the low attribute in a gauge

max Sets or returns the value of the max attribute in a gauge

min Sets or returns the value of the min attribute in a gauge

optimum Sets or returns the value of the optimum attribute in a gauge

value Sets or returns the value of the value attribute in a gauge

Standard Properties and Events


The Meter object also supports the standard properties and events.

HTML DOM Nav Object


Nav Object
The Nav Object is new in HTML5.

The Nav object represents an HTML <nav> element.

567
www.Sohrabpoor.com

Note: The <nav> element is not supported in Internet Explorer 8 and earlier
versions.

Access a Nav Object


You can access a <nav> element by using getElementById():

Example
var x = document.getElementById("myNav");

Try it Yourself »

Create a Nav Object


You can create a <nav> element by using the document.createElement()
method:

Example
var x = document.createElement("NAV");

Try it Yourself »

Standard Properties and Events


The Nav object supports the standard properties and events.

HTML DOM Object Object


Object Object
The Object object represents an HTML <object> element.

Access an Object Object


You can access an <object> element by using getElementById():

Example
var x = document.getElementById("myObject");

Try it Yourself »

568
www.Sohrabpoor.com

Create an Object Object


You can create an <object> element by using the document.createElement()
method:

Example
var x = document.createElement("OBJECT");

Try it Yourself »

Object Properties
= Property added in HTML5.

Property Description

align Not supported in HTML5. Use style.cssFloat instead.


Sets or returns the alignment of the object according to the surrounding text

archive Not supported in HTML5.


Sets or returns a string that can be used to implement your own archive
functionality for the object

border Not supported in HTML5. Use style.border instead.


Sets or returns the border around the object

code Not supported in HTML5.


Sets or returns the URL of the file that contains the compiled Java class

codeBase Not supported in HTML5.


Sets or returns the URL of the component

codeType Not supported in HTML5.

569
www.Sohrabpoor.com

data Sets or returns the URL of the resource to be used by the object

declare Not supported in HTML5.

form Returns a reference to the object's parent form

height Sets or returns the height of the object

hspace Not supported in HTML5. Use style.margin instead.


Sets or returns the horizontal margin of the object

name Sets or returns the name of the object

standby Not supported in HTML5.


Sets or returns a message when loading the object

type Sets or returns the content type for data downloaded via the data attribute

useMap Sets or returns the name of a client-side image map to be used with the object

vspace Not supported in HTML5. Use style.margin instead.


Sets or returns the vertical margin of the object

width Sets or returns the width of the object

Standard Properties and Events


The Object object also supports the standard properties and events.

570
www.Sohrabpoor.com

HTML DOM Ol Object


Ol Object
The Ol object represents an HTML <ol> element.

Access an Ol Object
You can access an <ol> element by using getElementById():

Example
var x = document.getElementById("myOl");

Try it Yourself »

Create an Ol Object
You can create an <ol> element by using the document.createElement()
method:

Example
var x = document.createElement("OL");

Try it Yourself »

Ol Object Properties
Property Description

compact Not supported in HTML5. Use style.lineHeight instead.


Sets or returns whether the list should render smaller than normal, or not

reversed Sets or returns whether the list order should be descending or not

571
www.Sohrabpoor.com

start Sets or returns the value of the start attribute of an ordered list

type Sets or returns the value of the type attribute of an ordered list

Standard Properties and Events


The Ol object also supports the standard properties and events.

HTML DOM OptionGroup Object


OptionGroup Object
The OptionGroup object represents an HTML <optgroup> element.

Access an OptionGroup Object


You can access an <optgroup> element by using getElementById():

Example
var x = document.getElementById("myOptgroup");

Try it Yourself »

Create an OptionGroup Object


You can create an <optgroup> element by using the
document.createElement() method:

Example
var x = document.createElement("OPTGROUP");

Try it Yourself »

572
www.Sohrabpoor.com

OptionGroup Object Properties


Property Description

disabled Sets or returns whether an option-group is disabled, or not

label Sets or returns the value the label attribute of an option-group

Standard Properties and Events


The OptionGroup object also supports the standard properties and events.

HTML DOM Option Object


Option Object
The Option object represents an HTML <option> element.

Access an Option Object


You can access an <option> element by using getElementById():

Example
var x = document.getElementById("myOption");

Try it Yourself »

Tip: You can also access an Option object by searching through


the elements collection of a form, or the optionscollection of a drop-down list.

Create an Option Object


You can create an <option> element by using the document.createElement()
method:

573
www.Sohrabpoor.com

Example
var x = document.createElement("OPTION");

Try it Yourself »

Option Object Properties


Property Description

defaultSelected Returns the default value of the selected attribute

disabled Sets or returns whether an option is disabled, or not

form Returns a reference to the form that contains the option

index Sets or returns the index position of an option in a drop-down list

label Sets or returns the value of the label attribute of an option in a drop-down
list

selected Sets or returns the selected state of an option

text Sets or returns the text of an option

value Sets or returns the value of an option to be sent to the server

Standard Properties and Events


The Option object also supports the standard properties and events.

574
www.Sohrabpoor.com

HTML DOM Output Object


Output Object
The Output Object is new in HTML5.

The Output object represents an HTML <output> element.

Note: The <output> element is not supported in Internet Explorer / Edge.

Access an Output Object


You can access an <output> element by using getElementById():

Example
var x = document.getElementById("myOutput");

Try it Yourself »

Tip: You can also access an <output> element by searching through


the elements collection of a form.

Create an Output Object


You can create an <output> element by using the document.createElement()
method:

Example
var x = document.createElement("OUTPUT");

Try it Yourself »

Output Object Properties


Property Description

defaultValue Sets or returns the default value of an <output> element

575
www.Sohrabpoor.com

form Returns a reference to the form that contains the <output> element

htmlFor Returns the value of the for attribute of an <output> element

labels Returns a list of <label> elements associated with the <output> element

name Sets or returns the value of the name attribute of an <output> element

type Returns which type of HTML element the Output object represents

value Sets or returns the value of an <output> element

Standard Properties and Events


The Output object also supports the standard properties and events.

HTML DOM Paragraph Object


Paragraph Object
The Paragraph object represents an HTML <p> element.

Access a Paragraph Object


You can access a <p> element by using getElementById():

Example
var x = document.getElementById("myP");

Try it Yourself »

576
www.Sohrabpoor.com

Create a Paragraph Object


You can create a <p> element by using the document.createElement()
method:

Example
var x = document.createElement("P");

Try it Yourself »

Paragraph Object Properties


Property Description

align Not supported in HTML5. Use style.textAlign instead.


Sets or returns the value of the align attribute of the paragraph

Standard Properties and Events


The Paragraph object also supports the standard properties and events.

HTML DOM Parameter Object


Parameter Object
The Parameter object represents an HTML <param> element.

The <param> element is used to define parameters for plugins embedded


with an <object> element.

Access a Parameter Object


You can access a <param> element by using getElementById():

577
www.Sohrabpoor.com

Example
var x = document.getElementById("myParam");

Try it Yourself »

Create a Parameter Object


You can create a <param> element by using the document.createElement()
method:

Example
var x = document.createElement("PARAM");

Try it Yourself »

Parameter Object Properties


Property Description

name Sets or returns the value of the name attribute of a parameter

value Sets or returns the value of the value attribute of a parameter

Standard Properties and Events


The Parameter object also supports the standard properties and events.

HTML DOM Pre Object


Pre Object
The Pre object represents an HTML <pre> element.

578
www.Sohrabpoor.com

Access a Pre Object


You can access a <pre> element by using getElementById():

Example
var x = document.getElementById("myPre");

Try it Yourself »

Create a Pre Object


You can create a <pre> element by using the document.createElement()
method:

Example
var x = document.createElement("PRE");

Try it Yourself »

Pre Object Properties


Property Description

width Not supported in HTML5. Use style.width instead.


Sets or returns the value of the width attribute of the preformatted text

Standard Properties and Events


The Pre object also supports the standard properties and events.

579
www.Sohrabpoor.com

HTML DOM Progress Object


Progress Object
The Progress Object is new in HTML5.

The Progress object represents an HTML <progress> element.

The <progress> element represents the progress of a task.

Access a Progress Object


You can access a <progress> element by using getElementById():

Example
var x = document.getElementById("myProgress");

Try it Yourself »

Create a Progress Object


You can create a <progress> element by using the
document.createElement() method:

Example
var x = document.createElement("PROGRESS");

Try it Yourself »

Progress Object Properties


Property Description

labels Returns a list of the progress bar's labels (if any)

max Sets or returns the value of the max attribute of a progress bar

580
www.Sohrabpoor.com

position Returns the current position of the progress bar

value Sets or returns the value of the value attribute of a progress bar

Standard Properties and Events


The Progress object also supports the standard properties and events.

HTML DOM Quote Object


Quote Object
The Quote object represents an HTML <q> element.

Access a Quote Object


You can access a <q> element by using getElementById():

Example
var x = document.getElementById("myQuote");

Try it Yourself »

Create a Quote Object


You can create a <q> element by using the document.createElement()
method:

Example
var x = document.createElement("Q");

Try it Yourself »

581
www.Sohrabpoor.com

Quote Object Properties


Property Description

cite Sets or returns the value of the cite attribute of a quotation

Standard Properties and Events


The Quote object also supports the standard properties and events.

HTML DOM S Object


S Object
The S object represents an HTML <s> element.

Access a S Object
You can access a <s> element by using getElementById():

Example
var x = document.getElementById("myS");

Try it Yourself »

Create a S Object
You can create a <s> element by using the document.createElement()
method:

Example
var x = document.createElement("S");

Try it Yourself »

582
www.Sohrabpoor.com

Standard Properties and Events


The S object also supports the standard properties and events.

HTML DOM Samp Object


Samp Object
The Samp object represents an HTML <samp> element.

Access a Samp Object


You can access a <samp> element by using getElementById():

Example
var x = document.getElementById("mySamp");

Try it Yourself »

Create a Samp Object


You can create a <samp> element by using the document.createElement()
method:

Example
var x = document.createElement("SAMP");

Try it Yourself »

Standard Properties and Events


The Samp object supports the standard properties and events.

583
www.Sohrabpoor.com

HTML DOM Script Object


Script Object
The Script object represents an HTML <script> element.

Access a Script Object


You can access a <script> element by using getElementById():

Example
var x = document.getElementById("myScript");

Try it Yourself »

Tip: You can also access a <script> element by using the scripts collection.

Create a Script Object


You can create a <script> element by using the document.createElement()
method:

Example
var x = document.createElement("SCRIPT");

Try it Yourself »

Script Object Properties


= Property added in HTML5.

Property Description

async Sets or returns whether a script should be executed asynchronously as soon as it is


available

charset Sets or returns the value of the charset attribute of a script

584
www.Sohrabpoor.com

crossOrigin Sets or returns the the CORS settings of a script

defer Sets or returns whether a script should be executed when the page has finished
parsing

src Sets or returns the value of the src attribute of a script

text Sets or returns the contents of all the text nodes that are children of a script

type Sets or returns the value of the type attribute of a script

Standard Properties and Events


The Script object also supports the standard properties and events.

HTML DOM Section Object


Section Object
The Section Object is new in HTML5.

The Section object represents an HTML <section> element.

Note: The <section> element is not supported in Internet Explorer 8 and


earlier versions.

Access a Section Object


You can access a <section> element by using getElementById():

Example
var x = document.getElementById("mySection");

Try it Yourself »

585
www.Sohrabpoor.com

Create a Section Object


You can create a <section> element by using the document.createElement()
method:

Example
var x = document.createElement("SECTION");

Try it Yourself »

Standard Properties and Events


The Section object supports the standard properties and events.

HTML DOM Select Object


Select Object
The Select object represents an HTML <select> element.

Access a Select Object


You can access a <select> element by using getElementById():

Example
var x = document.getElementById("mySelect");

Try it Yourself »

Tip: You can also access a Select object by searching through


the elements collection of a form.

Create a Select Object


You can create a <select> element by using the document.createElement()
method:

Example
var x = document.createElement("SELECT");

Try it Yourself »

586
www.Sohrabpoor.com

Select Object Collections


Collection Description

options Returns a collection of all the options in a drop-down list

Select Object Properties


Property Description

disabled Sets or returns whether the drop-down list is disabled, or not

form Returns a reference to the form that contains the drop-down list

length Returns the number of <option> elements in a drop-down list

multiple Sets or returns whether more than one option can be selected from the drop-
down list

name Sets or returns the value of the name attribute of a drop-down list

selectedIndex Sets or returns the index of the selected option in a drop-down list

size Sets or returns the value of the size of a drop-down list

type Returns which type of form element a drop-down list is

587
www.Sohrabpoor.com

value Sets or returns the value of the selected option in a drop-down list

Select Object Methods


Method Description

add() Adds an option to a drop-down list

remove() Removes an option from a drop-down list

Standard Properties and Events


The Select object also supports the standard properties and events.

HTML DOM Small Object


Small Object
The Small object represents an HTML <small> element.

Access a Small Object


You can access a <small> element by using getElementById():

Example
var x = document.getElementById("mySmall");

Try it Yourself »

Create a Small Object


You can create a <small> element by using the document.createElement()
method:

588
www.Sohrabpoor.com

Example
var x = document.createElement("SMALL");

Try it Yourself »

Standard Properties and Events


The Small object supports the standard properties and events.

HTML DOM Source Object


Source Object
The Source Object is new in HTML5.

The Source object represents an HTML <source> element.

Access a Source Object


You can access a <source> element by using getElementById():

Example
var x = document.getElementById("mySource");

Try it Yourself »

Create a Source Object


You can create a <source> element by using the document.createElement()
method:

Example
var x = document.createElement("SOURCE");

Try it Yourself »

589
www.Sohrabpoor.com

Source Object Properties


Property Description

media Sets or returns the value of the media attribute in a <source> element

src Sets or returns the value of the src attribute in a <source> element

type Sets or returns the value of the type attribute in a <source> element

Standard Properties and Events


The Source object also supports the standard properties and events.

HTML DOM Span Object


Span Object
The Span object represents an HTML <span> element.

Access a Span Object


You can access a <span> element by using getElementById():

Example
var x = document.getElementById("mySpan");

Try it Yourself »

Create a Span Object


You can create a <span> element by using the document.createElement()
method:

590
www.Sohrabpoor.com

Example
var x = document.createElement("SPAN");

Try it Yourself »

Standard Properties and Events


The Span object supports the standard properties and events.

HTML DOM Strong Object


Strong Object
The Strong object represents an HTML <strong> element.

Access a Strong Object


You can access a <strong> element by using getElementById():

Example
var x = document.getElementById("myStrong");

Try it Yourself »

Create a Strong Object


You can create a <strong> element by using the document.createElement()
method:

Example
var x = document.createElement("STRONG");

Try it Yourself »

Standard Properties and Events


The Strong object supports the standard properties and events.

591
www.Sohrabpoor.com

HTML DOM Style Object


Style object
The Style object represents an individual style statement.

Access a Style Object


The Style object can be accessed from the head section of the document, or
from specific HTML element(s).

Accessing style object(s) from the head section of the document:

Example
var x = document.getElementsByTagName("STYLE");

Try it Yourself »

Accessing a specified element's style object:

Example
var x = document.getElementById("myH1").style;

Try it Yourself »

Create a Style Object


You can create a <style> element by using the document.createElement()
method:

Example
var x = document.createElement("STYLE");

Try it Yourself »

You can also set the style properties of an existing element:

Example
document.getElementById("myH1").style.color = "red";

Try it Yourself »

592
www.Sohrabpoor.com

Style Object Properties


The "CSS" column indicates in which CSS version the property is defined
(CSS1, CSS2, or CSS3).

Property Description CSS

alignContent Sets or returns the alignment between the lines inside a flexible 3
container when the items do not use all available space

alignItems Sets or returns the alignment for items inside a flexible container 3

alignSelf Sets or returns the alignment for selected items inside a flexible 3
container

animation A shorthand property for all the animation properties below, except the 3
animationPlayState property

animationDela Sets or returns when the animation will start 3


y

animationDire Sets or returns whether or not the animation should play in reverse on 3
ction alternate cycles

animationDura Sets or returns how many seconds or milliseconds an animation takes to 3


tion complete one cycle

animationFillM Sets or returns what values are applied by the animation outside the time 3
ode it is executing

593
www.Sohrabpoor.com

animationItera Sets or returns the number of times an animation should be played 3


tionCount

animationNam Sets or returns a name for the @keyframes animation 3


e

animationTimi Sets or returns the speed curve of the animation 3


ngFunction

animationPlay Sets or returns whether the animation is running or paused 3


State

background Sets or returns all the background properties in one declaration 1

backgroundAtt Sets or returns whether a background-image is fixed or scrolls with the 1


achment page

backgroundCol Sets or returns the background-color of an element 1


or

backgroundIm Sets or returns the background-image for an element 1


age

backgroundPo Sets or returns the starting position of a background-image 1


sition

backgroundRe Sets or returns how to repeat (tile) a background-image 1


peat

594
www.Sohrabpoor.com

backgroundCli Sets or returns the painting area of the background 3


p

backgroundOri Sets or returns the positioning area of the background images 3


gin

backgroundSiz Sets or returns the size of the background image 3


e

backfaceVisibili Sets or returns whether or not an element should be visible when not 3
ty facing the screen

border Sets or returns borderWidth, borderStyle, and borderColor in one 1


declaration

borderBottom Sets or returns all the borderBottom* properties in one declaration 1

borderBottom Sets or returns the color of the bottom border 1


Color

borderBottom Sets or returns the shape of the border of the bottom-left corner 3
LeftRadius

borderBottom Sets or returns the shape of the border of the bottom-right corner 3
RightRadius

borderBottom Sets or returns the style of the bottom border 1


Style

595
www.Sohrabpoor.com

borderBottom Sets or returns the width of the bottom border 1


Width

borderCollapse Sets or returns whether the table border should be collapsed into a single 2
border, or not

borderColor Sets or returns the color of an element's border (can have up to four 1
values)

borderImage A shorthand property for setting or returning all the borderImage* 3


properties

borderImageO Sets or returns the amount by which the border image area extends 3
utset beyond the border box

borderImageR Sets or returns whether the image-border should be repeated, rounded 3


epeat or stretched

borderImageSli Sets or returns the inward offsets of the image-border 3


ce

borderImageS Sets or returns the image to be used as a border 3


ource

borderImageW Sets or returns the widths of the image-border 3


idth

borderLeft Sets or returns all the borderLeft* properties in one declaration 1

596
www.Sohrabpoor.com

borderLeftColo Sets or returns the color of the left border 1


r

borderLeftStyl Sets or returns the style of the left border 1


e

borderLeftWid Sets or returns the width of the left border 1


th

borderRadius A shorthand property for setting or returning all the four border*Radius 3
properties

borderRight Sets or returns all the borderRight* properties in one declaration 1

borderRightCol Sets or returns the color of the right border 1


or

borderRightSty Sets or returns the style of the right border 1


le

borderRightWi Sets or returns the width of the right border 1


dth

borderSpacing Sets or returns the space between cells in a table 2

borderStyle Sets or returns the style of an element's border (can have up to four 1
values)

borderTop Sets or returns all the borderTop* properties in one declaration 1

597
www.Sohrabpoor.com

borderTopColo Sets or returns the color of the top border 1


r

borderTopLeft Sets or returns the shape of the border of the top-left corner 3
Radius

borderTopRigh Sets or returns the shape of the border of the top-right corner 3
tRadius

borderTopStyl Sets or returns the style of the top border 1


e

borderTopWid Sets or returns the width of the top border 1


th

borderWidth Sets or returns the width of an element's border (can have up to four 1
values)

bottom Sets or returns the bottom position of a positioned element 2

boxDecoration Sets or returns the behaviour of the background and border of an 3


Break element at page-break, or, for in-line elements, at line-break.

boxShadow Attaches one or more drop-shadows to the box 3

boxSizing Allows you to define certain elements to fit an area in a certain way 3

captionSide Sets or returns the position of the table caption 2

598
www.Sohrabpoor.com

clear Sets or returns the position of the element relative to floating objects 1

clip Sets or returns which part of a positioned element is visible 2

color Sets or returns the color of the text 1

columnCount Sets or returns the number of columns an element should be divided into 3

columnFill Sets or returns how to fill columns 3

columnGap Sets or returns the gap between the columns 3

columnRule A shorthand property for setting or returning all the columnRule* 3


properties

columnRuleCol Sets or returns the color of the rule between columns 3


or

columnRuleSty Sets or returns the style of the rule between columns 3


le

columnRuleWi Sets or returns the width of the rule between columns 3


dth

columns A shorthand property for setting or returning columnWidth and 3


columnCount

columnSpan Sets or returns how many columns an element should span across 3

599
www.Sohrabpoor.com

columnWidth Sets or returns the width of the columns 3

content Used with the :before and :after pseudo-elements, to insert generated 2
content

counterIncrem Increments one or more counters 2


ent

counterReset Creates or resets one or more counters 2

cursor Sets or returns the type of cursor to display for the mouse pointer 2

direction Sets or returns the text direction 2

display Sets or returns an element's display type 1

emptyCells Sets or returns whether to show the border and background of empty 2
cells, or not

filter Sets or returns image filters (visual effects, like blur and saturation) 3

flex Sets or returns the length of the item, relative to the rest 3

flexBasis Sets or returns the initial length of a flexible item 3

flexDirection Sets or returns the direction of the flexible items 3

600
www.Sohrabpoor.com

flexFlow A shorthand property for the flexDirection and the flexWrap properties 3

flexGrow Sets or returns how much the item will grow relative to the rest 3

flexShrink Sets or returns how the item will shrink relative to the rest 3

flexWrap Sets or returns whether the flexible items should wrap or not 3

cssFloat Sets or returns the horizontal alignment of an element 1

font Sets or returns fontStyle, fontVariant, fontWeight, fontSize, lineHeight, 1


and fontFamily in one declaration

fontFamily Sets or returns the font family for text 1

fontSize Sets or returns the font size of the text 1

fontStyle Sets or returns whether the style of the font is normal, italic or oblique 1

fontVariant Sets or returns whether the font should be displayed in small capital 1
letters

fontWeight Sets or returns the boldness of the font 1

fontSizeAdjust Preserves the readability of text when font fallback occurs 3

fontStretch Selects a normal, condensed, or expanded face from a font family 3

601
www.Sohrabpoor.com

hangingPunctu Specifies whether a punctuation character may be placed outside the line 3
ation box

height Sets or returns the height of an element 1

hyphens Sets how to split words to improve the layout of paragraphs 3

icon Provides the author the ability to style an element with an iconic 3
equivalent

imageOrientati Specifies a rotation in the right or clockwise direction that a user agent 3
on applies to an image

justifyContent Sets or returns the alignment between the items inside a flexible 3
container when the items do not use all available space.

left Sets or returns the left position of a positioned element 2

letterSpacing Sets or returns the space between characters in a text 1

lineHeight Sets or returns the distance between lines in a text 1

listStyle Sets or returns listStyleImage, listStylePosition, and listStyleType in one 1


declaration

listStyleImage Sets or returns an image as the list-item marker 1

listStylePositio Sets or returns the position of the list-item marker 1


n

602
www.Sohrabpoor.com

listStyleType Sets or returns the list-item marker type 1

margin Sets or returns the margins of an element (can have up to four values) 1

marginBottom Sets or returns the bottom margin of an element 1

marginLeft Sets or returns the left margin of an element 1

marginRight Sets or returns the right margin of an element 1

marginTop Sets or returns the top margin of an element 1

maxHeight Sets or returns the maximum height of an element 2

maxWidth Sets or returns the maximum width of an element 2

minHeight Sets or returns the minimum height of an element 2

minWidth Sets or returns the minimum width of an element 2

navDown Sets or returns where to navigate when using the arrow-down navigation 3
key

navIndex Sets or returns the tabbing order for an element 3

navLeft Sets or returns where to navigate when using the arrow-left navigation 3
key

603
www.Sohrabpoor.com

navRight Sets or returns where to navigate when using the arrow-right navigation 3
key

navUp Sets or returns where to navigate when using the arrow-up navigation 3
key

opacity Sets or returns the opacity level for an element 3

order Sets or returns the order of the flexible item, relative to the rest 3

orphans Sets or returns the minimum number of lines for an element that must be 2
left at the bottom of a page when a page break occurs inside an element

outline Sets or returns all the outline properties in one declaration 2

outlineColor Sets or returns the color of the outline around a element 2

outlineOffset Offsets an outline, and draws it beyond the border edge 3

outlineStyle Sets or returns the style of the outline around an element 2

outlineWidth Sets or returns the width of the outline around an element 2

overflow Sets or returns what to do with content that renders outside the element 2
box

overflowX Specifies what to do with the left/right edges of the content, if it 3


overflows the element's content area

604
www.Sohrabpoor.com

overflowY Specifies what to do with the top/bottom edges of the content, if it 3


overflows the element's content area

padding Sets or returns the padding of an element (can have up to four values) 1

paddingBotto Sets or returns the bottom padding of an element 1


m

paddingLeft Sets or returns the left padding of an element 1

paddingRight Sets or returns the right padding of an element 1

paddingTop Sets or returns the top padding of an element 1

pageBreakAfte Sets or returns the page-break behavior after an element 2


r

pageBreakBefo Sets or returns the page-break behavior before an element 2


re

pageBreakInsid Sets or returns the page-break behavior inside an element 2


e

perspective Sets or returns the perspective on how 3D elements are viewed 3

perspectiveOri Sets or returns the bottom position of 3D elements 3


gin

605
www.Sohrabpoor.com

position Sets or returns the type of positioning method used for an element 2
(static, relative, absolute or fixed)

quotes Sets or returns the type of quotation marks for embedded quotations 2

resize Sets or returns whether or not an element is resizable by the user 3

right Sets or returns the right position of a positioned element 2

tableLayout Sets or returns the way to lay out table cells, rows, and columns 2

tabSize Sets or returns the length of the tab-character 3

textAlign Sets or returns the horizontal alignment of text 1

textAlignLast Sets or returns how the last line of a block or a line right before a forced 3
line break is aligned when text-align is "justify"

textDecoration Sets or returns the decoration of a text 1

textDecoration Sets or returns the color of the text-decoration 3


Color

textDecoration Sets or returns the type of line in a text-decoration 3


Line

textDecoration Sets or returns the style of the line in a text decoration 3


Style

606
www.Sohrabpoor.com

textIndent Sets or returns the indentation of the first line of text 1

textJustify Sets or returns the justification method used when text-align is "justify" 3

textOverflow Sets or returns what should happen when text overflows the containing 3
element

textShadow Sets or returns the shadow effect of a text 3

textTransform Sets or returns the capitalization of a text 1

top Sets or returns the top position of a positioned element 2

transform Applies a 2D or 3D transformation to an element 3

transformOrigi Sets or returns the position of transformed elements 3


n

transformStyle Sets or returns how nested elements are rendered in 3D space 3

transition A shorthand property for setting or returning the four transition 3


properties

transitionProp Sets or returns the CSS property that the transition effect is for 3
erty

transitionDurat Sets or returns how many seconds or milliseconds a transition effect 3


ion takes to complete

607
www.Sohrabpoor.com

transitionTimin Sets or returns the speed curve of the transition effect 3


gFunction

transitionDelay Sets or returns when the transition effect will start 3

unicodeBidi Sets or returns whether the text should be overridden to support 2


multiple languages in the same document

verticalAlign Sets or returns the vertical alignment of the content in an element 1

visibility Sets or returns whether an element should be visible 2

whiteSpace Sets or returns how to handle tabs, line breaks and whitespace in a text 1

width Sets or returns the width of an element 1

wordBreak Sets or returns line breaking rules for non-CJK scripts 3

wordSpacing Sets or returns the spacing between words in a text 1

wordWrap Allows long, unbreakable words to be broken and wrap to the next line 3

widows Sets or returns the minimum number of lines for an element that must be 2
visible at the top of a page

zIndex Sets or returns the stack order of a positioned element 2

608
www.Sohrabpoor.com

HTML DOM Subscript Object


Subscript Object
The Subscript object represents an HTML <sub> element.

Access a Subscript Object


You can access a <sub> element by using getElementById():

Example
var x = document.getElementById("mySub");

Try it Yourself »

Create a Subscript Object


You can create a <sub> element by using the document.createElement()
method:

Example
var x = document.createElement("SUB");

Try it Yourself »

Standard Properties and Events


The Subscript object supports the standard properties and events.

HTML DOM Summary Object


Summary Object
The Summary Object is new in HTML5.

The Summary object represents an HTML <summary> element.

Note: The <summary> element is currently only supported in Chrome,


Safari 6+ and Opera 15+.

609
www.Sohrabpoor.com

Access a Summary Object


You can access a <summary> element by using getElementById():

Example
var x = document.getElementById("mySummary");

Try it Yourself »

Create a Summary Object


You can create a <summary> element by using the
document.createElement() method:

Example
var x = document.createElement("SUMMARY");

Try it Yourself »

Standard Properties and Events


The Summary object also supports the standard properties and events.

HTML DOM Superscript Object


Superscript Object
The Superscript object represents an HTML <sup> element.

Access a Superscript Object


You can access a <sup> element by using getElementById():

Example
var x = document.getElementById("mySup");

Try it Yourself »

610
www.Sohrabpoor.com

Create a Superscript Object


You can create a <sup> element by using the document.createElement()
method:

Example
var x = document.createElement("SUP");

Try it Yourself »

Standard Properties and Events


The Superscript object supports the standard properties and events.

HTML DOM Table Object


Table Object
The Table object represents an HTML <table> element.

Access a Table Object


You can access a <table> element by using getElementById():

Example
var x = document.getElementById("myTable");

Try it Yourself »

Create a Table Object


You can create a <table> element by using the document.createElement()
method:

Example
var x = document.createElement("TABLE");

Try it Yourself »

611
www.Sohrabpoor.com

Table Object Collections


Collection Description

rows Returns a collection of all <tr> elements in a table

tBodies Returns a collection of all <tbody> elements in a table

Table Object Properties


Property Description

align Not supported in HTML5. Use style.cssFloat instead.


Sets or returns the alignment of a table according to surrounding text

background Not supported in HTML5. Use style.background instead.


Sets or returns the background image of a table

bgColor Not supported in HTML5. Use style.backgroundColor instead.


Sets or returns the background color of a table

border Deprecated. Use style.border instead.


Sets or returns the width of the table border.

caption Returns the <caption> element of a table

cellPadding Not supported in HTML5. Use style.padding instead.


Sets or returns the amount of space between the cell border and cell content

612
www.Sohrabpoor.com

cellSpacing Not supported in HTML5. Use style.borderSpacing instead.


Sets or returns the amount of space between the cells in a table

frame Not supported in HTML5.


Sets or returns which outer-borders (of a table) that should be displayed

height Not supported in HTML5. Use style.height instead.


Sets or returns the height of a table

rules Not supported in HTML5.


Sets or returns which inner-borders (between the cells) that should be
displayed in a table

summary Not supported in HTML5.


Sets or returns a description of the data in a table

tFoot Returns a reference to the <tfoot> element of a table

tHead Returns a reference to the <thead> element of a table

width Not supported in HTML5. Use style.width instead.


Sets or returns the width of the table

613
www.Sohrabpoor.com

Table Object Methods


Method Description

createCaption() Creates an empty <caption> element and adds it to the table

createTFoot() Creates an empty <tfoot> element and adds it to the table

createTHead() Creates an empty <thead> element and adds it to the table

deleteCaption() Removes the first <caption> element from the table

deleteRow() Removes a row (<tr>) from the table

deleteTFoot() Removes the <tfoot> element from the table

deleteTHead() Removes the <thead> element from the table

insertRow() Creates an empty <tr> element and adds it to the table

Standard Properties and Events


The Table object also supports the standard properties and events.

614
www.Sohrabpoor.com

HTML DOM TableData Object


TableData Object
The TableData object represents an HTML <td> element.

Access a TableData Object


You can access a <td> element by using getElementById():

Example
var x = document.getElementById("myTd");

Try it Yourself »

Tip: You can also access a <td> element by searching through


the cells collection of a table row.

Create a TableData Object


You can create a <td> element by using the document.createElement()
method:

Example
var x = document.createElement("TD");

Try it Yourself »

TableData Object Properties


Property Description

abbr Not supported in HTML5.


Sets or returns the value of the abbr attribute

615
www.Sohrabpoor.com

align Not supported in HTML5. Use style.textAlign instead.


Sets or returns the horizontal alignment of the content in a data cell

axis Not supported in HTML5.


Sets or returns a comma-separated list of related data cells

background Not supported in HTML5. Use style.background instead.


Sets or returns the background image of a data cell

bgColor Not supported in HTML5. Use style.backgroundColor instead.


Sets or returns the background color of a table

cellIndex Returns the position of a cell in the cells collection of a table row

ch Not supported in HTML5.


Sets or returns an alignment character for a data cell

chOff Not supported in HTML5.


Sets or returns the horizontal offset of the ch property

colSpan Sets or returns the value of the colspan attribute

headers Sets or returns the value of the headers attribute

height Not supported in HTML5. Use style.height instead.


Sets or returns the height of a data cell

noWrap Not supported in HTML5. Use style.whiteSpace instead.


Sets or returns whether the content in a cell can be wrapped

616
www.Sohrabpoor.com

rowSpan Sets or returns the value of the rowspan attribute

vAlign Not supported in HTML5. Use style.verticalAlign instead.


Sets or returns the vertical alignment of the content within a cell

width Not supported in HTML5. Use style.width instead.


Sets or returns the width of a data cell

Standard Properties and Events


The TableData object also supports the standard properties and events.

HTML DOM TableHeader Object


TableHeader Object
The TableHeader object represents an HTML <th> element.

Access a TableHeader Object


You can access a <th> element by using getElementById():

Example
var x = document.getElementById("myTh");

Try it Yourself »

Tip: You can also access a <th> element by searching through


the cells collection of a table row.

Create a TableHeader Object


You can create a <th> element by using the document.createElement()
method:

617
www.Sohrabpoor.com

Example
var x = document.createElement("TH");

Try it Yourself »

TableHeader Object Properties


Property Description

abbr Sets or returns the value of the abbr attribute

align Not supported in HTML5. Use style.textAlign instead.


Sets or returns the horizontal alignment of the content in a data cell

axis Not supported in HTML5.


Sets or returns a comma-separated list of related data cells

background Not supported in HTML5. Use style.background instead.


Sets or returns the background image of a data cell

bgColor Not supported in HTML5. Use style.backgroundColor instead.


Sets or returns the background color of a table

cellIndex Returns the position of a cell in the cells collection of a table row

ch Not supported in HTML5.


Sets or returns an alignment character for a data cell

chOff Not supported in HTML5.


Sets or returns the horizontal offset of the ch property

618
www.Sohrabpoor.com

colSpan Sets or returns the value of the colspan attribute

headers Sets or returns the value of the headers attribute

height Not supported in HTML5. Sets or returns the height of a data cell
Use style.height instead

noWrap Not supported in HTML5. Sets or returns whether the content in a cell can be
wrapped
Use style.whiteSpace instead

rowSpan Sets or returns the value of the rowspan attribute

vAlign Not supported in HTML5. Sets or returns the vertical alignment of the content
within a cell
Use style.verticalAlign instead

width Not supported in HTML5. Sets or returns the width of a data cell
Use style.width instead

Standard Properties and Events


The TableHeader object also supports the standard properties and events.

HTML DOM TableRow Object


TableRow Object
The TableRow object represents an HTML <tr> element.

619
www.Sohrabpoor.com

Access a TableRow Object


You can access a <tr> element by using getElementById():

Example
var x = document.getElementById("myTr");

Try it Yourself »

Tip: You can also access a <tr> element by searching through


the rows collection of a table.

Create a TableRow Object


You can create a <tr> element by using the document.createElement()
method:

Example
var x = document.createElement("TR");

Try it Yourself »

TableRow Object Collections


Collection Description

cells Returns a collection of all <td> or <th> elements in a table row

TableRow Object Properties


Property Description

align Not supported in HTML5. Use style.textAlign instead.


Sets or returns the horizontal alignment of the content within a table row

620
www.Sohrabpoor.com

bgColor Not supported in HTML5. Use style.backgroundColor instead.


Sets or returns the background color of a table row

ch Not supported in HTML5.


Sets or returns an alignment character for cells in a table row

chOff Not supported in HTML5.


Sets or returns the horizontal offset of the ch property

height Not supported in HTML5. Use style.height instead.


Sets or returns the height of a table row.

rowIndex Returns the position of a row in the rows collection of a table

sectionRowIndex Returns the position of a row in the rows collection of a tbody, thead, or tfoot

vAlign Not supported in HTML5. Use style.verticalAlign instead.


Sets or returns the vertical alignment of the content within a table row

TableRow Object Methods


Method Description

deleteCell() Deletes a cell from the current table row

insertCell() Inserts a cell into the current table row

621
www.Sohrabpoor.com

Standard Properties and Events


The TableRow object also supports the standard properties and events.

HTML DOM Textarea Object


Textarea Object
The Textarea object represents an HTML <textarea> element.

Access a Textarea Object


You can access a <textarea> element by using getElementById():

Example
var x = document.getElementById("myTextarea");

Try it Yourself »

Tip: You can also access a <textarea> element by searching through


the elements collection of a form.

Create a Textarea Object


You can create a <textarea> element by using the
document.createElement() method:

Example
var x = document.createElement("TEXTAREA");

Try it Yourself »

622
www.Sohrabpoor.com

Textarea Object Properties


= Property added in HTML5.

Property Description

autofocus Sets or returns whether a text area should automatically get focus when the page
loads

cols Sets or returns the value of the cols attribute of a text area

defaultValue Sets or returns the default value of a text area

disabled Sets or returns whether the text area is disabled, or not

form Returns a reference to the form that contains the text area

maxLength Sets or returns the value of the maxlength attribute of a text area

name Sets or returns the value of the name attribute of a text area

placeholder Sets or returns the value of the placeholder attribute of a text area

readOnly Sets or returns whether the contents of a text area is read-only

required Sets or returns whether the text area must be filled out before submitting a form

rows Sets or returns the value of the rows attribute of a text area

623
www.Sohrabpoor.com

type Returns the type of the form element the text area is

value Sets or returns the contents of a text area

wrap Sets or returns the value of the wrap attribute of a text area

Textarea Object Methods


Method Description

select() Selects the entire contents of a text area

Standard Properties and Events


The Textarea object also supports the standard properties and events.

HTML DOM Time Object


Time Object
The Time Object is new in HTML5.

The Time object represents an HTML <time> element.

Access a Time Object


You can access a <time> element by using getElementById():

Example
var x = document.getElementById("myTime");

Try it Yourself »

624
www.Sohrabpoor.com

Create a Time Object


You can create a <time> element by using the document.createElement()
method:

Example
var x = document.createElement("TIME");

Try it Yourself »

Time Object Properties


Property Description

dateTime Sets or returns the value of the datetime attribute in a <time> element

Standard Properties and Events


The Time object also supports the standard properties and events.

HTML DOM Title Object


Title Object
The Title object represents an HTML <title> element.

Access a Title Object


You can access a <title> element by using getElementsByTagName():

Example
var x = document.getElementsByTagName("TITLE")[0];

Try it Yourself »

625
www.Sohrabpoor.com

Create a Title Object


You can create a <title> element by using the document.createElement()
method:

Example
var x = document.createElement("TITLE");

Try it Yourself »

Title Object Properties


Property Description

text Sets or returns the text of the document's title

Standard Properties and Events


The Title object also supports the standard properties and events.

HTML DOM Track Object


Track Object
The Track Object is new in HTML5.

The Track object represents an HTML <track> element.

Access a Track Object


You can access a <track> element by using getElementById():

var x = document.getElementById("myTrack");

626
www.Sohrabpoor.com

Create a Track Object


You can create a <track> element by using the document.createElement()
method:

var x = document.createElement("TRACK");

Track Object Properties


Property Description

default Sets or returns the default state of the track

kind Sets or returns the value of the kind attribute of the track

label Sets or returns the value of the label attribute of the track

readyState Returns the current state of the track resource

src Sets or returns the value of the src attribute of the track

srclang Sets or returns the value of the srclang attribute of the track

track Returns a TextTrack object representing the track element's text track data

Standard Properties and Events


The Track object also supports the standard properties and events.

627
www.Sohrabpoor.com

HTML DOM Underline Object


Underline Object
The Underline object represents an HTML <u> element.

Access an Underline Object


You can access a <u> element by using getElementById():

Example
var x = document.getElementById("myU");

Try it Yourself »

Create an Underline Object


You can create a <u> element by using the document.createElement()
method:

Example
var x = document.createElement("U");

Try it Yourself »

Standard Properties and Events


The Underline object supports the standard properties and events.

HTML DOM Ul Object


Ul Object
The Ul object represents an HTML <ul> element.

Access a Ul Object
You can access a <ul> element by using getElementById():

628
www.Sohrabpoor.com

Example
var x = document.getElementById("myUL");

Try it Yourself »

Create a Ul Object
You can create a <ul> element by using the document.createElement()
method:

Example
var x = document.createElement("UL");

Try it Yourself »

Ul Object Properties
Property Description

compact Not supported in HTML5. Use style.lineHeight instead.


Sets or returns whether the unordered list should render smaller than normal, or
not

type Not supported in HTML5. Use style.listStyleType instead.


Sets or returns the value of the type attribute of an unordered list

Standard Properties and Events


The Ul object supports the standard properties and events.

629
www.Sohrabpoor.com

HTML DOM Variable Object


Variable Object
The Variable object represents an HTML <var> element.

Access a Variable Object


You can access a <var> element by using getElementById():

Example
var x = document.getElementById("myVar");

Try it Yourself »

Create a Variable Object


You can create a <var> element by using the document.createElement()
method:

Example
var x = document.createElement("VAR");

Try it Yourself »

Standard Properties and Events


The Variable object supports the standard properties and events.

HTML DOM Video Object


Video Object
The Video Object is new in HTML5.

The Video object represents an HTML <video> element.

Note: The <video> element is not supported in Internet Explorer 8 and earlier versions.

630
www.Sohrabpoor.com

Access a Video Object


You can access a <video> element by using getElementById():

Example
var x = document.getElementById("myVideo");

Try it Yourself »

Create a Video Object


You can create a <video> element by using the document.createElement() method:

Example
var x = document.createElement("VIDEO");

Try it Yourself »

Video Object Properties


Property Description

audioTracks Returns an AudioTrackList object representing available audio tracks

autoplay Sets or returns whether a video should start playing as soon as it is ready

buffered Returns a TimeRanges object representing the buffered parts of a video

controller Returns the MediaController object representing the current media


controller of a video

631
www.Sohrabpoor.com

controls Sets or returns whether a video should have controls displayed (play/pause
etc)

crossOrigin Sets or returns the CORS settings of a video

currentSrc Returns the URL of the current video

currentTime Sets or returns the current playback position in a video (in seconds)

defaultMuted Sets or returns whether the video should be muted by default

defaultPlaybackRate Sets or returns whether the default playback speed of the video

duration Returns the length of a video (in seconds)

ended Returns whether the playback of the video has ended

error Returns a MediaError object representing the error state of the video

height Sets or returns the value of the height attribute of a video

loop Sets or returns whether the video should start playing over again, every
time it is finished

mediaGroup Sets or returns the name of the media group the video(s) is a part of

muted Sets or returns whether the sound of a video should be turned off

632
www.Sohrabpoor.com

networkState Returns the current network state of a video

paused Sets or returns whether a video is paused

playbackRate Sets or returns the speed of the video playback

played Returns a TimeRanges object representing the played parts of the video

poster Sets or returns the value of the poster attribute of a video

preload Sets or returns the value of the preload attribute of a video

readyState Returns the current ready state of a video

seekable Returns a TimeRanges object representing the seekable parts of a video

seeking Returns whether the user is currently seeking in the video

src Sets or returns the value of the src attribute of a video

startDate Returns a Date object representing the current time offset

textTracks Returns a TextTrackList object representing the available text tracks

videoTracks Returns a VideoTrackList object representing the available video tracks

633
www.Sohrabpoor.com

volume Sets or returns the audio volume of a video

width Sets or returns the value of the width attribute of a video

Video Object Methods


Method Description

addTextTrack() Adds a new text track to the video

canPlayType() Checks whether the browser can play the specified video type

load() Re-loads the video element

play() Starts playing the video

pause() Pauses the currently playing video

Standard Properties and Events


The Video object also supports the standard properties and events.

634

You might also like