BUY THIS BOOK
Add to Cart

Print Book $9.95


Add to Cart

Print+PDF $12.93

Add to Cart

PDF $7.99

Safari Books Online

What is this?

Add to UK Cart

Print Book £6.95

What is this?

Looking to Reprint or License this content?


JavaScript Pocket Reference
JavaScript Pocket Reference, Second Edition

By David Flanagan
Book Price: $9.95 USD
£6.95 GBP
PDF Price: $7.99

Cover | Table of Contents


Table of Contents

Chapter 1: The JavaScript Language
JavaScript is a lightweight, object-based scripting language that can be embedded in HTML pages. This book starts with coverage of the core JavaScript language, followed by material on client-side JavaScript, as used in web browsers. The final portion of this book is a quick-reference for the core and client-side JavaScript APIs.
JavaScript syntax is modeled on Java syntax, Java syntax, in turn, is modeled on C and C++ syntax. Therefore, C, C++, and Java programmers should find that JavaScript syntax is comfortably familiar.
JavaScript is a case-sensitive language. All keywords are in lowercase. All variables, function names, and other identifiers must be typed with a consistent capitalization.
JavaScript ignores whitespace between tokens. You may use spaces, tabs, and newlines to format and indent your code in a readable fashion.
JavaScript statements are terminated by semicolons. When a statement is followed by a newline, however, the terminating semicolon may be omitted. Note that this places a restriction on where you may legally break lines in your JavaScript programs: you may not break a statement across two lines if the first line can be a complete legal statement on its own.
JavaScript supports both C and C++ comments. Any amount of text, on one or more lines, between /* and */ is a comment, and is ignored by JavaScript. Also, any text between // and the end of the current line is a comment, and is ignored. Examples:
// This is a single-line, C++-style comment.
/*
 * This is a multi-line, C-style comment.
 * Here is the second line.
 */
/* Another comment. */ // This too.
Variable, function, and label names are JavaScript identifiers. Identifiers are composed of any number of letters and digits, and _ and $ characters. The first character of an identifier must not be a digit, however. The following are legal identifiers:
i
my_variable_name
v13
$str
The following keywords are part of the JavaScript language, and have special meaning to the JavaScript interpreter. Therefore, they may not be used as identifiers:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Syntax
JavaScript syntax is modeled on Java syntax, Java syntax, in turn, is modeled on C and C++ syntax. Therefore, C, C++, and Java programmers should find that JavaScript syntax is comfortably familiar.
JavaScript is a case-sensitive language. All keywords are in lowercase. All variables, function names, and other identifiers must be typed with a consistent capitalization.
JavaScript ignores whitespace between tokens. You may use spaces, tabs, and newlines to format and indent your code in a readable fashion.
JavaScript statements are terminated by semicolons. When a statement is followed by a newline, however, the terminating semicolon may be omitted. Note that this places a restriction on where you may legally break lines in your JavaScript programs: you may not break a statement across two lines if the first line can be a complete legal statement on its own.
JavaScript supports both C and C++ comments. Any amount of text, on one or more lines, between /* and */ is a comment, and is ignored by JavaScript. Also, any text between // and the end of the current line is a comment, and is ignored. Examples:
// This is a single-line, C++-style comment.
/*
 * This is a multi-line, C-style comment.
 * Here is the second line.
 */
/* Another comment. */ // This too.
Variable, function, and label names are JavaScript identifiers. Identifiers are composed of any number of letters and digits, and _ and $ characters. The first character of an identifier must not be a digit, however. The following are legal identifiers:
i
my_variable_name
v13
$str
The following keywords are part of the JavaScript language, and have special meaning to the JavaScript interpreter. Therefore, they may not be used as identifiers:
break     do        if         switch  typeof        
case      else      in         this    var   
catch     false     instanceof throw   void  
continue  finally   new        true    while 
default   for       null       try     with
delete    function  return
JavaScript also reserves the following words for possible future extensions. You may not use any of these words as identifiers either:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Variables
Variables are declared and initialized with the var statement:
var i = 1+2+3;
var x = 3, message = 'hello world';
Variable declarations in top-level JavaScript code may be omitted, but they are required to declare local variables within the body of a function.
JavaScript variables are untyped: they can contain values of any data type.
Global variables in JavaScript are implemented as properties of a special Global object. Local variables within functions are implemented as properties of the Argument object for that function. Global variables are visible throughout a JavaScript program. Variables declared within a function are only visible within that function. Unlike C, C++, and Java, JavaScript does not have block-level scope: variables declared within the curly braces of a compound statement are not restricted to that block and are visible outside of it.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Data Types
JavaScript supports three primitive data types: numbers, booleans, and strings; and two compound data types: objects and arrays. In addition, it defines specialized types of objects that represent functions, regular expressions, and dates.
Numbers in JavaScript are represented in 64-bit floating-point format. JavaScript makes no distinction between integers and floating-point numbers. Numeric literals appear in JavaScript programs using the usual syntax: a sequence of digits, with an optional decimal point and an optional exponent. For example:
1
3.14
0001
6.02e23
Integers may also appear in hexadecimal notation. A hexadecimal literal begins with 0x:
0xFF // The number 255 in hexadecimal
When a numeric operation overflows, it returns a special value that represents positive or negative infinity. When an operation underflows, it returns zero. When an operation such as taking the square root of a negative number yields an error or meaningless result, it returns the special value NaN, which represents a value that is not-a-number. Use the global function isNaN( ) to test for this value.
The Number object defines useful numeric constants. The Math object defines various mathematical functions such as Math.sin( ), Math.pow( ), and Math.random( ).
The boolean type has two possible values, represented by the JavaScript keywords true and false. These values represent truth or falsehood, on or off, yes or no, or anything else that can be represented with one bit of information.
A JavaScript string is a sequence of arbitrary letters, digits, and other characters from the 16-bit Unicode character set.
String literals appear in JavaScript programs between single or double quotes. One style of quotes may be nested within the other:
'testing'
"3.14"
'name="myform"'
"Wouldn't you prefer O'Reilly's book?"
When the backslash character (\) appears within a string literal, it changes, or escapes, the meaning of the character that follows it. The following table lists these special escape sequences:
Escape
Represents
\b
Backspace
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Expressions and Operators
JavaScript expressions are formed by combining values (which may be literals, variables, object properties, array elements, or function invocations) using JavaScript operators. Parentheses can be used in an expression to group subexpressions and alter the default order of evaluation of the expression. Some examples:
1+2
total/n
sum(o.x, a[3])++
JavaScript defines a complete set of operators, most of which should be familiar to C, C++, and Java programmers. They are listed in the table below, and a brief explanation of the non-standard operators follows. The P column specifies operator precedence and the A column specifies operator associativity: L means left-to-right associativity, and R means right-to-left associativity.
P
A
Operator
Operation performed
15
L
.
Access an object property
L
[ ]
Access an array element
L
( )
Invoke a function
R
new
Create new object
14
R
++
Pre-or-post increment (unary)
R
--
Pre-or-post decrement (unary)
R
-
Unary minus (negation)
R
+
Unary plus (no-op)
R
~
Bitwise complement (unary)
R
!
Logical complement (unary)
R
delete
Undefine a property (unary) (JS 1.2)
R
typeof
Return data type (unary) (JS 1.1)
R
void
Return undefined value (unary) (JS 1.1)
13
L
*, /, %
Multiplication, division, remainder
12
L
+, -
Add, subtract
L
+
Concatenate strings
11
L
<<
Integer shift left
L
>>
Shift right, sign-extension
L
>>>
Shift right, zero extension
10
L
<, <=
Less than, less than or equal
L
>, >=
Greater than, greater than or equal
L
instanceof
Check object type (JS 1.5)
L
in
Check whether property exists (JS 1.5)
9
L
==
Test for equality
L
!=
Test for inequality
L
===
Test for identity (JS 1.3)
L
!==
Test for non-identity (JS 1.3)
8
L
&
Integer bitwise AND
7
L
^
Integer bitwise XOR
6
L
|
Integer bitwise OR
5
L
&&
Logical AND
4
L
||
Logical OR
3
R
?:
Conditional operator (3 operands)
2
R
=
Assignment
R
*=, +=, -=, etc.
Assignment with operation
1
L
,
Multiple evaluation
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Statements
A JavaScript program is a sequence of JavaScript statements. Most JavaScript statements have the same syntax as the corresponding C, C++, and Java statements.
Every JavaScript expression can stand alone as a statement. Assignments, method calls, increments, and decrements are expression statements. For example:
s = "hello world";
x = Math.sqrt(4);
x++;
When a sequence of JavaScript statements is enclosed within curly braces, it counts as a single compound statement. For example, the body of a while loop consists of a single statement. If you want the loop to execute more than one statement, use a compound statement. This is a common technique with if, for, and other statements described later.
The empty statement is simply a semicolon by itself. It does nothing, and is occasionally useful for coding empty loop bodies.
As of JavaScript 1.2, any statement can be labeled with a name. Labeled loops can then be used with the labeled versions of the break and continue statements:
label : statement
The following paragraphs document all JavaScript statements, in alphabetical order.
break
The break statement terminates execution of the innermost enclosing loop, or, in JavaScript 1.2 and later, the named loop:
break ;
break label ;
case
case is not a true statement. Instead it is a keyword used to label statements within a JavaScript 1.2 or later switch statement:
case constant-expression :
    statements
    [ break ; ]
Because of the nature of the switch statement, a group of statements labeled by case should usually end with a break statement.
continue
The continue statement restarts the innermost enclosing loop, or, in JavaScript 1.2 and later, restarts the named loop:
continue ;
continue label ;
default
Like case, default is not a true statement, but instead a label that may appear within a JavaScript 1.2 or later switch statement:
default:
    statements
    [ break ; ]
do/while
The do/while loop repeatedly executes a statement while an expression is true. It is like the while loop, except that the loop condition appears (and is tested) at the bottom of the loop. This means that the body of the loop is executed at least once:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Object-Oriented JavaScript
JavaScript objects are associative arrays that associate values with named properties. JavaScript provides a simple inheritance mechanism, and it is possible to define new classes of objects for use in your own programs. To define a new class, start by writing a constructor function. A constructor is like any other function, except it is invoked with the new operator and it uses the this keyword to refer to and initialize the newly created object. For example, here is a constructor to create objects of a new class named Point.
function Point(x,y) { // Constructor for Point
  this.x = x;  // Initialize X coordinate
  this.y = y;  // Initialize Y coordinate
}
Every JavaScript function used as a constructor has a property named prototype. This property refers to a special prototype object for the class of objects created by the constructor. Any properties you define on this prototype object are inherited by all objects created with the constructor function. The prototype object is commonly used to make methods available to all instances of a class. Defining a method named toString allows instances of your class to be converted to strings. For example:
// Define function literals and assign them 
// to properties of the prototype object.
Point.prototype.distanceTo = function(that) {
  var dx = this.x - that.x;
  var dy = this.y - that.y;
  return Math.sqrt(dx*dx + dy*dy);
}
Point.prototype.toString = function () {
  return '(' + this.x + ',' + this.y + ')';
}
If you want to define static (or class) methods or properties, you can assign them directly to the constructor function, rather than to the prototype object. For example:
// Define a commonly used Point constant
Point.ORIGIN = new Point(0,0);
The preceding code fragments define a simple Point class that we can use with code like this:
// Call constructor to create a new Point object
var p = new Point(3,4);
// Invoke a method of the object, using a static
// property as the argument.  
var d = p.distanceTo(Point.ORIGIN);
// Adding the object to a string implicitly
// invokes toString().
var msg = "Distance to " + p + " is " + d;
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Regular Expressions
JavaScript supports regular expressions for pattern matching with the same syntax as the Perl programming language. JavaScript 1.2 supports Perl 4 regular expressions, and JavaScript 1.5 adds supports for some of the additional features of Perl 5 regular expressions. A regular expression is specified literally in a JavaScript program as a sequence of characters within slash (/) characters, optionally followed by one or more of the modifier characters g (global search), i (case-insensitive search), and m (multi-line mode; a JavaScript 1.5 feature). In addition to this literal syntax, RegExp objects can be created with the RegExp( ) constructor, which accepts the pattern and modifier characters as string arguments, without the slash characters.
A full explanation of regular expression syntax is beyond the scope of this book, but the tables in the following subsections offer brief syntax summaries.
Letters, numbers, and most other characters are literals in a regular expression: they simply match themselves. As we'll see in the sections that follow, however, there are a number of punctuation characters and escape sequences (beginning with \) that have special meanings. The simplest of these escape sequences provide alternative ways of representing literal characters:
Character
Meaning
\n, \r, \t
Match literal newline, carriage return, tab
\\, \/, \*,\+, \?, etc.
Match a punctuation character literally, ignoring or escaping its special meaning
\xnn
The character with hexadecimal encoding nn.
\uxxxx
The Unicode character with hexadecimal encoding xxxx.
Regular expression syntax uses square brackets to represent character sets or classes in a pattern. In addition, escape sequences define certain commonly-used character classes, as shown in the following table.
Character
Meaning
[...]
Match any one character between brackets
[^...]
Match any one character not between brackets
.
Match any character other than newline
\w, \W
Match any word/non-word character
\s, \S
Match any whitespace/non-whitespace
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Versions of JavaScript
Netscape has defined a number of versions of JavaScript. Microsoft has released more-or-less compatible versions under the name "JScript," and the ECMA standards body has released three versions of a JavaScript standard named "ECMAScript". The following paragraphs describe these various versions, and explain how they relate to each other. Each entry in the reference section contains availability information that documents the version of JavaScript in which a feature was introduced.
JavaScript 1.0
The original version of the language. It was buggy and is now essentially obsolete. Implemented by Netscape 2.
JavaScript 1.1
Introduced a true Array object; most serious bugs resolved. Implemented by Netscape 3.
JavaScript 1.2
Introduced the switch statement, regular expressions, and a number of other features. Almost compliant with ECMA v1, but has some incompatibilities. Implemented by Netscape 4.
JavaScript 1.3
Fixed incompatibilities of JavaScript 1.2. Compliant with ECMA v1. Implemented by Netscape 4.5.
JavaScript 1.4
Only implemented in Netscape server products.
JavaScript 1.5
Introduced exception handling. Compliant with ECMA v3. Implemented by Mozilla and Netscape 6.
JScript 1.0
Roughly equivalent to JavaScript 1.0. Implemented by early releases of IE 3.
JScript 2.0
Roughly equivalent to JavaScript 1.1. Implemented by later releases of IE 3.
JScript 3.0
Roughly equivalent to JavaScript 1.3. Compliant with ECMA v1. Implemented by IE 4.
JScript 4.0
Not implemented by any web browser.
JScript 5.0
Supported exception handling; partial ECMA v3 compliance. Implemented by IE 5.
JScript 5.5
Roughly equivalent to JavaScript 1.5. Fully compliant with ECMA v3. Implemented by IE 5.5 and IE 6.
ECMA v1
The first standard version of the language. Standardized the basic features of JavaScript 1.1 and added a few new features. Did not standardize the switch statement or regular expression support. Conformant implementations are JavaScript 1.3 and JScript 3.0.
ECMA v2
A maintenance release of the standard that included clarifications but defined no new features.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 2: Client-side JavaScript
Client-side JavaScript is the name given to JavaScript code that is embedded within an HTML file and executed by a web browser. In addition to the core objects described in the previous section, client-side JavaScript code has access to a number of other objects that represent the web browser, the document displayed in the browser, and the contents of that document. Client-side JavaScript programs are usually event-based, which means that JavaScript event handlers are executed in response to user interactions with the browser and the document. The client-side JavaScript scripting framework is powerful enough to open substantial security holes in web browsers. For this reason, web browsers typically restrict the actions of client-side scripts. This section starts by explaining how JavaScript code is embedded in HTML files, then goes on to introduce the client-side JavaScript objects, JavaScript events and event handling, and JavaScript security restrictions.
JavaScript code may be embedded in HTML files in the form of scripts, event handlers and URLs, as detailed below.
Most JavaScript code appears in HTML files between a <script> tag and a </script> tag. For example:
<script>
document.write("The time is: " + new Date());
</script>
In JavaScript 1.1 and later you can use the src attribute of the <script> tag to specify the URL of an external script to be loaded and executed. Files of JavaScript code typically have a .js extension. Note that the </script> tag is still required when this attribute is used:
<script src="library.js"></script>
HTML allows scripts to be written in languages other than JavaScript, and some browsers, such as Internet Explorer, support languages such as VBScript. You can use the language attribute to specify what language a script is written in. This attribute defaults to "JavaScript" in all browsers, so you do not usually have to set it. You can also use attribute values such as "JavaScript1.3" and "JavaScript1.5" to specify the version of JavaScript your code uses. Browsers that do not support the specified version of the language simply ignore the script.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
JavaScript in HTML
JavaScript code may be embedded in HTML files in the form of scripts, event handlers and URLs, as detailed below.
Most JavaScript code appears in HTML files between a <script> tag and a </script> tag. For example:
<script>
document.write("The time is: " + new Date());
</script>
In JavaScript 1.1 and later you can use the src attribute of the <script> tag to specify the URL of an external script to be loaded and executed. Files of JavaScript code typically have a .js extension. Note that the </script> tag is still required when this attribute is used:
<script src="library.js"></script>
HTML allows scripts to be written in languages other than JavaScript, and some browsers, such as Internet Explorer, support languages such as VBScript. You can use the language attribute to specify what language a script is written in. This attribute defaults to "JavaScript" in all browsers, so you do not usually have to set it. You can also use attribute values such as "JavaScript1.3" and "JavaScript1.5" to specify the version of JavaScript your code uses. Browsers that do not support the specified version of the language simply ignore the script.
HTML 4 does not actually recognize the language attribute of the <script> tag. Instead, the official way to specify the language a script is written in is with the type attribute. For JavaScript, set this attribute to the MIME type "text/javascript":
<script src="functions.js"
        language="JavaScript1.5"
        type="text/javascript"></script>
JavaScript code may also appear as the value of an event handler attribute of an HTML tag. Event handler attribute names always begin with "on". The code specified by one of these attributes is executed when the named event occurs. For example, the following HTML creates a button, and the onclick attribute specifies an event handler that displays an alert (a dialog box) when the user clicks the button:
<input type="button" value="Press Me"
       onclick="alert('Hello World!');">
A list of other available event handler attributes is included later in this section.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The Window Object
The Window object represents a web browser window. In client-side JavaScript, the Window object is the global object that defines all top-level properties and methods. The properties and methods of the Window object are therefore global properties and global functions and you can refer to them by their property names without any object prefix. One of the properties of the Window object is named window and refers back to the Window object itself:
window           // The global Window object
window.document  // The document property of the window
document         // Or omit the object prefix
See the Window object in the reference section for a full list of its properties and methods. The following sections summarize the most important of these properties and methods and demonstrate key client-side programming techniques using the Window object. Note that the most important property of the Window object is document, which refers to the Document object that describes the document displayed by the browser window. The Document object is described in a section of its own following these window-related subsections.
Three methods allow you to display simple dialog boxes to the user. alert( ) lets you display a message to the user, confirm( ) lets you ask the user a yes-or-no question, and prompt( ) lets you ask the user to enter a single line of text. For example:
alert("Welcome to my home page!"); 
if (confirm("Do you want to play?")) {
    var n = prompt("Enter your name");
}
Most web browsers include a status line at the bottom of the window that is used to display the destination of links and other information. You can specify text to appear in the status line with the status property. The text you set on this property appears in the status area until you or the browser overwrites it with some new value. You can also set defaultStatus to specify text to appear by default when the browser is not displaying any other information in the status line. Here is an HTML hyperlink that uses JavaScript in an event handler to set the status text to something other than the URL of the link:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The Document Object
Every Window object has a document property that refers to a Document object. The Document object is arguably more important than the Window object itself: while the Window represents the browser window, the Document object represents the HTML document that is displayed in that window. The Document object has various properties that refer to other objects which allow access to and modification of document content. The way that document content is accessed and modified is called the document object model, or DOM, and there are several DOMs in existence:
Legacy DOM
The original legacy document object model evolved along with early versions of the JavaScript language. It is well supported by all browsers, but allows access only to certain key portions of documents, such as forms, form elements, and images.
W3C DOM
This document object model allows access and modification of all document content and is standardized by the World Wide Web Consortium (W3C). It is at least partially supported by Netscape 6 and later, Internet Explorer 5 and later, and other modern browsers. The W3C DOM is not closely compatible with the IE 4 DOM, but it does standardize many of the legacy features of the original DOM. This book covers the core features of the standard, and presents a simplified subset of the DOM relevant for JavaScript programmers working with HTML documents. You can find complete coverage in JavaScript: The Definitive Guide.
IE 4 DOM
Microsoft's Internet Explorer Version 4 extended the legacy DOM with powerful new features for accessing and modifying all content of a document. These features were never standardized, but some of them are supported in non-Microsoft browsers.
The following sections explain each of these DOMs in more detail and describe how you can use them to access and modify document content.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The Legacy DOM
The original client-side JavaScript DOM defines provides access to document content through properties of the Document object. Several read-only properties, such as title, URL, and lastModified provide information about the document as a whole. See the reference section for further details on these and all Document properties and methods. Other properties are arrays that refer to specific types of document content:
forms[ ]
An array of Form objects representing the forms in a document.
images[ ]
An array of Image objects representing the images that appear in a document.
applets[ ]
An array of objects that represent the Java applets embedded in a document. JavaScript can actually be used to script Java and control these applets, but doing so is beyond the scope of this pocket reference.
links[ ]
An array of Link objects representing the hyperlinks in the document.
anchors[ ]
An array of Anchor objects representing the anchors (named positions created with the name attribute of the HTML <a> tag) in the document.
These arrays contain objects in the order they appear in the document. So the first form in a document is document.forms[0], and the third image is document.images[2]. Another way to refer to document forms, images, and applets is to give them names with the HTML name attribute:
<form name="address">...</form>
When an form, image, or applet is given a name in this way, you can use that name to look it up in the array, or to look it up directly as a property of the document itself:
document.forms["address"]  // A named form
document.address           // The same thing
The Form object is particularly interesting. It has an elements[ ] array that contains objects representing the elements of the form, in the order they appear in the form. See Input, Select, and Textarea in the reference section for details on these form elements.
The elements[ ] array of a Form works much like the forms[ ] array of a Document: it holds form elements in the order they appear in the form, but it also allows them to be referred to by name. Consider this HTML excerpt:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The W3C DOM
The W3C DOM standardizes most of the features of the legacy DOM, but also adds important new ones. In addition to supporting forms[ ], images[ ], and other array properties of the Document object, it defines methods that allow scripts to access and manipulate any document element, not just special-purpose elements like forms and images.
When creating a document that contains special elements that will be manipulated by a script, you can identify each special element by giving it an id attribute with a unique value. Then, you can use the getElementById( ) method of the Document object to look up those elements by their ID:
<h1 id="title">Title</h1>  
<script>
var t = document.getElementById("title");
</script>
Another way to access document elements is to look them up by tag name. The getElementsByTagName( ) method of the Document object returns an array of all elements of that type. Each document element also supports the same method, so you can also obtain an array of specific types of tags that are all descendents of an element:
// Get an array of all <ul> tags
var lists = document.getElementsByTagName("ul");
// Find the 3rd <li> tag in the second <ul>
var item = lists[1].getElementsByTagName("li")[2];
The W3C DOM represents every document as a tree. The nodes of this tree represent the HTML tags, the strings of text, and the HTML comments that comprise the document. Each node of the tree is represented by a JavaScript object, and each has properties that allow you to traverse the tree, as illustrated by the following code fragment:
// Look up a node in the document
var n = document.getElementById("mynode");
var p = n.parentNode;  // The containing tag
var c0 = n.firstChild;    // First child of n
var c1 = c0.nextSibling;  // 2nd child of n
var c2 = n.childNodes[2]; // 3rd child of n
var last = n.lastChild;   // last child of n
See Node in the reference section for further details.
The Document object itself is a kind of node, and supports these same properties. The documentElement property of the Document object refers to the single
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
IE 4 DOM
The IE 4 DOM was introduced in Version 4 of Microsoft's Internet Explorer browser. It is a powerful but non-standard DOM with capabilities similar to those of the W3C DOM. IE 5 and later include support for most basic W3C DOM features, but this documentation on the IE 4 DOM is included because IE 4 is still commonly used. The following subsections document the IE 4 DOM in terms of its differences from the W3C DOM, so you should be familiar with the W3C DOM first.
The IE 4 DOM does not support the getElementById( ) method. Instead, it allows you to look up arbitrary document elements by id attribute within the all[ ] array of the document object:
var list = document.all["mylist"];
list = document.all.mylist;  // this also works
Instead of supporting the getElementsByTagName( ) method, the IE 4 DOM takes the unusual step of defining a tags( ) method on the all[ ] array, which exists on document elements as well as the Document object itself. Here's how to find all <li> tags within the first <ul> tag:
var lists = document.all.tags("UL");
var items = lists[0].all.tags("LI");
Note that you must specify the desired HTML tag name in uppercase with the all.tags( ) method.
You can traverse an IE 4 document tree in much the same way that you can traverse a W3C document tree. The difference is in the names of the relevant properties: instead of childNodes[ ], IE 4 uses children[ ], and instead of parentNode, IE 4 uses parentElement. IE 4 does not have any analogs to firstChild, nextSibling, and related W3C properties. One important difference between the IE 4 and W3C DOMs is that the IE 4 document tree only includes HTML tags: comments are ignored and document text is not part of the tree itself. Instead, the text contained by any element is available through the innerHTML and innerText properties of the element object. (We'll see more about innerHTML in the next section.)
The nodes of an IE 4 document tree are Element objects that are similar to the Element node of the W3C DOM. Like the Element nodes of a W3C document tree, these objects have properties that correspond to the attributes of the HTML tags, and you can query and set the properties as desired. To change the textual content of a document element, set its
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
DHTML: Scripting CSS Styles
DHTML, or Dynamic HTML, is the result of combining HTML, CSS, and JavaScript: it uses scripts to dynamically modify the style — which may include the position and visibility — of document elements. In the W3C and the IE 4 DOMs, every document element has a style property that corresponds to the HTML style attribute that specifies inline styles. Instead of referring to a simple string, however, the style property refers to a Style object that has properties corresponding to each of the CSS attributes of the style.
For example, if an element e has a style attribute that specifies the CSS color attribute, you can query the value of that attribute as e.style.color. When a CSS attribute name contains hyphens, the corresponding JavaScript property name removes the hyphens and uses mixed-case capitalization. Thus, to set the background-color CSS attribute of an element e, you set e.style.backgroundColor. There is one special case: the CSS float attribute is a reserved word in JavaScript, so the corresponding JavaScript property is cssFloat.
The CSS standard defines many properties that you can use to fine-tune the visual appearance of your documents. The Style entry in the reference section includes a table that lists them all. The positioning and visibility properties are particularly relevant for dynamic scripting. If the position property is set to absolute, you can use the top and left properties to specify the absolute position (in pixels, percentages, or other units) of the document element. Similarly, the width and height properties specify the size of the element. The visibility property can initially be set to hidden to make a document element invisible, and then dynamically set to visible to make the element appear when appropriate.
Note that the values of all Style properties are always strings, even for properties like left and width which represent numbers. When setting these length and dimension properties, be sure to convert your numbers to strings and to add the appropriate units specification (usually the string px for pixels.) The following table summarizes these positioning and visibility properties:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Events and Event Handling
We saw at the beginning of this section that one way to embed client-side JavaScript into HTML documents is to use event handler attributes of HTML tags. The following table lists the standard event handler attributes and the HTML tags to which they may be applied. The first column of the table gives the event handler attribute name: these names always begin with "on". The second column of the table lists the HTML tags to which these attributes can be applied, and explains, when necessary, what events trigger the handler code to be executed.
Handler
Supported by/Triggered when
onabort
<img>; image load aborted
onblur
<body> and form elements; window or element loses keyboard focus
onchange
Form elements; displayed value changes
onclick
All elements; mouse press and release; return false to cancel
ondblclick
All elements; mouse double-click
onerror
<img>; image loading fails
onfocus
<body> and form elements; window or element gets keyboard focus
onkeydown
<body> and form elements; key pressed; return false to cancel
onkeypress
<body> and form elements; key pressed and released; return false to cancel
onkeyup
<body> and form elements; key released
onload
<body>, <frameset>, <img>, <iframe>, <object>; document, image, or object completely loaded
onmousedown
All elements; mouse button pressed
onmousemove
All elements; mouse pointer moved
onmouseout
All elements; mouse moves off element
onmouseover
All elements; mouse moves over element; return true to prevent link URL display in status bar
onmouseup
All elements; mouse button released
onreset
<form>; form reset requested; return false to prevent reset
onresize
<body>, <frameset>; window size changes
onsubmit
<form>; form submission requested; return false to prevent submission
onunload
<body>, <frameset>; document unloaded
Note that when the browser triggers certain event handlers, such as onclick, onmouseover and onsubmit, it examines the return value of the handler (if there is one) to determine whether it should perform the default action associated with the event or not. Typically, if an event handler returns
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
JavaScript Security Restrictions
For security reasons, client-side JavaScript implementations typically impose restrictions on the tasks that scripts can perform. The most obvious restrictions are omissions of dangerous capabilities: there is no way for client-side JavaScript to delete files on a user's local hard disk, for example. Other restrictions exist to prevent the disclosure of private information or to keep scripts from annoying users. There is no standard set of security restrictions, but the following are restrictions found in typical browser implementations. Don't attempt to write scripts that do these things: even if they work for your browser, they probably won't work in others.
Same origin policy
Scripts can only read properties of windows and documents that were loaded from the same web server. This is a substantial and pervasive restriction on cross-window scripting, and prevents scripts from reading information from other unrelated documents that the user is viewing. This restriction also prevents scripts from registering event handlers or spoofing events on unrelated documents.
File uploads
Scripts cannot set the value property of the FileUpload form element.
Sending email and posting news
Scripts cannot submit forms to mailto: or news: URLs without user confirmation.
Closing windows
A script can only close browser windows that it created itself, unless it gets user confirmation.
Snooping in the cache
A script cannot load any about: URLs, such as about:cache.
Hidden windows and window decorations
A script cannot create small or offscreen windows or windows without a titlebar.
Note that this list of security restrictions is not static. As the use of JavaScript has grown, advertisers and unsavory characters have started doing annoying things with it. As a result, newer browsers, such as Mozilla 1.0, allow user-configurable security restrictions that can prevent scripts from opening new windows (such as pop-up ads), or from moving or resizing existing windows.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 3: JavaScript API Reference
The rest of this book contains a quick-reference for the core and client-side JavaScript APIs. It documents the complete core JavaScript API, covers the legacy (Level 0) DOM API, and presents a simplified view of the W3C Level 2 DOM API. Portions of that API not relevant to JavaScript programmers working with HTML documents have been omitted. The upper-right corner of the title block for each reference entry contains information that states whether a feature is part of the core or client-side API, and further indicates which version of JavaScript, which browsers, or which version of the DOM introduced the feature.
Because JavaScript is a loosely-typed language, there is not an official set of class names for the classes and objects of the JavaScript API, and they sometimes appear under different names in different references. (For brevity, this book actually uses a slightly different set of names than its big brother, JavaScript: The Definitive Guide.) The following table summarizes the reference entries that follow, and allows you to quickly scan for the class or object you are interested in.
Anchor
A named position in a document
Applet
A Java applet
Arguments
The arguments of a function
Array
Array creation and manipulation
Attr
An attribute of a document element
Boolean
A wrapper object for boolean values
Comment
An HTML comment
DOMException
Signals DOM errors
DOMImplementation
Creates documents, checks DOM features
Date
Manipulates dates and times
Document
An HTML document
DocumentFragment
Nodes to be manipulated together
Element
An HTML tag in a document
Error
Predefined exception types
Event
Event details
Form
An HTML input form
Function
A JavaScript function
Global
Global properties and functions
History
Browsing history
Image
An HTML image
Input
A form input element
Layer
An independent document layer
Link
An <a> or <area> link
Location
Current browser location
Math
Mathematical functions and constants
Navigator
Information about the browser
Node
A node in a document tree
Number
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!

Return to JavaScript Pocket Reference