Section 2.7. Alphabetical Object Reference


2.7. Alphabetical Object Reference


The a object reflects the a element, regardless of whether the element is set up to be an anchor, link, or both. Early versions of Netscape Navigator and Internet Explorer treat this object only as a member of the links[] and/or anchors[] arrays of a document. Starting with IE 4 and all browsers supporting the W3C DOM, you can access the object through supported element object reference syntax (e.g., the document.all[] collection for IE or document.getElementById( ) for IE 5 and later and W3C browsers).


HTML Equivalent

<a>


Object Model Reference

 [window.]document.links[i] [window.]document.anchors[i] [window.]document.getElementById("elementID") 


Object-Specific Properties

charset
coords
dataFld
dataFormatAs
dataSrc
hash
host
hostname
HRef
HReflang
Methods
mimeType
name
nameProp
pathname
port
protocol
protocolLong
rel
rev
search
shape
target
text
type
urn

Object-Specific Methods

None.


Object-Specific Events

Event

IE

Mozilla

Safari

Opera

W3C DOM

blur

·

·

·

click

·

·

·

·

·

dblclick

·

·

·

focus

·

·

·

help

·

mousedown

·

·

·

·

·

mousemove

·

·

·

·

·

mouseout

·

·

·

·

·

mouseover

·

·

·

·

·

mouseup

·

·

·

·

·


Anchor-only a objects have no events in Navigator through Version 4.


Character encoding of the document's content.


Example

 if (document.getElementById("myAnchor").charset == "csISO5427Cyrillic") {     // process for Cyrillic charset } 


Value

Case-insensitive alias from the character set registry (ftp://ftp.isi.edu/in-notes/iana/assignments/character-sets).


Default

Determined by browser.


Defines the outline of an area to be associated with a particular link or scripted action. This property is a member of the a object, but really belongs to the area object, which inherits the properties of the a object. Coordinate values are entered as a comma-delimited list. If hotspots of two areas should overlap, the area that is defined earlier in the code takes precedence.


Example

 document.getElementById("mapArea2").coords = "25, 5, 50, 70"; 


Value

Each coordinate is a length value, but the number of coordinates and their order depend on the shape specified by the shape attribute, which may optionally be associated with the element. For shape="rect", there are four coordinates (left, top, right, bottom); for shape="circle" there are three coordinates (center-x, center-y, radius); for shape="poly" there are two coordinate values for each point that defines the shape of the polygon.


Default

None.


Used with IE data binding to associate a remote data source column value in lieu of an href attribute for a link. The datasrc attribute must also be set for the element. Setting both the dataFld and dataSrc properties to empty strings breaks the binding between element and data source. Works only with text file data sources in IE 5/Mac.


Example

 document.getElementById("hotlink").dataFld = "linkURL"; 


Value

Case-sensitive identifier of the data source column.


Default

None.


Used with IE data binding, this property advises the browser whether the source material arriving from the data source is to be treated as plain text or as tagged HTML.


Example

 document.getElementById("hotlink").dataFormatAs = "HTML"; 


Value

IE recognizes two possible settings: text | html.


Default

text


Used with IE data binding to specify the ID of the page's object element that loads the data source object for remote data access. Content from the data source to be inserted into the a element text is specified via the datafld property. Setting both the dataFld and dataSrc properties to empty strings breaks the binding between element and data source. Works only with text file data sources in IE 5/Mac.


Example

 document.all.hotlink.dataSrc = "#DBSRC3"; 


Value

Case-sensitive identifier of the data source.


Default

None.


Provides that portion of the HRef attribute's URL following the # symbol, referring to an anchor location in a document. Do not include the # symbol when setting the property.


Example

 document.getElementById("myLink").hash = "section3"; document.links[2].hash = "section3"; 


Value

String.


Default

None.


This is the combination of the hostname and port (if any) of the server of the destination document for the link. If the port is explicitly part of the URL, the hostname and port are separated by a colon, just as they are in the URL. If the port number is not specified in an HTTP URL for IE, it automatically returns the default, port 80.


Example

 document.getElementById("myLink").host = "www.megacorp.com:80"; document.links[2].host = "www.megacorp.com:80"; 


Value

String of hostname optionally followed by a colon and port number.


Default

Depends on server.


This is the hostname of the server (i.e., a "two-dot" address consisting of server name and domain) of the destination document for the link. The hostname property does not include the port number.


Example

 document.getElementById("myLink").hostname = "www.megacorp.com"; document.links[2].hostname = "www.megacorp.com"; 


Value

String of hostname (server and domain).


Default

Depends on server.


Provides the URL specified by the element's HRef attribute.


Example

 document.getElementById("myLink").href = "http://www.megacorp.com"; document.links[2].href = "http://www.megacorp.com"; 


Value

String of complete or relative URL.


Default

None.


Provides the language code of the content at the destination of a link. Requires that the href attribute or property also be set.


Example

 document.getElementById("myLink").hreflang = "DE"; 


Value

Case-insensitive language code.


Default

None.


Provides an advisory attribute about the functionality of the destination of a link. A browser could use this information to display special colors or images for the element content based on what the destination does for the user, but Internet Explorer does not appear to do anything with this information.


Example

 document.links[1].Methods = "post"; 


Value

Any valid HTTP method as a string.


Default

None.


Returns a plain-language version of the MIME type of the destination document at the other end of the link specified by the HRef attribute. You could use this information to set the cursor type during a mouse rollover. Don't confuse this property with the navigator.mimeTypes[] array and individual mimeType objects that Netscape Navigator refers to. This is not available in IE 4/Macintosh.


Example

 if (document.getElementById("myLink").mimeType == "GIF Image") {     ... } 


Value

A plain-language reference to the MIME type as a string.


Default

None.


This is the identifier associated with an element that turns it into an anchor. You can also use the name as part of the object reference.


Example

 if (document.links[12].name == "section3") {     ... } 


Value

Case-sensitive identifier that follows the rules of identifier naming: it may contain no whitespace, cannot begin with a numeral, and should avoid punctuation except for the underscore character.


Default

None.


Returns just the filename, rather than the full URL, of the HRef attribute set for the element.


Example

 if (document.getElementById("myLink").nameProp == "logo2.gif") {     ... } 


Value

String.


Default

None.


Provides the pathname component of the URL assigned to the element's href attribute. This consists of all URL information following the last character of the domain name, including the initial forward slash symbol.


Example

 document.getElementById("myLink").pathname = "/images/logoHiRes.gif"; document.links[2].pathname = "/images/logoHiRes.gif"; 


Value

String.


Default

None.


Provides the port component of the URL assigned to the element's href attribute. This consists of all URL information following the colon after the last character of the domain name. The colon is not part of the port property value.


Example

 document.getElementById("myLink").port = "80"; document.links[2].port = "80"; 


Value

String (a numeric value as string).


Default

None.


Indicates the protocol component of the URL assigned to the element's href attribute. This consists of all URL information up to and including the first colon of a URL. Typical values are: "http:", "file:", "ftp:", and "mailto:".


Example

 document.getElementById("secureLink").protocol = "https:"; 


Value

String.


Default

None.


Provides a verbose description of the protocol implied by the URL of the href attribute or href property. Appears to be deprecated.


Example

 if (document.getElementById("myLink").protocolLong ==     "HyperText Transfer Protocol") {     // statements for treating document as server file } 


Value

String.


Default

None


Defines the relationship between the current element and the destination of the link. Also known as a forward link, not to be confused in any way with the destination document whose address is defined by the HRef attribute. Mainstream browsers do not take advantage of this attribute for the a element, but you can treat the attribute as a kind of parameter to be checked and/or modified under script control. See the discussion of the a element's rel attribute in Chapter 1 for a glimpse of how this property may be used in the future.


Value

Case-insensitive, space-delimited list of HTML 4.0 standard link types (as a single string) applicable to the element. Sanctioned link types are:

alternate
appendix
bookmark
chapter
contents
copyright
glossary
help
index
next
prev
section
start
stylesheet
subsection

Default

None.


Defines the relationship between the current element and the destination of the link. Also known as a reverse link. This property is not exploited yet in mainstream browsers, but you can treat the attribute as a kind of parameter to be checked and/or modified under script control. See the discussion of the a element's rev attribute in Chapter 1 for a glimpse of how this property may be used in the future.


Value

Case-insensitive, space-delimited list of HTML 4.0 standard link types (as a single string) applicable to the element. See the rel property for sanctioned link types.


Default

None.


Provides the URL-encoded portion of a URL assigned to the href attribute that begins with the ? symbol. A document that is served up as the result of the search also may have the search portion available as part of the window.location property. You can modify this property with a script. Doing so sends the URL and search criteria to the server. You must know the format of data (usually name/value pairs) expected by the server to perform this properly.


Example

 document.getElementById("searchLink").search="?p=Tony+Blair&d=y&g=0&s=a&w=s&m=25"; document.links[1].search="?p=Tony+Blair&d=y&g=0&s=a&w=s&m=25"; 


Value

String starting with the ? symbol.


Default

None.


Indicates the shape of a server-side image map area, with coordinates that are specified with the COORDS attribute. Intended for use by the area object, which inherits the properties of the a object.


Example

 document.getElementById("myLink").shape = "circle"; 


Value

Case-insensitive shape constant as string: default | rect | rectangle | circle | poly | polygon.


Default

rect


Provides the name of the window or frame that is to receive content as the result of navigating to a link. Such names are assigned to frames by the frame element's name attribute; for subwindows, the name is assigned via the second parameter of the window.open( ) method. If you need the services of a target attribute to open a linked page in a blank browser window and you also need the markup to validate under strict HTML or XHTML DTDs (see Online Section VI), you can omit the target attribute in the code, but you must assign a value to the a element's target property by script after the page loads.


Example

 document.getElementById("homeLink").target = "_top"; document.links[3].target = "_top"; 


Value

String value of the window or frame name, or any of the following constants (as a string): _parent | _self | _top | _blank. The _parent value targets the frameset to which the current document belongs; the _self value targets the current window; the _top value targets the main browser window, thereby eliminating all frames; and the _blank value creates a new window of default size.


Default

None.


Returns the text between the a element's start and end tags. This property pre-dates the W3C DOM and should be used only if needed for Navigator 4 (even though Mozilla, Safar, and Opera support it).


Value

String value.


Default

None.


This is the MIME type of the destination document at the other end of the link specified by the HRef attribute. A browser might use this information to assist in preparing support for a resource requiring a multimedia player or plugin.


Example

 if (document.getElementById("myLink").type == "image/jpeg") {     ... } 


Value

Case-insensitive MIME type. A catalog of registered MIME types is available from ftp://ftp.isi.edu/in-notes/iana/assignments/media-types/.


Default

None.


Indicates a Uniform Resource Name (URN) version of the destination document specified in the HRef attribute. This attribute is intended to offer support in the future for the URN format of URI, an evolving recommendation under discussion at the IETF (see RFC 2141). Although supported in IE, this attribute does not take the place of the href attribute.


Example

 document.getElementById("link3").urn = "http://www.megacorp.com"; 


Value

Complete or relative URN as a string.


Default

None.


All these objects reflect the corresponding HTML phrase elements of the same name. Each of these phrase elements provides a context for an inline sequence of content. Some of these elements are rendered in ways to distinguish themselves from running text. See the HTML element descriptions in Chapter 1 for details. From a scripted standpoint, all phrase element objects share the same set of properties, methods, and events.


HTML Equivalent

 <abbr> <acronym> <cite> <code> <dfn> <em> <kbd> <samp> <strong> <var> 


Object Model Reference

 [window.]document.getElementById("elementID") 


Object-Specific Properties

None.


Object-Specific Methods

None.


Object-Specific Events

None.


See the window object.


The address object reflects the address element.


HTML Equivalent

<address>


Object Model Reference

 [window.]document.getElementById("elementID") 


Object-Specific Properties

None.


Object-Specific Methods

None.


Object-Specific Events

None.


A collection of elements nested within the current element (only document.all is partially supported in Mozilla). A reference to document.all, for example, returns a collection (array) of all element objects contained by the document, including elements that may be deeply nested inside the document's first level of elements. The collection is sorted in source code order of the element tags. You can retrieve a reference to an element with its ID by any of the following syntaxes:

 document.all.elementID document.all["elementID"] document.all("elementID"] document.all.item("elementID") document.all.namedItem("elementID") 

The W3C DOM equivalent (the document.getElementById( ) method) operates only from the document object, providing global reach to elements throughout the entire document. Note that Mozilla's support for document.all operates only in quirks mode, and displays a warning message in the JavaScript/Error Console with each usage. Additionally, if you test for the existence of document.all in an if condition, the browser returns a value as if document.all does not existthus preventing scripts that use document.all as an Internet Explorer browser detector from executing within Mozilla.


Object Model Reference

 elementReference.all 


Object-Specific Properties

length

Object-Specific Methods

item( )
namedItem( )
tags( )
urns( )

Object-Specific Events

None.


Returns the number of elements in the collection.


Example

 var howMany = document.all.length; 


Value

Integer.


item( index[, subindex])

Returns a single object or collection of objects corresponding to the element matching the index value (or, optionally, the index and subindex values).


Returned Value

One object or collection (array) of objects. If there are no matches to the parameters, the returned value is null.


Parameters


index

When the parameter is a zero-based integer, the returned value is a single element corresponding to the specified item in source code order (nested within the current element); when the parameter is a string, the returned value is a collection of elements whose id or name properties match that string.


subindex

If you specify a string value for the first parameter, you can use the second parameter to specify a zero-based index that retrieves the specified element from the collection whose id or name properties match the first parameter's string value.


namedItem( IDOrName)

Returns a single object or collection of objects corresponding to the element matching the parameter string value.


Returned Value

One object or collection (array) of objects. If there are no matches to the parameters, the returned value is null.


Parameters


IDOrName

The string that contains the same value and case as the desired element's id or name attribute.


tags( tagName)

Returns a collection of objects (among all objects nested within the current element) whose tags match the tagName parameter.


Returned Value

A collection (array) of objects. If there are no matches to the parameters, the returned value is an array of zero length.


Parameters


tagName

A case-insensitive string that contains the element tag name only (no angle brackets), as in document.all.tags("p").


urns( URN)

Returns a collection of nested element objects that have behaviors attached to them and whose URNs match the URN parameter.


Returned Value

A collection (array) of objects. If there are no matches to the parameters, the returned value is an array of zero length.


Parameters


URN

A string with a local or external behavior file URN.


A collection of all a elements with assigned name attributes that make them behave as anchors (instead of links). Collection members are sorted in source code order. All browsers let you use array notation to access a single anchor in the collection (e.g., document.anchors[0], document.anchors["section3"]). Internet Explorer also allows the index value to be placed inside parentheses instead of brackets (e.g., document.anchors(0)). If you want to use the anchor's name as an index value (always as a string identifier), be sure to use the value of the name attribute, rather than the id attribute. To use the id attribute in a reference to an anchor, access the object via a document.all.elementID (in IE only) or document.getElementById("elementID") reference. Recent browsers include additional methods that provide named or indexed access.


Object Model Reference

 document.anchors 


Object-Specific Properties

length

Object-Specific Methods

item( )
namedItem( )
tags( )
urns( )

Object-Specific Events

None.


Returns the number of elements in the collection.


Example

 var howMany = document.anchors.length; 


Value

Integer.


item( index[, subindex])


item( index)

Returns a single anchor object or collection of anchor objects corresponding to the element matching the index value (or, optionally in IE, the index and subindex values).


Returned Value

One anchor object or collection (array) of anchor objects. If there are no matches to the parameters, the returned value is null.


Parameters


index

When the parameter is a zero-based integer (per the W3C spec), the returned value is a single element that corresponds to the specified item in source code order. When the parameter is a string (IE), the returned value is a collection of elements whose id or name properties match that string.


subindex

In IE only, if you specify a string value for the first parameter, you can use the second parameter to specify a zero-based index that retrieves the specified element from the collection with id or name properties that match the first parameter's string value.


namedItem( IDOrName)

Returns a single anchor object or collection of anchor objects corresponding to the element matching the parameter string value.


Returned Value

One anchor object or collection (array) of anchor objects. If there are no matches to the parameters, the returned value is null.


Parameters


IDOrName

The string that contains the same value as the desired element's id or name attribute.


tags( tagName)

Returns a collection of objects (among all objects nested within the current collection) with tags that match the tagName parameter. Implemented in all IE, Safari, and Opera collections (see the all.tags( ) method), but redundant for collections of the same element type.


urns( URN)

See the all.urns( ) method.


The applet object reflects the applet element. Note that although no object-specific methods are listed here, applets expose public properties and methods to scripts through LiveConnect, where supported. In particular, if you iterate through the properties and methods of an applet in a Mozilla-based browser, you will find a long list of public methods that are specific to the applet currently loaded into the applet element.


HTML Equivalent

<applet>


Object Model Reference

 [window.]document.appletName [window.]document.getElementById("elementID") 


Object-Specific Properties

align
alt
altHTML
archive
code
codeBase
dataFld
dataSrc
height
hspace
name
object
vspace
width

Object-Specific Methods

None.


Object-Specific Event Properties

None.


Defines the alignment of the element within its surrounding container. See "Alignment Constants" at the beginning of Chapter 1 for the various meanings that different values bring to this property.


Example

 document.getElementById("myApplet").align = "center"; 


Value

Any of the alignment constants: absbottom | absmiddle | baseline | bottom | left | middle | right | texttop | top.


Default

left


This is the text message to be displayed if the object or applet fails to load. There is little indication that setting this property on an existing applet object has any visual effect.


Example

 document.myApplet.alt= "Image Editor Applet"; 


Value

Any quoted string of characters, but HTML tags are not interpreted.


Default

None.


Provides the HTML content to be displayed if the object or applet fails to load. This can be a message, static image, or any other HTML that best fits the scenario. There is little indication that setting this property on an existing applet object has any visual effect.


Example

 document.myApplet.altHTML = "<img src='/books/2/570/1/html/2/appletAlt.gif'>"; 


Value

Any quoted string of characters, including HTML tags.


Default

None.


Reflects the archive attribute of the applet element. Only partially implemented in the browsers. See the discussion of the archive attribute in Chapter 1.


Example

 if (document.applets["clock"].archive == "myClock.zip") {     // process for the found class file } 


Value

Case-sensitive URI as a string.


Default

None.


Provides the name of the Java applet class file set to the code attribute.


Example

 if (document.applets["clock"].code == "XMAScounter.class") {     // process for the found class file } 


Value

Case-sensitive applet class filename as a string.


Default

None.


Provides the path to the directory holding the class file designated in the code attribute. The codebase attribute does not name the class file, just the path.


Example

 if (document.applets["clock"].codeBase == "classes") {     // process for the found class file directory } 


Value

Case-sensitive pathname, usually relative to the directory storing the current HTML document.


Default

None.


It is unclear how you would use this property with an applet object because the dataFld and dataSrc properties (as set in element attributes) are applied to individual param elements.


Value

Case-sensitive identifier of the data source column.


Default

None.


It's unclear how you would use this property with an applet object because the dataFld and dataSrc properties (as set in element attributes) are applied to individual param elements.


Value

Case-sensitive identifier of the data source.


Default

None.


Indicate the height and width in pixels of the element as set by the tag attributes. Changing the values does not necessarily change the actual rectangle of the applet after it has loaded.


Example

 var appletHeight = document.myApplet.height; 


Value

Integer.


Default

None.


Indicate the pixel measure of horizontal and vertical margins surrounding an applet. The hspace property affects the left and right edges of the element equally; the vspace affects the top and bottom edges of the element equally. These margins are not the same as margins set by style sheets, but they have the same visual effect.


Example

 document.getElementById("myApplet").hspace = 5; document.getElementById("myApplet").vspace = 8; 


Value

Integer of pixel count.


Default

0


This is the identifier associated with the applet. Use the name when referring to the object in the form document.appletName.


Value

Case-sensitive identifier that follows the rules of identifier naming: it may contain no whitespace, cannot begin with a numeral, and should avoid punctuation except for the underscore character.


Default

None.


Returns a reference to the applet object so that a script can access a property or method of the applet whose name is identical to a property or method of the applet element object. Although the functional version of this property is available only in IE, other supporting browsers simply return an empty string for its value.


Value

In IE, an applet object (not the applet element object) reference; in other supporting browsers, an empty string.


Default

None.


See hspace.


See height.


A collection of all the Java applets in the current element, sorted in source code order. Navigator and Internet Explorer let you use array notation to access a single applet in the collection (e.g., document.applets[0], document.applets["clockApplet"]). Internet Explorer allows the index value to be placed inside parentheses instead of brackets (e.g., document.applets(0)). If you wish to use the applet's name as an index value (always as a string identifier), use the value of the name attribute rather than the id attribute. To use the id attribute in a reference to an applet, access the object via a document.all.elementID (in IE only) or document.getElementById("elementID") reference.


Object Model Reference

 document.applets[i] 


Object-Specific Properties

length

Object-Specific Methods

item( )
namedItem( )
tags( )

Returns the number of elements in the collection.


Example

 var howMany = document.applets.length; 


Value

Integer.


item( index[, subindex]) item( index)

Returns a single applet object or collection of applet objects corresponding to the element matching the index value (or, optionally in IE, the index and subindex values).


Returned Value

One applet object or collection (array) of applet objects. If there are no matches to the parameters, the returned value is null.


Parameters


index

When the parameter is a zero-based integer, the returned value is a single element corresponding to the specified item in source code order (nested within the current element); when the parameter is a string, the returned value is a collection of elements whose id or name properties match that string.


subindex

In IE only, if you specify a string value for the first parameter, you can use the second parameter to specify a zero-based index that retrieves the specified element from the collection whose id or name properties match the first parameter's string value.


namedItem( IDOrName)

Returns a single applet object or collection of applet objects corresponding to the element matching the parameter string value.


Returned Value

One applet object or collection (array) of applet objects. If there are no matches to the parameters, the returned value is null.


Parameters


IDOrName

The string that contains the same value as the desired element's id or name attribute.


tags( tagName)

Returns a collection of objects (among all objects nested within the current collection) with tags that match the tagName parameter. Implemented in all IE, Safari, and Opera collections (see the all.tags( ) method), but redundant for collections of the same element type.


The area object reflects the area element, which defines the shape, coordinates, and destination of a clickable region of a client-side image map. Navigator and Internet Explorer treat an area object as a member of the links collection, since an area object behaves much like a link, but for a segment of an image.


HTML Equivalent

 <area> 


Object Model Reference

 [window.]document.links[i] [window.]document.getElementById("elementID") 


Object-Specific Properties

alt
coords
hash
host
hostname
href
noHref
pathname
port
protocol
search
shape
target

Object-Specific Methods

None.


Object-Specific Events

None.


Future nongraphical browsers may use the alt property setting to display a brief description of the meaning of the (invisible) image's hotspots.


Example

 document.getElementById("elementID").alt = "To Next Page"; 


Value

Any quoted string of characters.


Default

None.


Defines the outline of the area to be associated with a particular link or scripted action. Coordinate values are entered as a comma-delimited list. If hotspots of two areas should overlap, the area that is defined earlier in the code takes precedence.


Example

 document.getElementById("mapArea2").coords = "25, 5, 50, 70"; 


Value

Each coordinate is a pixel length value, but the number of coordinates and their order depend on the shape specified by the shape attribute, which may optionally be associated with the element. For shape="rect", there are four coordinates (left, top, right, bottom); for shape="circle", there are three coordinates (center-x, center-y, radius); for shape="poly", there are two coordinate values for each point that defines the shape of the polygon.


Default

None.


This is that portion of the HRef attribute's URL following the # symbol, referring to an anchor location in a document. Do not include the # symbol when setting the property.


Example

 document.getElementById("mapArea2").hash = "section3"; 


Value

String.


Default

None.


Provides the combination of the hostname and port (if any) of the server of the destination document for the area link. If the port is explicitly part of the URL, the hostname and port are separated by a colon, just as they are in the URL. If the port number is not specified in an HTTP URL for IE, it automatically returns the default, port 80.


Example

 document.getElementById("mapArea2").host = "www.megacorp.com:80"; 


Value

String of hostname optionally followed by a colon and port number.


Default

Depends on server.


Provides the hostname of the server (i.e., a two-dot address consisting of server name and domain) of the destination document for the area link. The hostname property does not include the port number.


Example

 document.areas[2].hostname = "www.megacorp.com"; 


Value

String of hostname (server and domain).


Default

Depends on server.


This is the URL specified by the element's href attribute.


Example

 document.areas[2].href = "http://www.megacorp.com"; 


Value

String of complete or relative URL.


Default

None.


Specifies whether the area defined by the coordinates has a link associated with it. When you set this property to TRue, scriptable browsers no longer treat the element as a link.


Example

 document.areas[4].noHref = "true"; 


Value

Boolean value: true | false.


Default

false


Provides the pathname component of the URL assigned to the element's href attribute. This consists of all URL information following the last character of the domain name, including the initial forward slash symbol.


Example

 document.getElementById("myLink").pathname = "/images/logoHiRes.gif"; 


Value

String.


Default

None.


Provides the port component of the URL assigned to the element's href attribute. This consists of all URL information following the colon after the last character of the domain name. The colon is not part of the port property value.


Example

 document.getElementById("myLink").port = "80"; 


Value

String (a numeric value as string).


Default

None.


Indicates the protocol component of the URL assigned to the element's href attribute. This consists of all URL information up to and including the first colon of a URL. Typical values are "http:", "file:", "ftp:", and "mailto:".


Example

 document.getElementById("secureLink").protocol = "https:"; 


Value

String.


Default

None.


This is the URL-encoded portion of a URL assigned to the href attribute that begins with the ? symbol. A document that is served up as the result of the search also may have the search portion available as part of the window.location property. You can modify this property with a script. Doing so sends the URL and search criteria to the server. You must know the format of data (usually name/value pairs) expected by the server to perform this properly.


Example

 document.getElementById("searchLink").search="?p=Tony+Blair&d=y&g=0&s=a&w=s&m=25"; 


Value

String starting with the ? symbol.


Default

None.


Indicates the shape of a server-side image map area with coordinates that are specified with the coords attribute.


Example

 document.getElementById("area51").shape = "circle"; 


Value

Case-insensitive shape constant as string: default | rect | rectangle | circle | poly | polygon.


Default

RECT (IE); empty string but rect implied (Mozilla).


This is the name of the window or frame that is to receive content as the result of navigating to an area link. Such names are assigned to frames by the frame element's name attribute; for subwindows, the name is assigned via the second parameter of the window.open( ) method. If you need the services of a target attribute to open a linked page in a blank browser window and you also need the HTML to validate under strict HTML or XHTML DTDs, you can omit the target attribute in the code, but assign a value to the area element's target property by script after the page loads.


Example

 document.getElementById("homeArea").target = "_blank"; 


Value

String value of the window or frame name, or any of the following constants (as a string): _parent | _self | _top | _blank. The _parent value targets the frameset to which the current document belongs; the _self value targets the current window; the _top value targets the main browser window, thereby eliminating all frames; and the _blank value creates a new window of default size.


Default

None.


A collection of all area elements associated with a map element. Notice that individual items of an areas collection are also members of the document-wide links collection (document.links[] array). But the members of an areas collection are local to a single map element.


Object Model Reference

 document.getElementById("mapElementID").areas 


Object-Specific Properties

length

Object-Specific Methods

item( )
namedItem( )
tags( )
urns( )

Returns the number of elements in the collection.


Example

 var howMany = document.areas.length; 


Value

Integer.


item( index[, subindex]) item( index)

Returns a single area object or collection of area objects corresponding to the element matching the index value (or, optionally in IE, the index and subindex values).


Returned Value

One area object or collection (array) of area objects. If there are no matches to the parameters, the returned value is null.


Parameters


index

When the parameter is a zero-based integer, the returned value is a single element corresponding to the specified item in source code order (nested within the current element); when the parameter is a string, the returned value is a collection of elements whose id or name properties match that string.


subindex

In IE only, if you specify a string value for the first parameter, you can use the second parameter to specify a zero-based index that retrieves the specified element from the collection whose id or name properties match the first parameter's string value.


namedItem( IDOrName)

Returns a single area object or collection of area objects corresponding to the element matching the parameter string value.


Returned Value

One area object or collection (array) of area objects. If there are no matches to the parameters, the returned value is null.


Parameters


IDOrName

The string that contains the same value as the desired element's id or name attribute.


tags( tagName)

Returns a collection of objects (among all objects nested within the current collection) with tags that match the tagName parameter. Implemented in all IE, Safari, and Opera collections (see the all.tags( ) method), but redundant for collections of the same element type.


urns( URN)

See the all.urns( ) method.


An abstract representation of an element's attribute name/value pair is an object known in the W3C DOM vernacular as the Attr object; in IE terminology, it is called an attribute object. They are different names for the same object. An attribute object is created in both environments via the document.createAttribute( ) method; the reference to the attribute object then becomes the parameter to an element's setAttributeNode( ) method to insert that attribute object into the element. For example:

 var newAttr = document.createAttribute("author"); newAttr.value = "William Shakespeare"; document.getElementById("hamlet").setAttributeNode(newAttr); 

Some W3C DOM element methods (most notably, the getAttributeNode( ) method) return attribute objects, which have properties that may be accessed like any scriptable object.

In the W3C DOM abstract model, the Attr object inherits all properties and methods of the Node object. Some Node object properties, however, are not inherited by the attribute object in IE/Windows until Version 6, even though they are implemented for element and text nodes in Version 5.


HTML Equivalent

Any name/value pair inside a start tag.


Object Model Reference

 [window.]document.getElementById("elementID").attributes[i] [window.]document.getElementById("elementID").attributes.item(i) [window.]document.getElementById("elementID").attributes.getNamedItem[attrName] 


Object-Specific Properties

expando
name
ownerElement
specified
value

Object-Specific Methods

None.


Object-Specific Events

None.


Returns Boolean TRue if the attribute, once it is inserted into an element, is not one of the native attributes for the element. This property is false for an attribute created by document.createAttribute( ) until the attribute is added to the element (via the setAttributeNode( ) method), at which time the property's value is reevaluated within the context of the element's native attributes.


Example

 var isCustomAttr =   document.getElementById("book3928").getAttributeNode("author").expando; 


Value

Boolean value: true | false.


Default

false


This is the name portion of the name/value pair of the attribute. It is identical to the nodeName property of the Attr node. You may not modify the name of an attribute by script because other dependencies may lead to document tree confusion. Instead, replace the old attribute with a newly created one, the name of which is a required parameter of the document.createAttribute( ) method.


Example

 if (myAttr.name == "author") {     // process author attribute } 


Value

String value.


Default

Empty string, although creating a new attribute requires a name.


Refers to the element that contains the current attribute object. Until a newly created attribute is inserted into an element, this property is null.


Example

 if (myAttr.ownerElement.tagName == "fred") {     // process attribute of <fred> element } 


Value

Element node reference.


Default

null


Returns Boolean true if the value of the attribute is explicitly assigned in the source code or adjusted by script. If the browser reflects an attribute that is not explicitly set (IE does this), the specified property for that value is false, even though the attribute may have a default value determined by the document's DTD. The W3C DOM Level 2 recommends (and Safari and Opera support) that the specified property of a freshly created Attr object should be true, but both IE 6+ and Mozilla leave it false until the attribute is inserted into an element.


Example

 if (myAttr.specified) {     // process attribute whose value is something other than DTD default } 


Value

Boolean value: true | false.


Default

false


Provides the value portion of the name/value pair of the attribute. Identical to the nodeValue property of the Attr node, as well as data accessed more directly via an element's getAttribute( ) and setAttribute( ) methods. If you create a new attribute object, you can assign its value via the value property prior to inserting the attribute into the element. Attribute node values are always strings, including in IE, which otherwise allows Number or Boolean data types for the corresponding properties.


Example

 document.getElementById("hamlet").getAttributeNode("author").value = "Shakespeare"; 


Value

String value.


Default

Empty string, except in IE/Windows, which returns the string undefined (that is, not a value whose type evaluates to the undefined value).


The object returned by the attributes property of every W3C DOM element object is a collection (array) of references to Attr (a.k.a. attribute) objects. An attribute type of node always has a name associated with it, which opens the way for methods of the collection of such nodes to access them directly by name, rather than iterating through the array in search of a matching node name. In the W3C DOM structure, the abstract representation of this array of named nodes is called the NamedNodeMap object, which shares some properties and methods of the IE attributes object. Since both objects refer to the same parts of a document tree, they are treated here together. A couple of other W3C DOM collections are also of the NamedNodeMap variety, but your primary contact with the NamedNodeMap in HTML documents is as a collection of Attr objects. Collection members are sorted in source code order.

There are more direct ways to access an attribute of an element (such as the getAttribute( ) or getAttributeNode( ) methods of all elements). The property and methods shown here, however, assume that your script has been handed a collection of attributes independent of their host element, and your processing starts from that point.


Object Model Reference

 elementReference.attributes 


Object-Specific Properties

length

Object-Specific Methods

getNamedItem( )
getNamedItemNS( )
item( )
removeNamedItem( )
removeNamedItemNS( )
setNamedItem( )
setNamedItemNS( )

Object-Specific Events

None.


Returns the number of elements in the collection.


Example

 var howMany = document.getElementById("myTable").attributes.length; 


Value

Integer.


getNamedItem(" attributeName")

Returns a single Attr object corresponding to the attribute whose node name matches the parameter value.


Returned Value

Reference to one Attr object. If there is no match to the parameter value, the returned value is null.


Parameters


attributeName

String corresponding to the name portion of an attribute's name/value pair.


getNamedItemNS(" namespaceURI", " localName")

Returns a single Attr object with a local name and namespace URI that match the parameter values.


Returned Value

Reference to one Attr object. If there is no match to the parameter values, the returned value is null.


Parameters


namespaceURI

URI string matching a URI assigned to a label earlier in the document.


localName

The local name portion of the attribute.


item( index)

Returns a single Attr object corresponding to the element matching the index value.


Returned Value

Reference to one Attr object. If there is no match to the index value, the returned value is null. Unlike some other collections in IE, a string index value is not allowed for the attributes object.


Parameters


index

A zero-based integer corresponding to the specified item in source code order.


removeNamedItem(" attributeName")

Removes from the collection a single Attr object corresponding to the attribute whose node name matches the parameter value.


Returned Value

Reference to the removed Attr object. If there is no match to the parameter value, the returned value is null.


Parameters


attributeName

String corresponding to the name portion of an attribute's name/value pair.


removeNamedItemNS(" namespaceURI", " localName")

Removes from the collection a single Attr object whose local name and namespace URI match the parameter values.


Returned Value

Reference to the removed Attr object. If there is no match to the parameter values, the method generates an error.


Parameters


namespaceURI

URI string matching a URI assigned to a label earlier in the document.


localName

The local name portion of the attribute.


setNamedItem( attrObjectReference)

Inserts a single Attr object into the current collection of attributes. If the destination of the attribute is an existing element, you may also use the setAttributeNode( ) method on the element to insert the Attr object. When the setNamedItem( ) method is invoked, the browser first looks for a match between the new attribute's name and existing attribute names within the collection. If there is a match, the new attribute replaces the original one; otherwise, the new attribute is added to the collection.


Returned Value

Reference to an Attr object either created anew or referenced from elsewhere in the document tree.


Parameters


attrObjectReference

A reference to an Attr node object created through document.createAttribute( ) or an Attr node from another element in the document tree.


setNamedItemNS( attrObjectReference)

Inserts a single Attr object into the current collection of attributes. If the destination of the attribute is an existing element, you may also use the setAttributeNodeNS( ) method on the element to insert the Attr object. When the setNamedItemNS( ) method is invoked, the browser first looks for a match between the new attribute's pairing of local name and namespace URI and existing attribute local names and namespace URIs within the collection. If there is a match, the new attribute replaces the original one; otherwise, the new attribute is added to the collection.


Returned Value

Reference to an Attr object either created anew or referenced from elsewhere in the document tree.


Parameters


attrObjectReference

A reference to an Attr node object created through document.createAttributeNS( ) or an Attr node from another element in the document tree.


The Audio object is a script-only control, whose standard is under the guidance of the WHATWG. Opera 9 is the first mainstream browser to support the object, whose purpose is to give scripts a standardized way of loading, playing, and stopping background sound. There is no plugin control panel automatically displayed by the browser, so it is up to the page designer to offer controls, if needed.

To use the object, create an instance of it by invoking the constructor function, passing as the sole parameter, the URL of the sound file to load. Opera 9 currently supports .wav files:

 var aud = new Audio("sample.wav"); 

You can use the load event to trigger the play( ) method.


Object Model Reference

 new Audio("audioFile") 


Object-Specific Properties

None.


Object-Specific Methods

loop( )
play( )
stop( )

Object-Specific Events

Event

IE

Mozilla

Safari

Opera

W3C DOM

error

·

load

·



loop([ count])

Controls how many times the loaded sound should play when the play( ) method is invoked. If the parameter is empty, the sound plays continuously.


Returned Value

None


Parameters


count

An integer controlling how many times the sound is to play.


Begins or halts the playback through the instance of the Audio object. The file must be completely loaded before playback can begin. When you stop the playback, the playback counter is reset to zero, and the playback pointer is set to the beginning of the file.


Returned Value

None.


Parameters

None.


All these objects reflect the HTML font-related style elements of the same name. Each of these elements specifies a rendering style for an inline sequence of content governed by each browser's default internal style sheet rules. All the elements are deprecated in HTML 4 in favor of style sheet attributes. See the HTML element descriptions in Chapter 1 for details. From a scripted standpoint, all font-related style element objects share the same set of properties, methods, event handlers, and collections.


HTML Equivalent

 <b> <big> <i> <s> <small> <strike> <tt> <u> 


Object Model Reference

 [window.]document.getElementById("elementID") 


Object-Specific Properties

None.


Object-Specific Methods

None.


Object-Specific Events

None.


A base object instructs the browser about the URL path to the current document. This path is then used as the basis for all relative URLs that are used to specify various src and href attributes throughout the document.


HTML Equivalent

<base>


Object Model Reference

 [window.]document.getElementById("elementID") 


Object-Specific Properties

HRef
target

Object-Specific Methods

None.


Object-Specific Events

None.


Provides the URL of a document whose server path is to be used as the base URL for all relative references in the document. This is typically the URL of the current document, but it can be set to another path if it makes sense to your document organization and directory structure.


Example

 document.getElementById("myBase").href = "http://www.megacorp.com"; 


Value

String of complete or relative URL.


Default

Current document pathname.


Provides the name of the window or frame that is to receive content as the result of navigating to a link or any other action on the page that loads a new document. Such names are assigned to frames by the frame element's name attribute; for subwindows, the name is assigned via the second parameter of the window.open( ) method. If you need the services of a target attribute to open a linked page in a blank browser window and you also need the HTML to validate under strict HTML or XHTML DTDs, you can omit the target attribute in the code, but assign a value to the base element's target property by script after the page loads.


Example

 document.getElementById("myBase").target = "_blank"; 


Value

String value of the window or frame name, or any of the following constants (as a string): _parent | _self | _top | _blank. The _parent value targets the frameset to which the current document belongs; the _self value targets the current window; the _top value targets the main browser window, thereby eliminating all frames; and the _blank value creates a new window of default size.


Default

_self


A basefont element advises the browser of some font information to be used as the basis for text rendering of the current page below the basefont element. The basefont element overrides the default font settings in the browser's user preferences settings.

If you intend to alter this element by script, do so only via the properties shown here or W3C DOM-compatible document tree manipulations. Other approaches either risk the display of the document or are not permitted by the browser.


HTML Equivalent

<basefont>


Object Model Reference

 [window.]document.getElementById("elementID") 


Object-Specific Properties

color
face
size

Object-Specific Methods

None.


Object-Specific Events

None.


Sets the font color of all text below the basefont element.


Example

 document.getElementsByTagName("basefont")[0].color = "#c0c0c0"; 


Value

Case-insensitive hexadecimal triplet or plain-language color name as a string. See Appendix A for acceptable plain-language color names.


Default

Browser default.


Indicates a hierarchy of font faces to use for the default font of a section headed by a basefont element. The browser looks for the first font face in the comma-delimited list of font face names until it either finds a match in the client system or runs out of choices, at which point the browser default font face is used. Font face names must match the system font face names exactly.


Example

 document.getElementById("myBaseFont").face = "Bookman, Times Roman, serif"; 


Value

One or more font face names in a comma-delimited list within a string. You may use real font names or the recognized generic faces: serif | sans-serif | cursive | fantasy | monospace.


Default

Browser default.


Provides the size of the font in the 17 browser relative scale.


Example

 document.getElementById("myBaseFont").size = "+1"; 


Value

Either an integer (as a quoted string) or a quoted relative value consisting of a + or - symbol and an integer value.


Default

3


The bdo element is designed to assist in instances when, due to various conversions during text processing, the normal bidirectional algorithms must be explicitly overridden. The primary property of this object is dir, which is shared among all other element objects.


HTML Equivalent

<bdo>


Object-Specific Properties

None.


Object-Specific Methods

None.


Object-Specific Events

None.


A bgsound element defines a sound file that is to play in the background while the user visits the page. Set properties to control the volume and how many times the sound track plays even after the sound file has loaded. A few properties, such as innerHTML and innerText, are exposed in the Windows version, but they don't apply to an element that does not have an end tag.


HTML Equivalent

<bgsound>


Object Model Reference

 [window.]document.getElementById("elementID") 


Object-Specific Properties

balance
loop
src
volume

Object-Specific Methods

None.


Object-Specific Events

None.


Specifies how the audio is divided between the left and right speakers. Once this attribute value is set in the element, its value cannot be changed by script control.


Example

 var currBal = document.getElementsByTagName("bgsound")[0].balance; 


Value

A signed integer between -10,000 and +10,000. A value of 0 is equally balanced on both sides. A negative value means the left side is dominant; a positive value means the right side is dominant.


Default

0


Specifies the number of times the sound plays. Assigning a value of -1 means the sound plays continuously until the page is unloaded.


Example

 document.getElementById("mySound").loop = 3; 


Value

Integer.


Default

1


Provides the URL of the sound file to be played. Change tunes by assigning a new URL to the property. The new tune plays according to the loop property setting.


Example

 document.getElementById("tunes").src = "sounds/blues.aif"; 


Value

Complete or relative URL as a string.


Default

None.


Specifies how loud the background sound plays relative to the maximum sound output level as adjusted by user preferences in the client computer. Maximum volumea setting of zerois only as loud as the user has set the Sound control panel. Attribute adjustments are negative values as low as -10,000 (although most users lose the sound at values much higher than that value).


Example

 var currVolume = document.getElementById("themeSong").volume; 


Value

Integer.


Default

Varies with operating system and sound settings.


See b.


The blockquote object reflects the blockquote element, which is intended to set off a long, block-level quote inside a document.


HTML Equivalent

<blockquote>


Object Model Reference

 [window.]document.getElementById("elementID") 


Object-Specific Properties

cite

Object-Specific Methods

None.


Object-Specific Events

None.


Provides a URL pointing to an online source document from which the quotation is taken. This is not in any way a mechanism for copying or extracting content from another document. No mainstream browser does anything special with this information.


Value

Any valid URL to a document on the World Wide Web, including absolute or relative URLs.


Default

None.


The body object reflects the body element, which is distinct from the document object. The body object refers to just the element and its nested content. There can be only one body element in an HTML page, so both the IE and W3C DOMs provide a shortcut reference to the object, document.body. Event handlers listed here appear as attributes in the <body> tag, but in truth are document-level events (best referenced in property form as document.eventName). While IE for the Mac doesn't share the sets of client and scroll properties with all element objects, those properties are defined for the body object.

In its effort to institute the standards-compatible mode in IE 6 for Windows (see the DOCTYPE element in Chapter 1), Microsoft has rendered useless the old trick of using the body element's clientHeight and clientWidth properties to obtain the equivalent of Netscape's window.innerHeight and window.innerWidth properties. In standards-compatibility mode (where document.compatMode == "CSS1Compat"), you must use the html element's clientHeight and clientWidth properties to find these values. Use these effective reference shortcuts:

 document.body.parentNode.clientHeight document.body.parentNode.clientWidth 

Most properties unique to the body element affect presentation aspects, which are better controlled through CSS rules applied to the body selector.


HTML Equivalent

<body>


Object Model Reference

 [window.]document.body 


Object-Specific Properties

aLink
background
bgColor
bgProperties
bottomMargin
leftMargin
link
noWrap
rightMargin
scroll
text
topMargin
vLink

Object-Specific Methods

createControlRange( )
createTextRange( )

Object-Specific Methods

Event

IE (Win)

Mozilla

Safari

Opera

W3C DOM

afterprint

·

beforeprint

·

beforeunload

·

load

·

·

·

·

·

select

·

·

unload

·

·

·

·

·



Indicates a color of a hypertext link as it is being clicked. The color is applied to the link text or border around an image or object embedded within an a element. See also link and vLink properties for unvisited and visited link colors. The deprecated but backward-compatible version of this property is the alinkColor property of the document object. Largely superceded in modern practice by the :active pseudo-class.


Example

 document.body.aLink = "green"; 


Value

A hexadecimal triplet or plain-language color name. See Appendix A for acceptable plain-language color names.


Default

#0000FF


Provides the URL of the background image for the entire document. If you set a bgColor to the element as well, the color appears if the image fails to load; otherwise, the image overlays the color.


Example

 document.body.background = "images/watermark.jpg"; 


Value

Complete or relative URL to the background image file.


Default

None.


Provides the background color of the element. Even if the bgcolor attribute or bgColor property is set with a plain-language color name, the returned value is always a hexadecimal triplet.


Example

 document.body.bgColor = "yellow"; 


Value

A hexadecimal triplet or plain-language color name. See Appendix A for acceptable plain-language color names.


Default

Varies with browser and operating system.


Specifies whether the background image remains in a fixed position or scrolls as a user scrolls the page. When the background image is set to remain in a fixed position, scrolled content flows past the background image very much like film credits roll past a background image on the screen.


Example

 document.body.bgProperties = "fixed"; 


Value

An empty string (indicating the normal scrolling behavior) or the case-insensitive constant string fixed.


Default

Empty string.


Indicates the amount of blank space between the very end of content and the bottom of a scrollable page. The setting has no visual effect if the length of the content or size of the window does not cause the window to scroll. The default value is for the end of content to be flush with the end of the document, but in the Macintosh version of Internet Explorer, there is about a 10-pixel margin visible even when the property is set to zero. Larger sizes are reflected properly. This property offers somewhat of a shortcut or alternative to setting the marginBottom style sheet property for the body element object.


Example

 document.body.bottomMargin = 20; 


Value

An integer value (zero or greater) of the number of pixels of clear space at the bottom of the document.


Default

0


Provides the width in pixels of the left margin of the body element in the browser window or frame. By default, the browser inserts a small margin to keep content from abutting the left edge of the window. Setting the property to an empty string is the same as setting it to zero.


Example

 document.body.leftMargin = 16; 


Value

Integer of pixel count.


Default

10 (Windows); 8 (Macintosh).


Indicates the color of a hypertext link that has not been visited (that is, the URL of the link is not in the browser's cache). This is one of three states for a link: unvisited, active, and visited. The color is applied to the link text or border around an image or object embedded within an a element. This property has the same effect as setting the document object's linkColor property. Largely superceded in modern practice by the :link pseudo-class.


Example

 document.body.link = "#00FF00"; 


Value

A hexadecimal triplet or plain-language color name. See Appendix A for acceptable plain-language color names.


Default

#0000FF


Specifies whether the browser should render the body content as wide as necessary to display a line of nonbreaking text on one line. Abuse of this attribute can force the user into a great deal of inconvenient horizontal scrolling of the page to view all of the content.


Example

 document.body.noWrap = "true"; 


Value

Boolean value: true | false.


Default

false


Provides the width in pixels of the right margin of the body element in the browser window or frame. By default, the browser inserts a small margin to keep content from abutting the right edge of the window (except on the Macintosh). Setting the property to an empty string is the same as setting it to zero.


Example

 document.body.leftMargin = 16; 


Value

Integer of pixel count.


Default

10 (Windows); 0 (Macintosh).


Specifies whether the window (or frame) displays scrollbars when the content exceeds the window size. If your document specifies a standards-compatible DOCTYPE definition (see Chapter 1), the scroll property does not respond to changes for the body element. Nor does the html element object gain this property, as Microsoft's developer documentation purports.


Example

 document.body.scroll = "no"; 


Value

Not exactly a Boolean value. Requires one of the following string values: yes | no | auto.


Default

yes


Indicates the color of text for the entire document body. Equivalent to the foreground color, and generally superceded in practice by the CSS color property..


Example

 document.body.text = "darkred"; 


Value

A hexadecimal triplet or plain-language color name. See Appendix A for acceptable plain-language color names.


Default

Browser default (user customizable).


Provides the width in pixels of the top margin of the body element in the browser window or frame. By default, the browser inserts a small margin to keep content from abutting the top edge of the window. Setting the property to an empty string is the same as setting it to zero.


Example

 document.body.topMargin = 16; 


Value

Integer of pixel count.


Default

15 (Windows); 8 (Macintosh).


Indicates the color of a hypertext link that has been visited recently. The color is applied to the link text or border around an image or object embedded within an a element. See also link and aLink properties for unvisited and clicked link colors. The deprecated but backward-compatible version of this property is the vlinkColor property of the document object. Largely superceded in modern practice by the :vlink pseudo-class.


Example

 document.body.vLink = "gold"; 


Value

A hexadecimal triplet or plain-language color name. See Appendix A for acceptable plain-language color names.


Default

Varies with browser and operating system.


When content of an element is in user editing mode, this method creates a controlRange collectiona collection of all contiguous elements currently selected.


Returned Value

controlRange collection.


Parameters

None.


Creates a TexTRange object from the rendered text content of the current element. See the Textrange object for details.


Returned Value

Textrange object.


Parameters

None.


The br object reflects the br element.


HTML Equivalent

<br>


Object Model Reference

 [window.]document.getElementById("elementID") 


Object-Specific Properties

clear

Object-Specific Methods

None.


Object-Specific Events

None.


Tells the browser how to treat the next line of text following a br element if the current text is wrapping around a floating image or other object. The value you use depends on the side of the page to which one or more inline images are pegged and how you want the next line of text to be placed in relation to those images.


Example

 document.getElementById("specialBreak").clear = "all"; 


Value

Case-insensitive string of any of the following constants: all | left | none | right.


Default

none


The button object reflects the button element. See the discussion of the button element in Chapter 1 to see how it differs from the input element of type button. Opera 9 implements numerous properties and methods for its Web Forms 2.0 support.


HTML Equivalent

<button>


Object Model Reference

 [window.]document.getElementById("elementID") 


Object-Specific Properties

action
autofocus
dataFld
dataFormatAs
dataSrc
enctype
form
forms
htmlTemplate
labels
method
name
replace
status
target
type
validationMessage
validity
value
willValidate

Object-Specific Methods

checkValidity( )
createTextRange( )
dispatchChange( )
dispatchFormChange( )
setCustomValidity( )

Object-Specific Event Properties

None.


Web Forms 2.0 extension that allows a submission of the enclosing form to a URI different from the regular form when the button element is clicked (and its type is set to submit).


Example

 document.getElementById("myButton").action = "redirect.php"; 


Value

URI string.


Default

None.


Web Forms 2.0 extension that brings focus to the element after the page loads. Should be assigned to only one form control element per page. The button's type must be set to submit.


Example

 document.getElementById("myButton").autofocus = true; 


Value

Boolean: true | false.


Default

false


Used with IE data binding to associate a remote data source column name to a button object's label. A datasrc attribute must also be set for the element. Setting both the dataFld and dataSrc properties to empty strings breaks the binding between element and data source.


Example

 document.getElementById("myButton").dataFld = "linkURL"; 


Value

Case-sensitive identifier of the data source column.


Default

None.


Used with IE data binding, this property advises the browser whether the source material arriving from the data source is to be treated as plain text or as tagged HTML.


Example

 document.getElementById("myButton").dataFormatAs = "html"; 


Value

String constant values: text | html.


Default

text


Used with IE data binding to specify the ID of the page's object element that loads the data source object for remote data access. Content from the data source is specified via the datafld attribute in the button element. Setting both the dataFld and dataSrc properties to empty strings breaks the binding between element and data source.


Example

 document.getElementById("myButton").dataSrc = "DBSRC3"; 


Value

Case-sensitive identifier of the object element.


Default

None.


Web Forms 2.0 extension that allows (in concert with other properties, such as action) a submission of the enclosing form to a URI and enclosure MIME type different from the regular form when the button element is clicked (and its type is set to submit).


Example

 document.getElementById("myButton").enctype = "text/plain"; 


Value

MIMEtype string.


Default

None.


Returns a reference to the form element that contains the current element (if any). In the Web Forms 2.0 environment, you can reassign a button to be associated with a different form via the setAttribute( ) method.


Example

 var theForm = event.srcElement.form; 


Value

Object reference.


Default

None.


Web Forms 2.0 extension that returns an array (NodeList) of references to form objects with which the current button element is associated.


Example

 var formList = document.getElementById("myButton").forms; 


Value

Array.


Default

One-item array with a reference to any enclosing form element.


Web Forms 2.0 extension that returns a reference to the element object (a RepetitionElement object) whose ID matches that of the current button element's template attribute (which must be set for this property to be anything other than null).


Example

 var repeatTemplate = document.getElementById("myButton").htmlTemplate; 


Value

Element object reference.


Default

null


Web Forms 2.0 extension that returns an array (HTMLCollection) of references to label element objects associated with the current button element.


Example

 var allLabels = document.getElementById("myButton").labels; 


Value

Array of label element object references.


Default

Empty array.


Web Forms 2.0 extension (when used with other extensions, such as the action attribute) that allows a submission for the enclosing form to a URI different and even method from the regular form when the button element is clicked (and its type is set to submit).


Example

 document.getElementById("myButton").method = "get"; 


Value

String of method type.


Default

get


This is the identifier associated with the element when used as a form control. The value of this property is submitted as one-half of the name/value pair when the form is submitted to the server. Names are hidden from user view, since control labels are assigned via other means, depending on the control type. Form control names may also be used by script references to the objects.


Example

 document.forms[0].compName.name = "company"; 


Value

Case-sensitive identifier that follows the rules of identifier naming: it may contain no whitespace, cannot begin with a numeral, and should avoid punctuation except for the underscore character.


Default

None.


Web Forms 2.0 extension that associates instructions to a submission form control with how to process the data returned from the server after the form is submitted. The choice is whether the response replaces the original document in the browser (the default) or the browser should apply returned values to the form, rather than retrieve initial form data (if a URL is assigned to the data attribute of the form element).


Example

 document.getElementById("myButton").replace = "values"; 


Value

One of two constant values: document | values.


Default

document


Unlike the status property of other types of form controls, the property has no visual or functional impact on the button.


Value

Boolean value: TRue | false; or null.


Default

null


Web Forms 2.0 extension that allows (in concert with other attributes, such as action) the page returned from a submission of the enclosing form to appear in a window or frame different from the destination of the page returned from regular form when the button element is clicked (and its type is set to submit).


Example

 document.getElementById("myButton").target = "_blank"; 


Value

Frame or window name as a string.


Default

None (signifying the current window or frame).


Specifies whether the button element is specified as a button, reset, or submit style button. Web Forms 2.0 also adds types that facilitate control of repetition blocks.


Example

 if (evt.target.type == "button") {     // process button element } 


Value

For all supporting browsers, one of the three constants (as a string): button | reset | submit. For browsers supporting Web Forms 2.0, additional string constants: add | move-down | move-up | remove.


Default

button


Web Forms 2.0 extension that returns a browser-generated message if the form control fails to validate according to its specifications. This property is meant more for text-oriented form controls, where an empty string means that the entry validates properly. For a button element, this property is always an empty string.


Value

Empty string.


Default

Empty string.


Web Forms 2.0 extension that returns a ValidityState object. For a button element, all members of the returned object are false, except for the valid property, which is TRue. See the ValidityState object.


Value

ValidityState object.


Default

ValidityState object.


Provides the current value associated with the form control that is submitted with the name/value pair for the element. Unlike the button-type input element object, this value property's value is unseen by the user; the label is set by the element's content (innerHTML property or nested node).


Example

 var val = document.getElementById("myButton").value; 


Value

String.


Default

None.


Web Forms 2.0 extension that returns a Boolean value indicating whether the form control element meets criteria for validating under the Web Forms 2.0 mechanism. A button element is not one of the correct types, and therefore always returns false.


Value

Boolean value: true | false.


Default

false


Web Forms 2.0 method that returns a Boolean value representing whether the form control element meets its validity criteriaultimately, whether the validity.valid property is TRue. Because that value is always true for a button element, the checkValidity( ) method always returns true.


Returned Value

Boolean value: TRue | false.


Parameters

None.


Creates a Textrange object containing the button's label text. See the Textrange object.


Returned Value

Textrange object.


Parameters

None.


Web Forms 2.0 methods that fire the change and formchange events on the current element. You could, for example "convert" a click event to a change or formchange event by having the onclick event handler invoke either method.


Returned Value

None.


Parameters

None.


setCustomValidity([ errorString])

Web Forms 2.0 method that sets the customError Boolean value of the validity property (itself a ValidityState object). This method has no effect on button elements and throws a NOT_SUPPORTED_ERR error.


Returned Value

None.


Parameters


errorString

If null or an empty string, the parameter resets the validity object's customError property, signifying the form control is not valid. An error string is to be remembered by the browser (during the current session) so that it displays the string upon subsequent validation failures.


The canvas object reflects the canvas element (as defined in the Web Applications 1.0 specification of the WebHypertext Application Technology Working Group (WHATWG). This object is simply the DOM element within the document tree. To perform graphic operations inside the canvas element space, first obtain the canvas rendering context object (via getContext( )), and then invoke methods of that object (see the CanvasRenderingContext2D object).


HTML Equivalent

<canvas>


Object Model Reference

 [window.]document.getElementById("elementID") 


Object-Specific Properties

height
width

Object-Specific Methods

getContext( )
toDataURL( )

Object-Specific Events

None.


Determine pixel dimensions of the graphical drawing space of the element. You can change the size of the element by script even if the dimensions are set by element attributes.


Example

 document.getElementById("myCanvas").width = 450; 


Value

Integer pixel values.


Default

0


getContext(" contextID")

Returns a reference to the drawing space (called a context) in the element. See the CanvasRenderingContext2D object for the methods you can invoke to specify and draw lines and shapes in to appear in the canvas element.


Returned Value

Canvas context object (CanvasRenderingContext2D).


Parameters


contextID

A string that identifies which drawing context to reference from the canvas element. Early generation implementations have only a two-dimensional context, named 2D.


toDataURL([" MIMEType"])

Returns a string in the form of a URI (starting with a data: protocol) containing the binary representation of the image rendered in the element. The default MIME type is image/png, but you can specify others, as supported by the browser (e.g., Mozilla also supports image/jpeg).


Returned Value

URI String.


Parameters


MIMEType

A string denoting the MIME type for the data to be returned by the method.


This object is returned by the canvas element object's getContext( ) method, and provides the drawing mechanism for the space within the rendered element. Properties and methods of this object control the drawing operations that only scripts can perform inside a canvas element. Eventually there will likely be other types of contexts that allow drawing in, say, three-dimensional space. This particular context is limited to two-dimensional drawing along x and y axes. Safari 2 internally calls this object Context2D.

As a simple example of a typical coding sequence, the following function draws a smiley face using arcs of two different line thicknesses:

 function draw( ) {     var canvas = document.getElementById("mycanvas");     var ctxt = canvas.getContext("2d");     ctxt.fillStyle = "rgb(255,225,0)";     ctxt.beginPath( );     ctxt.lineWidth = 2;     ctxt.arc(75,75,50,0,Math.PI*2,true);     ctxt.fill( );     ctxt.moveTo(65,65);     ctxt.arc(60,65,5,0,Math.PI*2,true);     ctxt.moveTo(95,65);     ctxt.arc(90,65,5,0,Math.PI*2,true);     ctxt.stroke( ); // render arcs thus far     ctxt.beginPath( );     ctxt.moveTo(110,75);     ctxt.lineWidth = 4;     ctxt.arc(75,75,35,0,Math.PI,false);     ctxt.stroke( ); // render thicker arc } 

The range of properties and methods for drawing images and animations in a canvas context is large. Effective usage of some of the methods benefit from knowledge of color gradients, geometry, and even illustration techniquesall subjects beyond the scope of this reference. You can get a good introduction to how to apply the properties and methods discussed here at http://developer.mozilla.org/en/docs/Canvas_tutorial.


Object Model Reference

 [window.]document.getElementById("canvasElementID").getContext("2D") 


Object-Specific Properties

canvas
fillStyle
globalAlpha
globalCompositeOperation
lineCap
lineJoin
lineWidth
miterLimit
shadowBlur
shadowColor
shadowOffsetX
shadowOffsetY
strokeStyle

Object-Specific Methods

arc( )
arcTo( )
beginPath( )
bezierCurveTo( )
clearRect( )
clip( )
closePath( )
createLinearGradient( )
createPattern( )
createRadialGradient( )
drawImage( )
fill( )
fillRect( )
lineTo( )
moveTo( )
quadraticCurveTo( )
rect( )
restore( )
rotate( )
save( )
scale( )
stroke( )
strokeRect( )
translate( )

Object-Specific Event Properties

None.


A reference to the canvas element from which the current context was derived. This is a convenience property that lets a reusable script refer back to the original element, perhaps to adjust the element's height or width properties.


Example

 myContext.canvas.width = 450; 


Value

HTML element reference.


Default

Containing canvas element reference.


Specifies the color, gradient, or pattern to be used to fill a shape.


Example

 myContext.fillStyle = "rgb(255, 0, 0)"; 


Value

For a color, any valid CSS3 color value as a string, including color names, numeric RGB, and numeric RGBA (alpha for transparency) values. For gradient or pattern, any object created by the gradient or pattern generation methods of the canvas context object.


Default

rgb(0, 0, 0) (black).


Specifies the transparency level for all shapes or images prior to their rendering.


Example

 myContext.globalAlpha = 0.5; 


Value

Floating point number from 0 to 1.0, with 0 being completely transparent and 1.0 being completely opaque.


Default

1.0 (opaque).


Specifies the type of masking (if any) between a new shape (to be rendered after setting the property) and existing content within the canvas context.


Example

 myContext.globalCompositeOperation = "destination-in"; 


Value

One of 12 string constants: copy | darker | destination-atop | destination-in | destination-out | destination-over | lighter | source-atop | source-in | source-out | source-over


Default

source-over (new shapes are drawn atop existing content with no clipping).


Specifies the way endpoints of lines are to be rendered. By default, a line ends with a square edge at the endpoint coordinates specified by a method such as lineTo( ). But lines can also be drawn so that the ends are rendered with filled semicircles (whose radius is one-half the line width) or a rectangle (whose height is one-half the line width). These latter two styles cause the line cap to render slightly beyond the endpoint coordinates for the extra caps.


Example

 myContext.lineCap = "round"; 


Value

One of three string constants: butt | round | square.


Default

butt


Specifies the way to render the meeting points of two lines. By default, two lines meet in a miter joint such that the outer edges of the lines meet at one point. But line can also meet with a rounded or beveled joint.


Example

 myContext.lineJoin = "bevel"; 


Value

One of three string constants: bevel | miter | round.


Default

miter


Specifies the thickness of a line to be drawn for a shape. The unit of measure is canvas coordinate space units (typically pixels). Note that when a method draws a line according to coordinates, the coordinates are applied to the centerline of the line, which may cause a wide line to position, say, a rectangle drawn with the fillRect( ) method to be positioned slightly differently than you expect.


Example

 myContext.lineWidth = 5; 


Value

Positive floating-point number.


Default

1.0


Specifies the ratio of the miter length (the distance from the inside joint to the outside joint).


Example

 myContext.miterLimit = 17.5; 


Value

Positive floating point number.


Default

10.0


Specifies the number of coordinate space units adjacent to a shape that is to be covered by a shadow.


Example

 myContext.shadowBlur = 3; 


Value

Positive floating point number.


Default

1.0


Specifies the color to be used for a shape's shadow.


Example

 myContext.shadowColor = "rgb(90, 90, 90)"; 


Value

CSS3-compatible color specification as a string.


Default

black


Specify the horizontal (x) and vertical (y) distances in coordinate space units of the shadow in relation to the shapes about to be drawn. Positive values are up and to the right; negative values are down and to the left.


Example

 myContext.shadowOffsetX = 5; 


Value

Positive or negative floating point number.


Default

0


Specifies the color, gradient, or pattern to be used to draw lines or the outlines of shapes.


Example

 myContext.strokeStyle = "rgb(255, 0, 0)"; 


Value

For a color, any valid CSS3 color value as a string, including color names, numeric rgb, and numeric rgba (alpha for transparency) values. For gradient or pattern, any object created by the gradient or pattern generation methods of the canvas context object.


Default

rgb(0, 0, 0) (black).


arc( x, y, radius, startAngle, endAngle, counterClockwiseFlag)

Specifies an arc to be drawn in the canvas context from the current point in the path. The arc is drawn along a path defined by two endpoints measured as angles (in radians) around the x,y origin. As with all path-related methods, this method belongs between a beginPath( ) and a stroke( ) method call.


Returned Value

None.


Parameters


x, y

Horizontal (x) and vertical (y) coordinates (in canvas coordinate units as number values) of the center point of the circle defined by the arc.


radius

Length, in canvas coordinate units as a number value, of the radius of the circle of which the arc is a part.


startAngle, endAngle

Points along the circle where the arc begins and ends, specified in radians as number values.


counterClockwiseFlag

Boolean value indicating the direction of the arc from start to end: true for counter-clockwise; false for clockwise.


arc( x1, y1, x2, y2, radius)

Specifies an arc to be drawn in the canvas context from the current point in the path. The arc is drawn along a path that has one point tangent to the line from the current position to point (x1, y1), one point tangent to the line from from the point (x1, y1) to the point (x2, y2), and that has radius radius.


Returned Value

None.


Parameters


x1, y1

Horizontal (x) and vertical (y) coordinates (in canvas coordinate units as number values) of the start point of the arc.


x2, y2

Horizontal (x) and vertical (y) coordinates (in canvas coordinate units as number values) of the endpoint of the arc.


radius

Length, in canvas coordinate units as a number value, of the radius of the circle of which the arc is a part.


Resets the context's path list to empty and moves the pointer to 0, 0 to get ready to accept new path specifications for another shape. This method is automatically invoked when the context is first created.


Returned Value

None.


Parameters

None.


bezierCurveTo( cp1x, cp1y, cp2x, cp2y, x, y)

Specifies a cubic Bézier curve to be drawn in the canvas context from the current point in the path to an endpoint specified by x and y. The precise shape of the curve is guided by two control point coordinates, one for the start point (cp1x, cp1y), the other for the endpoint (cp2x, cp2y).


Returned Value

None.


Parameters


cp1x, cp1y

Horizontal (x) and vertical (y) coordinates (in canvas coordinate units as number values) of the control point that influences the shape of the curve at the start point.


cp2x, cp2y

Horizontal (x) and vertical (y) coordinates (in canvas coordinate units as number values) of the control point that influences the shape of the curve at the endpoint.


x, y

Horizontal (x) and vertical (y) coordinates (in canvas coordinate units as number values) of the endpoint of the curve.


clearRect( x, y, width, height)

Erases the canvas context for the region specified by parameters. You can selectively erase multiple rectangular regions, or clear the entire canvas. A generic script can obtain the size of the canvas via the canvas.height and canvas.width properties.


Returned Value

None.


Parameters


x, y

Horizontal (x) and vertical (y) coordinates (in canvas coordinate units as number values) of the top-left corner of the rectangle to clear.


width, height

Width and height (in canvas coordinate units as number values) of the rectangle to be cleared. Neither value can be zero.


After establishing a path through other methods, invoke clip( ) to create a clipping region for the canvas context. Thereafter, new shapes will appear only within the clipping region. Clipping regions can be any shape you create using the various path methods.


Returned Value

None.


Parameters

None.


Draws a straight line between the current path point and the first point of the path.


Returned Value

None.


Parameters

None.


createLinearGradient( x0, y0, x1, y1)

Creates and returns a CanvasGradient object (assignable to a context's fillStyle and strokeStyle properties) for a straight line gradient. A linear gradient has a start and endpoint within the context space, specified as parameters to the method. Once you have the gradient object, you can then assign colors to various points along the length of the gradient via the addColorStop( ) method of a gradient object. For example, the following code sequence creates a linear gradient that transitions from white to red along a diagonal starting at the top-left corner of the context, extending to 200 pixels down and across:

 var ctxt = document.getElementById("mycanvas").getContext("2d"); var gradient = ctxt.createLinearGradient(0, 0, 200, 200); gradient.addColorStop(0, "white"); gradient.addColorStop(1, "red"); ctxt.fillStyle = gradient; ctxt.fillRect(0, 0, 200, 200); 

The first parameter of addColorStop( ) is a floating-point number between 0 (the start point of the gradient) and 1 (the endpoint of the gradient). You can specify multiple color stops along the way.


Returned Value

CanvasGradient object.


Parameters


x0, y0

Horizontal (x) and vertical (y) coordinates (in canvas coordinate units as number values) of the start point of the gradient.


x1, y1

Horizontal (x) and vertical (y) coordinates (in canvas coordinate units as number values) of the endpoint of the gradient.


createPattern( imageObjectRef, " repeatStyle")

Creates and returns a CanvasPattern object (assignable to a context's fillStyle and strokeStyle properties) whose original image becomes either a shape fill pattern or stroke pattern. The image object to be passed as a first parameter can be created through familiar DOM techniques, as follows:

 var img = new Image( ); img.src = "myImage.png"; var pattern = ctxt.createPattern(img, "repeat"); 

Then assign the resulting object to the context's fillStyle or strokeStyle properties.


Returned Value

CanvasPattern object.


Parameters


imageObjectRef

Reference to an image object whose src property points to an image URL. Some browsers may also support assigning an image object that has been returned by the canvas element's dataToURL( ) method.


repeatStyle

One of four constant strings: no-repeat | repeat | repeat-x | repeat-y.


createRadialGradient( x0, y0, r0, x1, y1, r1)

Creates and returns a CanvasGradient object (assignable to a context's fillStyle and strokeStyle properties) for a gradient that extends outward from a center circle or point to a distance specified by radius values measured from the center point. A radial gradient has a start and endpoint within the context space, specified as parameters to the method. Once you have the gradient object, you can then assign colors to various points along the length of the gradient via the addColorStop( ) method of a gradient object.


Returned Value

CanvasGradient object.


Parameters


x0, y0

Horizontal (x) and vertical (y) coordinates (in canvas coordinate units as number values) of the start point of the gradient.


x1, y1

Horizontal (x) and vertical (y) coordinates (in canvas coordinate units as number values) of the endpoint of the gradient.


r0, r1

Radius distances (in canvas coordinate units as number values) from the center point to the location of the start point (r0) and the endpoint (r1).


drawImage( imageOrCanvas, dx, dy)


drawImage( imageOrCanvas, dx, dy, dw, dh)


drawImage( imageOrCanvas, sx, sy, sw, sh, dx, dy, dw, dh)

Copies an imported (or generated) image into the canvas context at a designated location within the context. The method has three different versions, depending on the number of parameters you specify.


Returned Value

None.


Parameters


dx, dy

Horizontal (x) and vertical (y) coordinates (in canvas coordinate units as number values) of the top-left corner of the image within the canvas context (referred to as the destination).


dw, dh

Width and height (in canvas coordinate units as number values) of the image.


sx, sy

Horizontal (x) and vertical (y) coordinates (in canvas coordinate units as number values) of the top-left corner of the image scaled within the original image space.


dw, dh

Width and height (in canvas coordinate units as number values) of the scaled image.


Fills spaces defined by the current path, using the color, gradient, or pattern assigned to the fillStyle property.


Returned Value

None.


Parameters

None.


fillRect( x, y, width, height)

Paints the region specified by parameters with the color, gradient, or pattern assigned to the fillStyle property.


Returned Value

None.


Parameters


x, y

Horizontal (x) and vertical (y) coordinates (in canvas coordinate units as number values) of the top-left corner of the rectangle to paint.


width, height

Width and height (in canvas coordinate units as number values) of the rectangle to be painted. Neither value can be zero.


lineTo( x, y)

Adds a line to the path from the current path point to the coordinates specified as parameters, after which the current point is the passed coordinates.


Returned Value

None.


Parameters


x, y

Horizontal (x) and vertical (y) coordinates (in canvas coordinate units as number values) of the endpoint of the line.


moveTo( x, y)

Moves the current point to the specified coordinate position, and also begins a subpath using the point as the starting position.


Returned Value

None.


Parameters


x, y

Horizontal (x) and vertical (y) coordinates (in canvas coordinate units as number values) of the new position.


quadraticCurveTo( cp1x, cp1y, x, y)

Specifies a quadratic Bézier curve to be drawn in the canvas context from the current point in the path to an endpoint specified by x and y. The precise shape of the curve is guided by control point coordinates cp1x and cp1y.


Returned Value

None.


Parameters


cp1x, cp1y

Horizontal (x) and vertical (y) coordinates (in canvas coordinate units as number values) of the control point that influences the shape of the curve relative to both the start and endpoints of the curve.


x, y

Horizontal (x) and vertical (y) coordinates (in canvas coordinate units as number values) of the endpoint of the curve.


rect( x, y, width, height)

Creates a separate subpath that defines a rectangle at the specified position and dimensions. The method then sets the current point to 0,0.


Returned Value

None.


Parameters


x, y

Horizontal (x) and vertical (y) coordinates (in canvas coordinate units as number values) of the top-left corner of the rectangle path.


width, height

Width and height (in canvas coordinate units as number values) of the rectangle path.


Pops the topmost drawing from the internal drawing state stack. Use save( ) to push onto the stack.


Returned Value

None.


Parameters

None.


rotate( angle)

Has the effect of rotating the canvas context (called a transformation matrix), and should be invoked before drawing in the transformed state.


Returned Value

None.


Parameters


angle

The clockwise rotation angle in radians.


Pushes the current state of the drawing onto an internal drawing state stack. Use restore( ) to pop from the stack.


Returned Value

None.


Parameters

None.


scale( x, y)

Adjusts the scale of the canvas context by multiples specified for the horizontal and vertical axes.


Returned Value

None.


Parameters


x, y

Floating-point numbers representing the multiplication factor for scaling the context in the horizontal (x) and vertical (y) axes.


Draws the current path in the canvas context, using the settings of the lineJoin, lineWidth, miterLimit, and strokeStyle properties.


Returned Value

None.


Parameters

None.


fillRect( x, y, width, height)

Draws a rectangular outline in the parameter-driven location and dimensions using the values assigned to the lineJoin, lineWidth, miterLimit, and strokeStyle properties.


Returned Value

None.


Parameters


x, y

Horizontal (x) and vertical (y) coordinates (in canvas coordinate units as number values) of the top-left corner of the rectangle to paint.


width, height

Width and height (in canvas coordinate units as number values) of the rectangle to be painted.


translate( x, y)

Moves the origin point of the canvas context to the coordinates specified as parameters.


Returned Value

None.


Parameters


x, y

Floating-point numbers representing the offsets along the horizontal (x) and vertical (y) axes that define the new origin point of the canvas context.


The caption object reflects the caption element, which must always be nested inside a table element. IE/Mac implements the client and scroll property sets for this object.


HTML Equivalent

<caption>


Object Model Reference

 [window.]document.getElementById("elementID") 


Object-Specific Properties

align
vAlign

Object-Specific Methods

None.


Object-Specific Events

None.


Determines the position of the caption in the table. See the align attribute of the caption element in Chapter 1 for details on the interaction between the align and vAlign attributes and properties in IE for Windows. The W3C DOM uses the align property predominantly for placing the caption above or below the table.


Example

 document.getElementById("myCaption").align = "bottom"; 


Value

Any of the following constants (as a string): bottom | left | right | top.


Default

top


Specifies whether the table caption appears above or below the table.


Example

 document.getElementById("tabCaption").vAlign = "bottom" 


Value

Case-insensitive constant (as a string): bottom | top.


Default

top


A collection of all TD elements contained within a single TR element. Collection members are sorted in source code order.


Object Model Reference

 document.getElementById("rowID").cells 


Object-Specific Properties

length

Object-Specific Methods

item( )
namedItem( )
tags( )
urns( )

Object-Specific Events

None.


Returns the number of elements in the collection.


Example

 var howMany = document.getElementById("myTable").rows[0].cells.length; 


Value

Integer.


item( index[, subindex]) item( index)

Returns a single td object or collection of td objects corresponding to the element matching the index value (or, optionally in IE, the index and subindex values).


Returned Value

One TD object or collection (array) of TD objects. If there are no matches to the parameters, the returned value is null.


Parameters


index

When the parameter is a zero-based integer, the returned value is a single element corresponding to the specified item in source code order (nested within the current element); when the parameter is a string (IE only), the returned value is a collection of elements whose id properties match that string.


subindex

In IE only, if you specify a string value for the first parameter, you can use the second parameter to specify a zero-based index that retrieves the specified element from the collection whose id properties match the first parameter's string value.


namedItem(" ID")

Returns a single td object or collection of td objects corresponding to the element matching the parameter string value.


Returned Value

One TD object or collection (array) of TD objects. If there are no matches to the parameters, the returned value is null.


Parameters


ID

The string that contains the same value as the desired element's id attribute.


tags(" tagName")

Returns a collection of objects (among all objects nested within the current collection) whose tags match the tagName parameter. Implemented in all IE collections (see the all.tags( ) method), but redundant for collections of the same element type.


urns( URN)

See the all.urns( ) method.


The center object reflects the center element. The W3C DOM does not support the deprecated HTML 4 center element. For backward compatibility, Mozilla treats the element as earlier browsers do, but the scriptable element is treated as a span object, whose default text-align style is set to center.


HTML Equivalent

<center>


Object Model Reference

 [window.]document.getElementById("elementID") 


Object-Specific Properties

None.


Object-Specific Methods

None.


Object-Specific Events

None.


See input.


See Text.


The object returned by the childNodes property of several W3C DOM objects is a collection (array) of references to Node objects that are immediate children of the current node object. In the W3C DOM structure, the abstract representation of this array is called the NodeList object, which shares some properties and methods of the IE childNodes object. Since both objects refer to the same parts of a document tree, they are treated here together. Collection members are sorted in source code order.


Object Model Reference

 nodeReference.childNodes 


Object-Specific Properties

length

Object-Specific Methods

item( )
urns( )

Object-Specific Events

None.


Returns the number of nodes in the collection.


Example

 var howMany = document.getElementById("myTable").attributes.length; 


Value

Integer.


item( index)

Returns a single Node object corresponding to the element matching the index value.


Returned Value

Reference to one Node object. If there is no match to the index value, the returned value is null. Unlike some other collections in IE, a string index value is not allowed for the childNodes object.


Parameters


index

A zero-based integer corresponding to the specified item in source code order (nested within the current node).


urns( URN)

See the all.urns( ) method.


A collection of all elements contained in the current element. Note that unlike the childNodes collection, children counts only elements and not text nodes. Collection members are sorted in source code order. Internet Explorer lets you use array notation or parentheses to access a single element in the collection.


Object Model Reference

 document.getElementById("elementID").children(i) document.getElementById("elementID").children[i] 


Object-Specific Properties

length

Object-Specific Methods

item( )
namedItem( )
tags( )
urns( )

Object-Specific Events

None.


Returns the number of elements in the collection.


Example

 var howMany = document.body.children.length; 


Value

Integer.


item( index)

Returns an element object corresponding to the element matching the index value in source code order.


Returned Value

Reference to an element object. If there is no matches to the parameter, the returned value is null.


Parameters


index

A zero-based integer corresponding to the specified item in source code order (nested within the current element).


namedItem( IDOrName)

Returns an element object or collection of objects corresponding to the element matching the parameter string value.


Returned Value

One element object or collection (array) of element objects. If there are no matches to the parameters, the returned value is null.


Parameters


IDOrName

The string that contains the same value as the desired element's id or name attribute.


tags( tagName)

Returns a collection of objects (among all objects nested within the current collection) whose tags match the tagName parameter. Implemented in all IE collections (see the all.tags( ) method), but redundant for collections of the same element type.


urns( URN)

See the all.urns( ) method.


See abbr.


See navigator.


The clipboardData object (accessible as a property of a window or frame object) allows script access to the Windows system clipboard as a temporary container that scripts in IE 5 and later for Windows can use to transfer text data, particularly during script-controlled operations that simulate cutting, copying, and pasting, or that control dragging. Your script controls what data is stored in the clipboardData object, such as just the text of an element, an element's entire HTML, or the URL of an image. For example, a page for children could display simple icon images of several different kinds of animals. If the user starts dragging the dog icon, the script initiated by the img element's onDragStart event handler stores a custom attribute value of that element (perhaps the URL of a pretty dog photo) into the clipboardData object. When the user drops the icon into the designated area, the onDrop event handler's function reads the clipboardData object's data and loads the photo image into position on the page.

Data stored in this object survives navigation to other pages within the same domain and protocol. Therefore, you can use it to pass text data (including arrays that have been converted to strings by the Array.join( ) method) from one page to another without using cookies or location.search strings.

For more information on transferring data via this object and the event.dataTransfer object, visit http://msdn.microsoft.com/workshop/author/datatransfer/overview.asp.


HTML Equivalent

None.


Object Model Reference

 [window.]clipboardData 


Object-Specific Properties

dropEffect
effectAllowed

Object-Specific Methods

clearData( )
geTData( )
setData( )

Object-Specific Events

None.


These two properties belong to the clipboardData object by inheritance from the dataTransfer object, to which they genuinely apply. Ignore these properties for the clipboardData object.


clearData([ dataFormat])

Removes data from the clipboardData object.


Returned Value

None.


Parameters


dataFormat

An optional string specifying a single format for the data to be removed. Earlier plans to allow multiple data types appear to have fallen through. As of IE 6, the only reliable format is Text. Omitting the parameter removes all data of all types.


getData( dataFormat)

Returns a copy of data from the clipboardData object. The clipboardData contents remain intact for subsequent reading in other script statements.


Returned Value

String.


Parameters


dataFormat

A string specifying the format for the data to be read. Earlier plans to allow multiple data types appear to have fallen through. As of IE 6, the only reliable format is Text.


setData( dataFormat, stringData)

Stores string data in the clipboardData object. Returns Boolean TRue if the assignment is successful


Returned Value

Boolean value: true | false.


Parameters


dataFormat

A string specifying the format for the data to be read. Earlier plans to allow multiple data types appear to have fallen through. As of IE 6, the only reliable format is Text. While the method accepts URL as a format, reading a set value in that format is not successful.


stringData

Any string value, including strings that contain HTML tags.


See abbr.


The col object reflects the col element. The element provides ways of assigning single or multiple adjacent columns to groups for convenience in assigning styles, widths, and other visual treatments to columns within a table.


HTML Equivalent

<col>


Object Model Reference

 [window.]document.getElementById("elementID") 


Object-Specific Properties

align
ch
chOff
span
vAlign
width

Object-Specific Methods

None.


Object-Specific Events

None.


Defines the horizontal alignment of content within cells covered by the col element.


Example

 document.getElementById("myCol").align = "center"; 


Value

Any of the three horizontal alignment constants: center | char | left | right.


Default

left


Defines the text character used as an alignment point for text within a column or column group (reflecting the char attribute). This property is normally of value only for the align attribute set to "char". In practice, however, none of the supporting browsers respond to this property.


Example

 document.getElementById("myCol").ch = "."; 


Value

Single character string.


Default

None.


Defines the offset point at which the character specified by the char attribute is to appear within a cell. In practice, none of the supporting browsers respond to this property.


Example

 document.getElementById("myCol").chOff = "80%"; 


Value

String value of the number of pixels or percentage (within the cell).


Default

None.


Provides the number of adjacent columns for which the element's attribute and style settings apply.


Example

 document.getElementById("myCol").span = 2; 


Value

Integer.


Default

1


Provides the manner of vertical alignment of text within the column grouping's cells.


Example

 document.getElementById("myCol").vAlign = "baseline"; 


Value

Case-insensitive constant (as a string): baseline | bottom | middle | top.


Default

middle


Provides the width in pixels of each column of the column grouping. Changes to these values are immediately reflected in reflowed content on the page.


Example

 document.getElementById("myCol").width = 150; 


Value

Integer.


Default

None.


The colgroup object reflects the colgroup element, which provides ways of assigning multiple adjacent columns to groups for convenience in assigning styles, widths, and other visual treatments.


HTML Equivalent

<colgroup>


Object Model Reference

 [window.]document.getElementById("elementID") 


Object-Specific Properties

align
ch
chOff
span
vAlign
width

Object-Specific Methods

None.


Object-Specific Events

None.


Defines the horizontal alignment of content within cells covered by the colgroup element.


Example

 document.getElementById("myColgroup").align = "center"; 


Value

Any of the three horizontal alignment constants: center | char | left | right.


Default

left


Defines the text character used as an alignment point for text within a column or column group (reflecting the char attribute). This property is normally of value only for the align attribute set to "char". In practice, none of the supporting browsers respond to this property.


Example

 document.getElementById("myColgroup").ch = "."; 


Value

Single character string.


Default

None.


Defines the offset point at which the character specified by the char attribute is to appear within a cell. In practice, none of the supporting browsers respond to this property.


Example

 document.getElementById("myColgroup").chOff = "80%"; 


Value

String value of the number of pixels or percentage (within the cell).


Default

None.


Provides the number of adjacent columns for which the element's attribute and style settings apply.


Example

 document.getElementById("myColgroup").span = 2; 


Value

Integer.


Default

1


Provides the manner of vertical alignment of text within the column grouping's cells.


Example

 document.getElementById("myColgroup").vAlign = "baseline"; 


Value

Case-insensitive constant (as a string): baseline | bottom | middle | top.


Default

middle


Provides the width in pixels of each column of the column grouping. Changes to these values are immediately reflected in reflowed content on the page.


Example

 document.getElementById("myColgroup").width = 150; 


Value

Integer.


Default

None.


The comment object reflects the ! element in an HTML document. But in a W3C DOM environment, such as Mozilla, this object is not a genuine element in the context of the W3C DOM abstract model. Instead, the object is simply a special kind of node, whose nodeType value of 8 identifies it as a Comment node. A Comment node has the following inheritance chain in the DOM abstract model: Node->CharacterData->Comment. While a Comment node has special values automatically assigned to some of its properties (such as nodeValue), a Comment node has no properties or methods beyond the ones inherited from the Node and CharacterData objects. Node properties and methods are discussed earlier in this chapter among the shared items; CharacterData properties and methods are covered in detail with the Text object, which also inherits from CharacterData, and is more likely to be scripted.

To reference a comment element, use relative element or node properties. While IE provides an id property by virtue of its inheritance model, you cannot assign an identifier to the element via an id attribute. Such an element in IE does, however, have a tag name value of !. Therefore, you can reference an IE HTML comment element via the collection of elements returned by the document.all.tags("!") method. You can reference comment nodes in Mozilla only for comments delivered with the document within the body element, not the head. In Safari, you can reference only comment nodes added through scripting (e.g., via document.createComment( ) and any of the node insertion methods).


HTML Equivalent

 <!--comment text--> 


Object Model Reference

 nodeReference 


Object-Specific Properties

data
length
text

Object-Specific Methods

appendData( )
deleteData( )
insertData( )
replaceData( )
substringData( )

Object-Specific Events

None.


Provides the text content of the comment. See Text.data.


Provides the character count of the comment data. See Text.length.


Provides the text content of the element. Due to the nature of this element in IE, the value of the text property is identical to the values of the innerHTML and outerHTML properties. Changes to this property do not affect the text of the comment as viewed in the browser's source code version of the document. This property is not available in IE 4/Macintosh. For modern cross-browser access, use the data property.


Example

 document.all.tags("!")[4].text = "Replaced comment, but no one will know."; 


Value

String.


Default

None.


Provide methods for manipulating comment text. See these methods in the Text object.


See CanvasRenderingContext2D.


The controlRange object is a collection of element objects that had been selected from within an editable container (i.e., its contentEditable property is true), and created via the document.body.controlRange( ) or document.selection.createRange( ) methods. In a typical editing application, users can select whatever contiguous elements the editor allows within the container. A script can then iterate through the controlRange collection (perhaps filtering out elements such as img elements) and perform operations (including commands via the execCommand( ) method) on the elements within the collection. Microsoft has a demo of this feature at http://msdn.microsoft.com/library/default.asp?url=/workshop/samples/author/dhtml/collections/controlrange.htm.


Object Model Reference

 controlRangeReference 


Object-Specific Properties

length

Object-Specific Methods

add( )
addElement( )
execCommand( )
item( )
queryCommandEnabled( )
queryCommandIndeterm( )
queryCommandState( )
queryCommandSupported( )
queryCommandValue( )
remove( )
scrollIntoView( )
select( )

Object-Specific Events

None.


add( elementRef[, index])

Adds an element (from the createElement( ) method) to the current collection.


Returned Value

None.


Parameters


elementRef

A fully formed element object reference, usually generated by the createElement( ) method.


index

An optional integer indicating where in the collection the new element should be placed.


add( elementRef)

Adds an element to the current collection. This method is specifically designed for the controlRange collection. The new element should be contiguous with existing elements in the collection if you intend to invoke execCommand( ) or select( ) methods.


Returned Value

None.


Parameters


elementRef

A fully formed element object reference.


See the Textrange.execCommand method for details.


item( index)

Returns a single object from the collection.


Returned Value

One object reference. If there are no matches to the parameters, the returned value is null.


Parameters


index

Zero-based integer.


See the corresponding method description in the TexTRange object for details.


remove( index)

Deletes an element from the current collection. Simply specify the zero-based index value of the element you wish to remove from the collection.


Returned Value

None.


Parameters


index

A zero-based integer indicating which item in the collection should be deleted.


See scrollIntoView( ) in the shared methods at the beginning of this chapter.


Selects all the elements within the controlRange collection.


Returned Value

None.


Parameters

None.


See CSSRule.


A style sheet rule object is a member of the collection of styleSheet objects in the document. The IE and W3C DOMs have different syntax for referencing each of these rule objects. For IE, the reference is via the rules collection (a single object being known as a rule object); for W3C, as implemented in IE 5 for the Macintosh, Mozilla, Safari, and Opera 9, the reference is via the cssRules collection (a single object being known as a cssRule object). Note that the cssRule object is not in the Windows version of IE through Version 7. Additionally, security restrictions built into IE 6 and 7 prevent scripts from accessing the rules collection of a styleSheet object. Therefore, even though properties and methods below show IE support, those properties and methods are not truly available, and cause "Access denied" security errors.

The W3C DOM abstract object of a cssRule is called the CSSRule object, but that form of the object name is important only to scripters who wish to modify the prototype properties and methods of the CSSRule object in Mozilla. The W3C DOM goes further to define special types of CSSRule objects for each of the @ rule types (CSSImportRule, CSSMediaRule, and so onsee the type property for a list of all types). A member of the cssRules collection can be any one of those types, and is identified as such by its type property. Each type has its own set of properties and/or methods that apply to that cssRule type. In the property and method listings below, observe the type(s) for which they apply. By and large, however, the rules you will script are of the CSSStyleRule type, which are the typical rules that have selectors pointing to various elements in a document.

Use scriptable access to a rule or cssRule object with caution. If you modify a rule's selector or style definition, the changes affect the entire document, and could, with a misplaced colon, ruin other rules in the document. To toggle among two or more styles for a single element, class, or element type, it is generally more reliable and efficient to use other techniques that work with multiple rules (swapping className assignments on elements) or multiple style sheets (enabling and disabling styleSheet objects). But for the sake of the completeness of the object model, the W3C DOM in particular provides full access to style sheet rule pieces if you absolutely need them.


Object Model Reference

 document.styleSheets[i].rules[j]  // pre-IE 6 document.styleSheets[i].cssRules[j] 


Object-Specific Properties

cssRules
cssText
encoding
href
media
parentRule
parentStyleSheet
readOnly
selectorText
style
styleSheet
type

Object-Specific Methods

deleteRule( )
insertRule( )

Object-Specific Events

None.


Returns a collection of cssRule objects nested within an @media rule.


W3C DOM CSSRule Types

 CSSMediaRule 


Value

Reference to a cssRules collection object.


Default

Array of zero length.


Indicates the complete text of the style sheet rule, including selector and attribute name/value pairs inside curly braces. IE 6 for Windows provides no equivalent property. In supporting browsers, changes do not influence the object or rendering.


W3C DOM CSSRule Types

All.


Example

 document.styleSheets[0].cssRules[2].cssText = "td {text-align:center}"; 


Value

String.


Default

None.


Returns the character set code (e.g., ISO-8859-1 or UTF-8) associated with an @charset rule.


W3C DOM CSSRule Types

 CSSCharsetRule 


Value

String.


Default

None.


Returns the URI of the external style sheet file imported via an @import rule.


W3C DOM CSSRule Types

 CSSImportRule 


Value

String.


Default

None.


Returns the media type specified for an @import or @media rule.


W3C DOM CSSRule Types

 CSSImportRule CSSMediaRule 


Value

String constant for media types supported by the browser (e.g., screen or print).


Default

all


Refers to the cssRule object that contains the current cssRule, such as a rule nested inside an @ rule.


W3C DOM CSSRule Types

All.


Example

 var superRule = document.styleSheets[0].cssRules[1].parentRule; 


Value

cssRule object reference.


Default

null


Refers to the styleSheet object that contains the current cssRule. Allows a function that might be passed a reference to a cssRule object to obtain a reference to the containing styleSheet object, possibly to learn more about what else is in the style sheet.


W3C DOM CSSRule Types

All.


Example

 var ss = document.styleSheets[0].cssRules[3].parentStyleSheet; 


Value

styleSheet object reference.


Default

Current object.


Returns Boolean true for rules that arrive to a document via an @import rule or a link element. Such rules may not be modified by script, although an element governed by such a rule can have individual style properties modified because the modifications are made to the element's own style property, and not the rule object.


Example

 if (!document.styleSheets[2].cssRules[0].readOnly) {     // not read-only, so OK to modify here } 


Value

Boolean value: true | false.


Default

Varies with rule type.


Indicates the selector portion of the style sheet rule. Although this property is read/write (except in IE 5/Mac), changes do not influence the object or rendering.


W3C DOM CSSRule Types

 CSSPageRule CSSStyleRule 


Example

 document.styleSheets[0].cssRules[2].selectorText = "td.leftHeaders"; 


Value

String.


Default

None.


Returns a style object with properties that reflect the attribute settings of the current rule. This is the same kind of style object associated with elements in the document (corresponding to the W3C DOM CSSStyleDeclaration object). If you must modify style sheet settings at the rule level, do so via the style property of the rule or cssRule. Changes register themselves immediately, and the elements affected by the rule render their changes accordingly.


W3C DOM CSSRule Types

 CSSFontRule CSSPageRule CSSStyleRule 


Example

 var oneRule; if (document.styleSheets) {     if (document.styleSheets[0].cssRules) {         oneRule = document.styleSheets[2].cssRules[1];     } else if (document.styleSheets[0].rules) {         oneRule = document.styleSheets[2].rules[1];     } } if (oneRule) {     oneRule.style.color = "red";     oneRule.style.fontWeight = "bold"; } 


Value

Reference to a style (W3C CSSStyleDeclaration) object.


Default

Current style object.


Returns a reference to the styleSheet object contained by the imported style sheet. From here you can inspect cssRule objects belonging to that styleSheet objectessentially drilling down one more level to the styleSheet object structure of the remote style sheet file.


W3C DOM CSSRule Types

 CSSImportRule 


Value

styleSheet object reference.


Default

None.


Returns an integer corresponding to one of seven cssRule types, as defined by the W3C DOM. Every cssRule object in Mozilla comes equipped with plain-language constant properties corresponding to the rule types, as follows.

Constant

Equivalent integer

cssRuleReference.UNKNOWN_RULE

0

cssRuleReference.STYLE_RULE

1

cssRuleReference.CHARSET_RULE

2

cssRuleReference.IMPORT_RULE

3

cssRuleReference.MEDIA_RULE

4

cssRuleReference.FONT_FACE_RULE

5

cssRuleReference.PAGE_RULE

6



W3C DOM CSSRule Types

All.


Example

 var oneRule = document.styleSheets[2].cssRules[1]; if (oneRule.type == oneRule.IMPORT_RULE) {     // process @import rule } 


Value

Integer.


Default

1


deleteRule( index)

Removes the zero-based index numbered rule from the current @media rule.


W3C DOM CSSRule Types

 CSSMediaRule 


Returned Value

None.


Parameters


index

A zero-based integer corresponding to the specified item in source code order.


insertRule(" rule", index)

Inserts a new rule (selector text and style attributes) into the current @media rule at the position indicated by the second parameter.


W3C DOM CSSRule Types

 CSSMediaRule 


Returned Value

Integer of inserted position.


Parameters


rule

A string containing selector and curly braced style attributes comprising the rule to be inserted.


index

A zero-based integer corresponding to the specified item in source code order.


A collection of cssRule (W3C DOM browsers) or rule (IE 4 and later, but not accessible in IE 6 or 7 for security reasons) objects that are members of a styleSheet object. The W3C DOM abstract representation of this collection is called a CSSRuleList object. Members of this collection are accessed only via their integer index number, but you may iterate through the collection and examine properties of each rule object (such as the selectorText property) to distinguish one rule from another.


Object Model Reference


IE (Windows, pre-IE 6)

document.styleSheets[i].rules


Others

document.styleSheets[i].cssRules


Object-Specific Properties

length

Object-Specific Methods

item( )

Object-Specific Events

None.


Returns the number of elements in the collection, including @ rules.


Example

 var howMany = document.styleSheets[1].cssRules.length; 


Value

Integer.


item( index)

Returns a style sheet rule object corresponding to the rule matching the index value in source code order.


Returned Value

Reference to a cssRule or rule object, depending on the object model. If there are no matches to the parameters, the returned value is null.


Parameters


index

A zero-based integer corresponding to the specified item in source code order (nested within the current styleSheet object).


See style.


See styleSheet.


The currentStyle object (a property of all HTML element objects in IE 5 and later for Windows) provides read-only access to the effective (cascaded) style properties applied to the current element, including properties influenced by linked, imported, and explicit style sheet settings. This object is a property of all renderable HTML element objects and stands in contrast to an element's style object, which reports, and allows modification of, style sheet properties explicitly assigned to the inline style attribute.


Object Model Reference

 [window.]document.getElementById("elementID").currentStyle 


Object-Specific Properties

See the style object.


Object-Specific Methods

See the style object.


Object-Specific Events

None.


Provides scriptable access to author-defined elements. Such elements share properties, methods, and event handlers of generic HTML element objects, and usually have custom attributes associated with them. Internet Explorer exposes custom attributes as properties of the element object.


HTML Equivalent

 <user-defined-tag> 


Object Model Reference

 [window.]document.getElementById("elementID") 


Object-Specific Properties

None.


Object-Specific Methods

None.


Object-Specific Events

None.


The dataTransfer object (accessible as a property of the event object) is a temporary container that scripts in IE 5 or later for Windows and Safari 2 can use to transfer text data, particularly during script-controlled operations that simulate cutting, copying, and pasting, or that control dragging. Your script controls what data is stored in the dataTransfer object, such as just the text of an element, an element's entire HTML, or the URL of an image. For example, a page for children could display simple icon images of several different kinds of animals. If the user starts dragging the dog icon, the script initiated by the img element's ondragstart event handler can store a custom attribute value of that element (perhaps the URL of a pretty dog photo) into the dataTransfer object. When the user drops the icon into the designated area, the ondrop event handler's function reads the dataTransfer object's data, and loads the photo image into position on the page.

Even though an event object changes its properties with each new event action, the dataTransfer object preserves its data from one event to the next, until a script removes the data from the object or other data is stored in it. Properties of the dataTransfer object distinguish its powers from those of the clipboardData object. By setting the dropEffect and effectAllowed properties, your scripts can control the type of cursor icon that appears during drag and drop operations. Example 2-1 demonstrates how the properties and methods of the dataTransfer object can be wired to dragging events such that the cursor changes to a "copy" style when rolled atop a desired drop target.

Example 2-1. Using the dataTransfer object

 <html> <head> <title>dataTransfer Demo</title> <style type="text/css"> td {text-align:center} th {text-decoration:underline} .cyan {color:cyan} .yellow {color:yellow} .magenta {color:magenta} #blank1 {text-decoration:underline} </style> <script type="text/javascript"> // set stage when dragging a desired source element function setupDrag(evt) {     evt = (evt) ? evt : window.event;     var elem = (evt.target) ? evt.target : evt.srcElement;     if (elem.nodeType == 3) {elem = elem.parentNode;}     if (elem.tagName != "TD") {         // don't allow dragging for any other elements         evt.returnValue = false;     if (evt.preventDefault) {evt.preventDefault( );}     } else {         // set cursor to look like copy action         evt.dataTransfer.effectAllowed = "copy";         // store dragged cell text to transfer         evt.dataTransfer.setData("Text", elem.innerHTML);     } } // perform drop operations function handleDrop( evt) {     evt = (evt) ? evt : window.event;     var elem = (evt.target) ? evt.target : evt.srcElement;     var passedData = event.dataTransfer.getData("Text");     if (passedData) {         // show drop target cursor         event.dataTransfer.dropEffect = "copy";         // apply data to drop target         elem.innerHTML = passedData;         elem.className = passedData;         if (document.selection) {             document.selection.empty( );         }     } } // we're dragging/copying, but not to here function cancelDefault(evt) {     evt = (evt) ? evt : window.event;     // set cursor to "No" symbol     evt.dataTransfer.dropEffect = "copy";     evt.returnValue = false;     if (evt.preventDefault) {evt.preventDefault( );} } </script> </head> <body ondragstart="setupDrag(event);"> <table cellpadding="5"> <tr><th>Select and Drag Your Favorite Color</th></tr> <tr><td>cyan</td></tr> <tr><td>yellow</td></tr> <tr><td>magenta</td></tr> </table> <p>My favorite color is <span  ondragenter="cancelDefault(event);" ondragover="cancelDefault(event);" ondrop="handleDrop(event);"> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span> .</p> </body> </html> 

For more information on transferring data via this object and the clipboardData object, visit http://msdn.microsoft.com/workshop/author/datatransfer/overview.asp.


HTML Equivalent

None.


Object Model Reference

 [window.]event.dataTransfer 


Object-Specific Properties

dropEffect
effectAllowed

Object-Specific Methods

clearData( )
getdata( )
setData( )

Object-Specific Events

None.


These two properties work together but at different stages along a dragging operation that involves the dataTransfer object. They both control the appearance of the cursor during the drag and drop process. Assign a cursor style at the beginning of a drag operation via the ondragstart event and effectAllowed property. The drop target's ondragover and ondragenter event handlers should set the dropEffect property to the desired cursor style, and also set the event.returnValue property to false. This opens the way for the ondrop event handler not only to set the cursor via the dropEffect property, but to process the drop action. See Example 2-1 for a simple demonstration of the interaction of all these events and properties.


Example

 event.dataTransfer.dropEffect= "copy"; 


Value

Case-insensitive constant (as a string): copy | link | move | none.


Default

none


clearData([ dataFormat])

Removes data from the dataTransfer object.


Returned Value

None.


Parameters


dataFormat

An optional string specifying the format for the data to be removed. Earlier plans to allow multiple data types appear to have fallen through. The only reliable format is Text. Omitting the parameter deletes all data of all types.


getData( dataFormat)

Returns a copy of data from the dataTransfer object. The dataTransfer contents remain intact for subsequent reading in other script statements.


Returned Value

String.


Parameters


dataFormat

A string specifying the format for the data to be read. Earlier plans to allow multiple data types appear to have fallen through. The only reliable format is Text.


setData( dataFormat, stringData)

Stores string data in the dataTransfer object. Returns Boolean TRue if the assignment is successful


Returned Value

Boolean value: true | false.


Parameters


dataFormat

A string specifying the format for the data to be read. Earlier plans to allow multiple data types appear to have fallen through. The only reliable format is Text. While the method accepts URL as a format, reading a set value in that format is not successful.


stringData

Any string value, including strings that contain HTML tags.


The dd object reflects the dd element.


HTML Equivalent

<dd>


Object Model Reference

 [window.]document.getElementById("elementID") 


Object-Specific Properties

noWrap


Object-Specific Methods

None.


Object-Specific Events

None.


Specifies whether the browser should render the element as wide as is necessary to display a line of nonbreaking text on one line. Abuse of this attribute can force the user into a great deal of inconvenient horizontal scrolling of the page to view all of the content.


Example

 document.getElementById("wideBody").noWrap = "true"; 


Value

Boolean value: TRue | false.


Default

false


The del object reflects the del element.


HTML Equivalent

<del>


Object Model Reference

 [window.]document.getElementById("elementID") 


Object-Specific Properties

cite
dateTime

Object-Specific Methods

None.


Object-Specific Events

None.


These two properties are listed among the shared properties earlier in this chapter due to an implementation oddity in IE 6 and 7. IE 5/Macintosh, Mozilla, Safari, and Opera correctly implement these properties only for the del and ins objects, as specified in the W3C DOM, but in no mainstream browser do they convey any special powers. See the shared cite and dateTime properties.


See abbr.


The Dialog Helper object is an ActiveX control delivered with IE 6 and 7 that provides a short assortment of potentially useful system and document information; the method also displays a color selector dialog from which your scripts can obtain a user's color choice. Most typically, it would be used when scripting IE's edit mode, where users need to make color, font, and element choices. But you might find the object's properties and methods useful in traditional browser document settings.

Loading this object into the page requires the following <object> tag:

 <object  class         width="0px" height="0px"> </object> 

Because this object is not rendered, you may place its tag in the head portion of your document. You may also assign your choice of identifier to the id attribute. Once the object is loaded, reference it as a global object in the window.


HTML Equivalent

None.


Object Model Reference

 [window.]document.getElementById("elementID") 


Object-Specific Properties

blockFormats
fonts

Object-Specific Methods

ChooseColorDlg( )
getCharset( )

Object-Specific Events

None.


Returns a collection of plain-language names of block-level elements supported by the browser. Unlike other IE collections, to read the number of items, you must access its Count property, rather than length property. The names of items returned are strings, such as "Heading 1" and "Numbered List" (corresponding to the H1 and ol elements, respectively). Access each item in the collection via the collection's item( ) method.


Example

 var blockList = dlgHelper.blockFormats; var blockNames = new Array( ); for (var i = 0; i < blockList.Count; i++) {     blockNames[blockNames.length]= blockList.item(i); } 


Value

Array of strings


Default

Implementation-dependent.


Returns a collection of plain-language names of system fonts. Unlike other IE collections, to read the number of items, you must access its Count property, rather than length property. The names of items returned are strings, such as "MS Sans Serif" and "Verdana". Access each item in the collection via the collection's item( ) method.


Example

 var fontList = dlgHelper.fonts; var fontNames = new Array( ); for (var i = 0; i < fontList.Count; i++) {     fontNames [fontNames .length]= fontList .item(i); } 


Value

Array of strings


Default

Implementation-dependent.


ChooseColorDlg([ initialHexColor])

Displays a color selector dialog box, and returns a decimal number corresponding to the color chosen by the user. To apply the color to style or other color property settings, you may have to convert the decimal value to a suitable hexadecimal triplet value of the #RRGGBB format. The following fragment demonstrates the sequence of obtaining the color, converting it to the desired base and digit count, and assigning the value to a style property:

 var colorChoice = dlgHelper.ChooseColorDlg( ); var hexColor = colorChoice.toString(16); while (hexColor.length < 6) {hexColor = "0" + hexColor;} document.body.style.color = "#" + hexColor; 

If the user selects a custom color in the dialog and adds it to a little shortcut box, the color does not reappear in the box the next time the dialog appears. But a custom color can still be pre-selected by passing its hex value as a parameter to the method.


Returned Value

Decimal integer of the selected color (0 through as many colors of the client settings).


Parameters


initialHexColor

Optional hexadecimal number that presets the initially selected color in the dialog box.


getCharset(" fontName")

Returns an integer corresponding to a constant associated with a character set known by the operating system. Among the common values returned for font families installed on Latin-based systems are 0 (for plain ANSI character set) and 2 (for a symbol set). The required parameter is the name of a font to inspect for its character set. Such names may be retrieved from the fonts property of the Dialog Helper object:

 var setID = dlgHelper.getCharset(dlgHelper.fonts.item(4)); 

Not all Windows versions have the same character set suite installed.


Returned Value

Integer.


Parameters


fontName

String name of installed system font.


The dir object reflects the dir element. This element, originally intended as a multicolumn list format, is treated the same as the ul element.


HTML Equivalent

<dir>


Object Model Reference

 [window.]document.getElementById("elementID") 


Object-Specific Properties

compact


Object-Specific Methods

None.


Object-Specific Events

None.


Provided for this element for the sake of compatibility with the W3C DOM standard. However, mainstream browsers do not act upon this property or its corresponding attribute.


Value

Boolean value: TRue | false.


Default

false


These objects belong to the window object and represent portions of the "chrome" surrounding the content area of the browser window (the directories object was added to the list for Mozilla). With signed scripts in Navigator 4 or Mozilla (and the user's permission), you can dynamically hide and show these elements in a browser window. These features can also be turned off via the third parameter of the window.open( ) method, but only when generating a new window. To change the visibility of these items in an existing window, signed scripts are required. Other browsers offer no equivalent functionality for a window that is already open.


Object Model Reference

 [window.]directories [window.]locationbar [window.]menubar [window.]personalbar [window.]scrollbars [window.]statusbar [window.]toolbar 


Object-Specific Properties

visible


Object-Specific Methods

None.


Object-Specific Events

None.


Accessible only through signed scripts in Navigator 4 or Mozilla, determines whether the window chrome feature is displayed.


Example

 netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserWrite"); window.statusbar.visible = "false"; netscape.security.PrivilegeManager.revertPrivilege("UniversalBrowserWrite"); 


Value

Boolean value: true | false.


Default

true


The div object reflects the div element. This element creates a block-level element often used for element positioning or containment grouping of several related elements. The client and scroll properties are active in IE for the Macintosh.


HTML Equivalent

<div>


Object Model Reference

 [window.]document.getElementById("elementID") 


Object-Specific Properties

align
dataFld
dataFormatAs
dataSrc
noWrap

Object-Specific Methods

None.


Object-Specific Events

None.


Defines the horizontal alignment of content within the element's box. Unless otherwise reined in, the box width is that of the next outermost positioning contextusually the body.


Example

 document.getElementById("myDIV").align = "center"; 


Value

Any of the three horizontal alignment constants: center | left | right.


Default

left


Used with IE data binding to associate a remote data source column name to a div element's content. A datasrc attribute must also be set for the element. Setting both the dataFld and dataSrc properties to empty strings breaks the binding between element and data source. Works only for text data sources in IE 5 for the Macintosh.


Example

 document.getElementById("myDiv").dataFld = "comment"; 


Value

Case-sensitive identifier of the data source column.


Default

None.


Used with IE data binding, this property advises the browser whether the source material arriving from the data source is to be treated as plain text or as tagged HTML.


Example

 document.getElementById("myDiv").dataFormatAs = "text"; 


Value

String constants: text | html.


Default

text


Used with IE data binding to specify the ID of the page's object element that loads the data source object for remote data access. Content from the data source is specified via the datafld attribute. Setting both the dataFld and dataSrc properties to empty strings breaks the binding between element and data source.


Example

 document.getElementById("myDiv").dataSrc = "DBSRC3"; 


Value

Case-sensitive identifier of the data source.


Default

None.


Specifies whether the browser should render the element as wide as is necessary to display a line of nonbreaking text on one line. Abuse of this attribute can force the user into a great deal of inconvenient horizontal scrolling of the page to view all of the content. The corresponding attribute is deprecated.


Example

 document.getElementById("wideDiv").noWrap = "true"; 


Value

Boolean value: true | false.


Default

false


The dl object reflects the dl element. This element is the wrapper for a definition list grouping.


HTML Equivalent

<dl>


Object Model Reference

 [window.]document.getElementById("elementID") 


Object-Specific Properties

compact


Object-Specific Methods

None.


Object-Specific Events

None.


When set to true, the compact property instructs the browser to render a related dt and dd pair on the same line if space allows. This compact styling is intended for dt elements consisting of only a few characters.


Example

 document.getElementById("maindl").compact = true; 


Value

Boolean value: true | false.


Default

false


The document object represents both the content viewed in the browser window or frame and the other content of the HTML file loaded into the window or frame. Thus, all information from the head portion of the file is also part of the document object. The document object has no name other than its hard-wired object name: document.

For a browser with internal architecture based closely on the W3C DOM, this document object represents the HTMLDocument objecta special kind (internal subclass) of the core module's Document object, suited to holding HTML documents. In other words, the HTMLDocument object inherits the properties and methods of the core Document and Node objects (sharing facilities with XML documents) and gets additional properties and methods that apply only to HTML documents. Of course, there is the conceptual incongruity about whether an HTMLDocument is applicable to an XHTML document because such a document theoretically is an XML document. But, in practice, even an XHTML document becomes an HTML document for scripting purposes, and has all the HTMLDocument properties and methods available to it.

One more important practical side to a W3C DOM implementation (as evidenced by implementations in Mozilla, Safari, and Opera) is that the document object internally implements document-level properties and methods from other DOM modules, such as views, events, and styles. Each of these modules defines an object (DocumentEvent, DocumentRange, DocumentStyle, and DocumentView) that provides a vital connection between the HTMLDocument and these add-on module features. Thus, it is the styleSheets property of the DocumentStyle object in the W3C DOM that the scriptable document object described here uses to reach the styleSheet objects and their rules. And the DocumentEvent object links in its createEvent( ) method that allows the scriptable document object to generate an event outside the normal user- or system-created events. All of these features become subsumed by the document object you reference and script in Mozilla and other W3C DOM-centric browsers. The precise source module for a particular feature is not important to the scripterall you need to know is that the properties and methods belong to the scriptable document object.


Object Model Reference

 [window.]document 


Object-Specific Properties

activeElement
alinkColor
all[]
anchors[]
applets[]
bgColor
body
charset
characterSet
compatMode
contentType
cookie
defaultCharset
defaultView
designMode
doctype
documentElement
documentURI
domain
domConfig
embeds[]
expando
fgColor
fileCreatedDate
fileModifiedDate
fileSize
fileUpdatedDate
forms[]
frames[]
height
ids[]
images[]
implementation
inputEncoding
lastModified
layers[]
linkColor
links[]
location
media
mimeType
nameProp
namespaces[]
parentWindow
plugins[]
preferredStylesheetSet
protocol
readyState
referrer
scripts[]
security
selectedStylesheetSet
selection
strictErrorChecking
styleSheets[]
tags[]
title
URL
URLUnencoded
vlinkColor
width
xmlEncoding
xmlStandalone
xmlVersion

Object-Specific Methods

addBinding( )
adoptNode( )
captureEvents( )
clear( )
close( )
createAttribute( )
createAttributeNS( )
createCDATASection( )
createComment( )
createDocumentFragment( )
createElement( )
createElementNS( )
createEntityReference( )
createEvent( )
createEventObject( )
createNodeIterator( )
createProcessingInstruction( )
createRange( )
createStyleSheet( )
createTextNode( )
createTreeWalker( )
elementFromPoint( )
execCommand( )
getAnonymousElementByAttribute( )
getAnonymousNodes( )
getBindingParent( )
getElementById( )
getElementsByName( )
getOverrideStyle( )
getSelection( )
handleEvent( )
hasFocus( )
importNode( )
loadBindingDocument( )
normalizeDocument( )
open( )
postMessage( )
queryCommandEnabled( )
queryCommandIndeterm( )
queryCommandState( )
queryCommandSupported( )
queryCommandText( )
queryCommandValue( )
recalc( )
releaseEvents( )
removeBinding( )
renameNode( )
routeEvent( )
write( )
writeln( )

Object-Specific Events

Event

IE

Others

DOM

selectionchange

4

n/a

n/a

stop

4

n/a

n/a



Refers to the object that is currently designated as the active element in the document. To learn more about the returned object, you'll need to examine the object's tagName, id, or other properties. Because buttons and other elements may not receive focus on all platforms, the returned value of this property may vary with operating system. While an element (especially a form control) that receives focus also becomes active, an element might be active, but due to other settings in newer IE versions, does not have focus. See the shared setActive( ) method.


Example

 var currObj = document.activeElement; 


Value

Element object reference.


Default

None.


Specifies the color of a hypertext link as it is being clicked. The color is applied to the link text or border around an image or object embedded within all a elements in the document. See also linkColor and vlinkColor properties for unvisited and visited link colors. Replaced in the W3C DOM by the aLink property of the body object or in CSS by the :active pseudo-class. Dynamically changed values for alinkColor are not reflected on the page in pre-Mozilla Navigator.


Example

 document.alinkColor = "green"; 


Value

A hexadecimal triplet or plain-language color name. See Appendix A for acceptable plain-language color names.


Default

#0000FF


The all property is a member of all containers in IE 4 or later and Opera 7 or later, but a member of only the document object in Mozilla 1.7 or later. This property was added to Mozilla as a convenience for old scripts that used document.all references without conditional branches that tested for the existence of the property. As such, Mozilla recognizes document.all only in pages marked up in quirks mode (see the DOCTYPE element in Chapter 1), but even there does not expose the property as being valid in an if conditional expression. The normal IE practice of referencing elements by document.all.elementID and referencing an element solely by its ID work in Mozilla in quirks mode. See the all collection object earlier in this chapter.


Value

A collection of element objects in the document.


Default

The current collection.


Returns an array of all anchor objects in the current document. This includes a elements that are designed as either anchors or combination anchors and links. Items in this array are indexed (zero-based) in source code order.


Example

 var aCount = document.anchors.length; 


Value

Array of anchor element objects.


Default

Array of length zero.


Returns an array of all Java applet objects in the current document. An applet must be started and running before it is counted as an object. Items in this array are indexed (zero-based) in source code order.


Example

 var appletCount = document.applets.length 


Value

Array of applet element objects.


Default

Array of length zero.


Provides the background color of the document. Even if the bgcolor attribute or bgColor property is set with a plain-language color name, the returned value is always a hexadecimal triplet.

The modern preference to managing a document's background color is via the CSS background property for the body element.


Example

 document.bgColor = "yellow"; 


Value

A hexadecimal triplet or plain-language color name. See Appendix A for acceptable plain-language color names.


Default

Varies with browser and operating system.


Returns a reference to the body object defined by the body element within the document. This property is used as a gateway to the body object's properties.


Example

 document.body.style.marginLeft = "15px"; 


Value

Object reference.


Default

The current body object.


Indicates the character encoding of the document's content. For other browsers, use the document.characterSet property.


Example

 if (document.charset == "csISO5427Cyrillic") {     // process for Cyrillic charset } 


Value

Case-insensitive alias from the character set registry (ftp://ftp.isi.edu/in-notes/iana/assignments/character-sets).


Default

Determined by browser.


Indicates the character encoding of the document's content.


Example

 if (document.characterSet == "ISO-8859-1") {     // process for standard Latin character set } 


Value

Case-insensitive alias from the character set registry (ftp://ftp.isi.edu/in-notes/iana/assignments/character-sets).


Default

Determined by browser.


Returns the compatibility mode for the document, as controlled by the DOCTYPE element's content. See the DOCTYPE element discussion in Chapter 1 for details on how to force the browser to treat a document in either backward compatibility or standards compatibility mode for element positioning and other implementation details. Because the choice of mode can impact some style property results, you can use this property to branch between two calculations in a shared library so that they treat the current document correctly, regardless of mode.


Example

 if (document.compatMode == "BackCompat") {     // process as "quirks" mode } 


Value

String constant: BackCompat | CSS1Compat.


Default

BackCompat


Returns the MIME type for the document, as conveyed by the server.


Example

 if (document.contentType != "text/html") {     // process for alternative MIME type } 


Value

String.


Default

text/html


Indicates the HTTP cookie associated with the domain of the document and stored on the client machine. The Mozilla browsers group all cookie data together into a single file, while IE creates a separate file for each domain's cookie data.

Reading and writing the cookie property are not parallel operations. Reading a cookie property returns a semicolon-delimited list of name/value pairs in the following format:

 name=value 

Up to 20 of these pairs can be stored in the cookie property for a given domain (regardless of the number of HTML documents used in that web site). A total of 4,000 characters can be stored in the cookie, but it is advisable to keep each name/value pair to less than 2,000 characters in length. It is up to your scripting code to parse the cookie property value for an individually named cookie's value.

Writing cookie property values allows more optional pairs of data associated with a single name/value pair. Cookie data must be a string, but you can deconstruct an array into a string via the Array.join( ) method for writing the cookie value, and then use String.split( ) to reconstruct the array after reading the cookie data. The format is as follows:

 document.cookie = "name=value     [; expires=timeInGMT]     [; path=pathName]     [; domain=domainName]     [; secure]"; 

No matter how many optional subproperties you set per cookie, only the name/value pair may be retrieved. All cookie data written to the cookie property is maintained in the browser's memory until the browser quits. If an expiration date has been made part of the cookie data and that time has not yet expired, the cookie data is saved to the actual cookie file; otherwise, the cookie data is discarded. The browser automatically deletes cookie data that has expired when the browser next starts.


Example

 var exp = new Date( ); var nowPlusOneWeek = exp.getTime( ) + (7 * 24 * 60 * 60 * 1000); exp.setTime(nowPlusOneWeek); document.cookie = "userName=visitor; expires=" + exp.toGMTString( ); 


Value

Cookie data as string. See description.


Default

None.


Indicates the character encoding of the content of the document.


Example

 var cset = document.defaultCharset; 


Value

Case-insensitive alias from the character set registry (ftp://ftp.isi.edu/in-notes/iana/assignments/character-sets).


Default

Determined by browser.


Returns a reference to the W3C DOM abstract representation of a "viewer" that renders the document (the formal name for the object is AbstractView). In Mozilla and Opera, this object equates to the window or frame object that contains the document. A script function that has access to a document object (such as via the element object's ownerDocument property) can obtain a valid reference to the document's window in these browsers via this defaultView property. Safari, on the other hand, returns a reference just to an instance of the AbstractView object. The document's view (in either object referencing scheme) includes knowledge about cascaded style rules applied to each element. See Online Section V for an example of obtaining the effective style of an element with the help of the document.defaultView property and the getComputedStyle( ) method.


Example

 var elem = document.getElementById("myDiv"); var vw = document.defaultView; var currStyle = vw.getComputedStyle(elem, ""); var elemLeft = currStyle.getPropertyValue("left"); 


Value

Reference to a window object in Mozilla and Opera; reference to an instance of the AbstractView object in Safari that implements the W3C DOM ViewCSS object (also supported by Mozilla and Opera).


Default

The document's window or view.


Controls whether the document can be edited by the user. Because this property governs the entire document, it is prudent to create a separate, editable portion of the main page inside an iframe element, and engage the designMode property for the iframe's document.

When designMode is on, supporting browsers also make additional document methods available to the scripter, particularly those that execute commands (e.g., execCommand( )) to apply font and other text stylings to user-selected text in an editable document.

For an introduction to the use of designMode and related features in the Mozilla environment, visit: http://developer.mozilla.org/en/docs/Rich-Text_Editing_in_Mozilla.


Example

 document.getElementById("editMe").designMode = "on"; 


Value

String constant: off | on. Internet Explorer also allows Inherit.


Default

off (W3C); Inherit (IE)


Returns a reference to the DOCTYPE element object (the same as the W3C DOM abstract DocumentType node object). The property returns a reference value only if the DOCTYPE is specified in the document; otherwise the property returns null. See the DocumentType object for properties available in various browsers. In a pure W3C DOM environment, the doctype property is inherited from the core document object, and is thus available to XML documents, as well.


Example

 var docsType = document.doctype; 


Value

Node reference.


Default

None.


Returns a reference to the root element node of the document. For HTML documents, the reference is to the html element that encompasses the document's head and body elements. In a pure W3C DOM environment, the documentElement property is inherited from the core document object, and is thus available to XML documents, as well.


Example

 var rootElem = document.documentElement; 


Value

Element node reference.


Default

The current html element object.


Denotes the Uniform Resource Identifier of the current document. The value is the same as location.href, and can be used in the same way to navigate to a different URI, if desired.


Example

 document.documentURI = "http://www.megacorp.com"; 


Value

Complete or relative URI as a string.


Default

The current document's URI.


Provides the hostname of the server that served up the document. If documents from different servers on the same domain must exchange content with each other, the domain properties of both documents must be set to the same domain to avoid security restrictions. Normally, if the hosts don't match, browser security disallows access to the other document's form data. This property allows, for example, a page from the www server to communicate with a page served up by a secure server.


Example

 document.domain = "megaCorp.com"; 


Value

String of the domain name that two documents have in common (exclusive of the server name).


Default

None.


Returns a DOMConfiguration object, which reveals information about numerous configuration features of the current document. These features are typically of more use when working with XML documents.


Example

 var paramList = document.domConfig.parameterNames; 


Value

DOMConfiguration object.


Default

Current DOMConfiguration object.


Returns an array of all embedded objects (embed elements) in the current document. Items in this array are indexed (zero-based) in source code order.


Example

 var embedCount = document.embeds.length; 


Value

Array of embed object references.


Default

Array of zero length.


Specifies whether scripts in the current document allow the creation and use of custom properties assigned to the document object. The extensible nature of JavaScript allows scripters to create a new object property by just assigning a value to it (as in document.stooge = "Curly"). This also means the document accepts incorrectly spelled property assignments, such as forgetting to set a middle letter of a long property name to uppercase (marginLeftColor). Such assignments are accepted without question, but the desired result is nowhere to be seen. If you don't intend to create custom properties, consider setting document.expando to false in an opening script statement as you author a page. This could help prevent spelling errors from causing bugs. The setting affects only scripts in the current document.


Example

 document.expando = false; 


Value

Boolean value: TRue | false.


Default

true


Provides the foreground (text) color for the document. While you can change this property in all versions of Navigator, the text does not change dynamically in versions prior to 6. Still supported in current browsers, this property better handled via the document.body.text property or, better still, CSS color property settings.


Example

 document.fgColor = "darkred"; 


Value

A hexadecimal triplet or plain-language color name. See Appendix A for acceptable plain-language color names.


Default

Browser default (usually black).


Returns a string of the date (but not the time) that the server (or local filesystem) reports the currently loaded file was created. Starting with IE 5, the date information is formatted as mm/dd/yyyy. The value may be corrupted if the server supplies the data in a format that IE does not expect.


Example

 var dateObj = new Date(document.fileCreatedDate); 


Value

Date string.


Default

None.


Returns a string of the date (but not the time) that the server (or local file system) reports the currently loaded file was most recently modified. Starting with IE 5, the date information is formatted as mm/dd/yyyy. The value may be corrupted or incorrect if the server supplies the data in a format that IE does not expect.


Example

 var dateObj = new Date(document.fileModifiedDate); 


Value

Date string.


Default

None.


Returns the number of bytes for the size of the currently loaded document. IE for Windows returns this value as a string, while IE for Macintosh returns a number value (an important distinction if you need to perform math operations on the value).


Example

 var byteCount = parseInt(document.fileSize, 10); 


Value

Integer as string (Windows) or number (Mac).


Default

None.


Returns an empty string. Apparently not officially supported for the document object.


Returns an array of all form objects (form elements) in the current document. Items in this array are indexed (zero-based) in source code order, but may also be accessed by using the form's name as a string index value.


Example

 var elemCount = document.forms[0].elements.length; 


Value

Array of form objects.


Default

Array of zero length.


Returns an array of all iframe objects (iframe element objects, not to be confused with window-like frame objects) in the current document. Items in this array are indexed (zero-based) in source code order. For cross-browser compatibility with modern browsers, use document.getElementsByTagName("iframe") instead.


Example

 var iframeCount = document.frames.length; 


Value

Array of iframe objects.


Default

Array of zero length.


Return the pixel dimensions of the entire rendered document. These values coincide with the offsetHeight and offsetWidth property values for the document.body.parentNode (i.e., the html element) object. Since neither property pairing is yet sanctioned by the W3C DOM, you might prefer the offset pair, because they are at least cross-browser compatible.


Example

 var howTall = document.height; 


Value

Number of pixels.


Default

Current document size.


Used with the Navigator 4-only JavaScript syntax of style sheets, the ids[] collection is part of a reference to a single ID and the style property assigned to it in the syntax form [document.]ids.idName.stylePropertyName. For a list of related properties, see the tags object listing in this chapter.


Returns an array of all img element objects in the current document node tree (exclusive of pre-cached images loaded via the new Image( ) constructor). Items in this array are indexed (zero-based) in source code order, and may be accessed by number or by string name. The presence of this property indicates support for live, swappable images.


Example

 document.images["home"].src = "images/homeHilite.jpg"; 


Value

Array of img element objects.


Default

Array of zero length.


Returns a reference to the W3C DOMImplementation object, which represents, to a limited degree, the environment that makes up the document containerthe browser, for our purposes. Methods of the object let you see which DOM modules the browser reports supporting. This object is also a gateway to creating virtual W3C Document and DocumentType objects outside of the current document tree. Thus, in Mozilla you can use the document.implementation property as a start to generating a nonrendered document for external XML documents. See the DOMImplementation object for details about the methods and their browser support.


Example

 var xDoc = document.implementation.createDocument("", "theXdoc", null); 


Value

Reference to a DOMImplementation object.


Default

Current DOMImplementation object.


Returns the character encoding type specified for the document. The value is influenced by encoding specifications in the document, such as a meta element that specifies a charset.


Example

 if (document.inputEncoding == "ISO-8859-5") {     // process for ISO-8859-5 character encoding } 


Value

Character encoding type as a string, or null if the document is created outside of the current document node tree.


Default

UTF-8


Provides the date and time (as a string) on which the server says the document file was last modified. Some servers don't supply this information at all or correctly. Only in recent browsers is the date string in a form suitable as a parameter for a Date object constructor.


Example

 document.write(document.lastModified); 


Value

String representation of a date and time.


Default

None.


Returns an array of all Navigator 4-only layer element objects in the current document. Also included in the array are references to other HTML elements with style sheets that set the element to be relative- or absolute-positioned (in which case, Navigator 4 treats those elements as layer objects). Items in this array are indexed (zero-based) in source code order, and may be accessed by number or by string name. As a dead-end feature implemented only in Navigator 4, the presence of this property indicates support for the unique referencing requirements for Netscape layers.


Example

 if (document.layers) {     // use document.layers[] syntax for references } 


Value

Array of layer objects or their equivalent.


Default

Array of zero length.


Indicates the color of a hypertext link that has not been visited (that is, the URL of the link is not in the browser's cache). This is one of three states for a link: unvisited, active, and visited. The color is applied to the link text or border around an image or object embedded within an a element. Changes to this property do not dynamically change the link color in Navigator 4 or earlier. In modern browsers, you should be using the W3C DOM alternative, document.body.link, or, better still, the :link CSS pseudo-class.


Example

 document.link Color= "#00FF00"; 


Value

A hexadecimal triplet or plain-language color name. See Appendix A for acceptable plain-language color names.


Default

#0000FF


Returns an array of all area element objects and a element objects that have HRef attributes assigned to them (i.e., they are clickable links). Items in the array are in source code order.


Example

 for (var i = 0; i < document.links.length; i++) {     // iterate through document.links[] array } 


Value

Array of area and a (set up as link) element objects.


Default

Array of zero length.


Indicates the URL of the current document. This property was deprecated because it may conflict with the window.location property, but browsers continue to support it. Use either the widely implemented document.URL property, or, better, the window.location.href property.


Example

 document.location = "products/widget33.html"; 


Value

A full or relative URL as a string.


Default

Document URL.


Returns a string indicating the output medium for which the content is formatted. The property returns an empty string as of IE 6, and throws a security error if you assign accepted string values (all, print, or screen) to it. Avoid using this property with the document object.


Returns a string indicating the basic document type, but not in a MIME format. For an HTML document, the string returned changed starting with IE 5.5 to HTML Document. Do not confuse this document object property with the Netscape, Mozilla, and IE/Mac navigator.mimeTypes property, which is an entirely different animal.


Example

 var what = document.mimeType; 


Value

String.


Default

HTML Document


Returns a string containing the same data as document.title, including an empty string if no title element exists in the document. This property may not be officially supported for the document object in IE.


Value

String.


Default

Empty string.


Returns a collection of IE namespace objects implemented in the current document. A namespace object is a gateway to loading external behaviors. For more details, visit http://msdn.microsoft.com/workshop/author/behaviors/overview/elementb_ovw.asp.


Example

 var IENSCount = document.namespaces.length; 


Value

Array of namespace object references.


Default

Array of zero length.


Returns a reference to the window object (which may be a frame in a frameset) that contains the current document. Use this reference to access the window's properties and methods directly. The returned value is the same as the window reference from the document.


Example

 var siblingCount = document.parentWindow.frames.length; 


Value

window or frame object reference.


Default

window object.


Returns an array of all embedded objects (embed elements) in the current document. Items in this array are indexed (zero-based) in source code order. Do not confuse this collection with the navigator.plugins collection.


Example

 var embedCount = document.plugins.length; 


Value

Array of embed object references.


Default

Array of zero length.


Returns the title property value of the imported style sheet marked up to be the document author's preferred one, according to HTML 4 specifications for the link element.


Example

 if (document.preferredStylesheetSet == "main") {     // statements to work on 'main' style sheet rules } 


Value

String.


Default

Empty string.


Returns a plain-language string describing the protocol used to load the current document. Unlike the location.protocol property's literal value (e.g., http: or file:), the document.protocol is human-readable (e.g., Hypertext Transfer Protocol or File Protocol).


Example

 if (document.protocol == "File Protocol") {     // process for file access in IE } 


Value

Plain-language string.


Default

Current document's protocol type.


Returns the current download status of the document content. If a script (especially one initiated by a user event) can perform some actions while the document is still loading, but must avoid other actions until the entire page has loaded, this property provides intermediate information about the loading process. You would use its value in condition tests. The value of this property changes during loading as the loading state changes. Each change of the property value fires a readystatechange event.


Example

 if (document.readyState == "loading") {     // statements for alternate handling } 


Value

One of the following values (as strings): complete | interactive | loading | uninitialized. Some elements may allow the user to interact with partial content, in which case the property may return interactive until all loading has completed.


Default

None.


Returns a string of the URL of the page from which the current page was accessed, provided the original page had a link to the current page. Many server logs capture this information as well. Scripts can see whether the visitor reached the current document from specific origins and perhaps present slightly different content on the page accordingly. If the visitor arrived by another method, such as typing the document URL into a browser dialog or by selecting a bookmark, the referrer property returns an empty string. Many versions of IE for Windows fail to report the correct referrer URL, often showing the URL of the current page instead.


Example

 if (document.referrer) {     document.write("<p>Thanks for following the link to our web site.</p>"); } 


Value

String.


Default

None.


Returns an array of all script objects (script elements) in the current document. Each script object may contain any number of functions. The scripts[] collection counts the number of actual <script> tags in the document. Items in this array are indexed (zero-based) in source code order.


Example

 var scriptCount = document.scripts.length; 


Value

Array of script element references.


Default

Array of zero length.


Returns a string describing the security policy in force for the current document.


Example

 var secPolicy = document.security; 


Value

String.


Default

This type of document does not have a security certificate.


Returns the title property value of the imported style sheet marked up to be the document author's preferred one and currently selected. This appears to be an experimental property (see http://hixie.ch/specs/css/dom/altss/altss-1.0-pre7).


Value

String.


Default

Empty string.


Returns a selection object. To work with text that has been selected by the user or script, you must convert the selection to a Textrange object. Access to the text of a Mozilla or Safari selection is via the window.getSelection( ) method.


Example

 var range = document.selection.createRange( ); 


Value

Object reference.


Default

None.


Boolean value that controls whether the browser throws exceptions for DOM operations.


Example

 document.strictErrorChecking = false; 


Value

Boolean value: true | false.


Default

true


Returns an array of all styleSheet objects in the current document. Each style sheet object may contain any number of style sheet rules. The styleSheets[] collection counts the number of actual <style> tags in the document as well as <link> tags that load external style sheet files. Items in this array are indexed (zero-based) in source code order. An @import style sheet object is accessible via a styleSheet object's cssRule.styleSheet property. See the styleSheet object.


Example

 for (var i = 0; i < document.styleSheets.length; i++) {     // loop through each styleSheet object } 


Value

Array of styleSheet object references.


Default

Array of zero length.


Used with the Navigator 4-only JavaScript syntax of style sheets, the tags[] collection is part of a reference to a single tag type and the style property assigned to it. For a list of properties, see the tags object listing in this chapter. Do not confuse this Navigator use of the tags[] collection with Internet Explorer's use of the tags[] collection that belongs to the all collection.


Example

 document.tags.H1.color= "red"; 


Value

Array of Navigator 4 JavaScript Style Sheet tag object references.


Default

Array of zero length.


Unlike the title property for objects that reflect HTML elements, the document.title property refers to the content of the title element defined in the head portion of a document. The title content appears in the browser's titlebar to help identify the document. This is also the content that goes into a bookmark listing for the page. Although the property is read/write, don't be surprised if a browser version does not alter the window titlebar in response for security reasons.


Example

 document.title = "Fred\'s Home Page"; 


Value

String.


Default

None.


Provides the URL of the current document. The value is the same as location.href. The document.URL property evolved as a replacement for document.location to avoid potential confusion (by scripters and JavaScript interpreter engines) between the location object and document.location property.


Example

 document.URL = "http://www.megacorp.com"; 


Value

Complete or relative URL as a string.


Default

The current document's URL.


Returns the URL of the current document, but with any URL-encoded characters returned to their plain-language version (e.g., %20 is converted to a space character). The returned value is the same as if applying the JavaScript decodeURI( ) function to document.URL.


Example

 var straightPath = document.URLUnencoded; 


Value

Complete or relative URL as a string.


Default

The current document's URL.


Color of a hypertext link that has been visited recently. The color is applied to the link text or border around an image or object embedded within an a element. See also alinkColor and linkColor properties for clicked and unvisited link colors. Changes to this property do not dynamically change the link color in Navigator 4 or earlier. In modern browsers, you should use the W3C DOM alternative, document.body.vLink, or, better still, the CSS :visited pseudo-class.


Example

 document.vlinkColor = "gold"; 


Value

A hexadecimal triplet or plain-language color name. See Appendix A for acceptable plain-language color names.


Default

Varies with browser and operating system.


See height.


These three properties reflect information in an XML document's XML declaration. For example, in the following declaration

 <?xml version="1.0" standalone="yes"?> 

The xmlVersion property reports 1.0 and xmlStandalone returns true. Because there is no character encoding declared, the xmlEncoding property returns an empty string. The xmlVersion property is read-only, while the other two are read-write.

Although Mozilla 1.8 and 1.8.1 support these properties, they are not completely implemented, and may report incorrect values.


Value

Strings (xmlVersion and xmlEncoding); Boolean (xmlStandalone).


Default

Should be null, false, and null (respectively), but in Mozilla 1.8 and 1.8.1 evaluate to an empty string, false, and an empty string (respectively).


This series of Mozilla document object methods are part of a browser programming feature called Extensible Binding Language (XBL), an adjunct to the XML-based mechanism that the browser uses for generating user interface skins. To learn more about XBL, visit http://www.mozilla.org/docs/xul/xulnotes/xulnote_xbl.html.


adoptNode( nodeReference)

Removes a node from another document and brings it into the context of the current document. You can then use other methods of the current document to insert the node into the desired location in the document tree.


Returned Value

Reference to adopted node.


Parameters


nodeReference

A reference to the node (usually in another document) you intend to adopt into the current document.


captureEvents( eventTypeList)

Instructs the browser to grab events of a specific type before they reach their intended target objects. The object invoking this method must then have event handlers defined for the given event types to process the event. Although this method is part of the Navigator 4 event model, it continues to be supported in Mozilla, as well as Safari and Opera 8 or later, creating the equivalent of a W3C DOM capture-mode event listener for the document object. While the method may be convenient, you should direct new code to the W3C DOM event listener syntax as described in Online Section VI.


Returned Value

None.


Parameters


eventTypeList

A comma-separated list of case-sensitive event types as derived from the available static Event object constants, such as Event.CLICK or Event.MOUSEMOVE.


Removes the current document from the window or frame, usually in preparation to open a new stream for writing new content. The document.write( ) and document.writeln( ) methods automatically invoke this method. Many bugs with the document.clear( ) method plagued earlier browser versions. Even today, it is best to let the document writing methods handle the job for you. The W3C DOM explicitly omits this method.


Returned Value

None.


Parameters

None.


Closes the document writing stream to a window or frame. If a script uses document.write( ) or document.writeln( ) to generate all-new content for a window or frame (which will replace the entire current document with the newly written content), you must append a document.close( ) method to make sure the entire content is written to the document. Omitting this method may cause some content not to be written. This method also prepares the window or frame for a brand new set of content with the next document writing method. Do not, however, use document.close( ) if you use the document writing methods to dynamically write content to a page while loading from the server.


Returned Value

None.


Parameters

None.


createAttribute(" attributeName")

Generates in memory an instance of an attribute node (Attr object). A typical sequence is to create the attribute, assign a value to it via its nodeValue property, and then insert the Attr node into an element's attribute list via the element's setAttributeNode( ) method.


Returned Value

Attr node object reference.


Parameters


attributeName

A case-sensitive string of the attribute's name.


createAttributeNS(" namespaceURI", " qualifiedName")

Generates in memory an instance of an attribute node (Attr object) whose name is defined in an external namespace. A typical sequence is to create the attribute, assign a value to it via its nodeValue property, and then insert the Attr node into an element's attribute list via the element's setAttributeNodeNS( ) method.


Returned Value

Attr node object reference.


Parameters


namespaceURI

URI string that will match a URI assigned to a label earlier in the document into which the attribute is eventually added.


qualifiedName

The full name for the attribute, consisting of the local name prefix (if any), a colon, and the local name.


createCDATASection(" data")

Generates in memory an instance of a character data section node (CDATASection object) in an XML (including XHTML) document.


Returned Value

CDATASection node object reference.


Parameters


data

String data that comprises the content of the section.


createComment(" commentText")

Generates in memory an instance of a comment node (comment object with a nodeValue of 8). A typical sequence is to create the Comment node, then insert it into the desired location of the document tree via any node's appendChild( ) or insertBefore( ) method. Only partially implemented in IE 5/Mac.


Returned Value

Comment node object reference.


Parameters


commentText

String containing the comment data.


Generates in memory an instance of an empty document fragment node (DocumentFragment object). This node becomes an arbitrary holder for assembling a sequence of nodes that ultimately get appended or inserted into a document tree. See the DocumentFragment object for more details.


Returned Value

DocumentFragment node object reference.


Parameters

None.


createElement(" tagName")

Generates in memory an instance of an element object associated with the tag passed as a parameter to the method. The method is limited to area, img, and option elements in IE 4; all elements are permitted in other supporting browsers. A newly created element has no attribute values assigned (except any default values assigned according to the DTD), nor is the element yet part of the document tree. Assign attributes (such as the type for an input element or id for any element), and append or insert the element into the document tree. This sequence is the W3C DOM approach to generating new content (in place of the Microsoft proprietary innerHTML convenience property implemented in many modern browsers).


Returned Value

Element object reference.


Parameters


tagName

A string of the tag name of the new element: document.createElement("option"). IE also allows a complete start tag string, complete with angle brackets and attribute name/value pairs. Only the straight tag name is supported by the W3C DOM specification.


createElementNS(" namespaceURI", " qualifiedName")

Generates in memory an instance of an element object associated with namespace, label, and tag passed as parts of the method's parameters. A newly created element has no attribute values assigned (except any default values assigned according to the DTD), nor is the element yet part of the document tree. Assign attributes (such as the type for an input element or id for any element), and append or insert the element into the document tree.


Returned Value

Element object reference.


Parameters


namespaceURI

URI string that will match a URI assigned to a label earlier in the document into which the attribute is eventually added.


qualifiedName

The full name for the attribute, consisting of the local name prefix (if any), a colon, and the local name.


createEntityReference(" entityName")

Generates in memory an instance of an entity reference node object for an XML document. Only partial support provided in IE 5/Mac.


Returned Value

Entity reference node object reference.


Parameters


entityName

String value.


createEvent(" eventType")

Generates in memory an instance of a W3C DOM Event object of a particular event category. After the generic event is created, it must be initialized (via one of several initialization methods) as a particular event type, along with other properties appropriate for the event category. The following sequence creates a mousedown event and sends it to an element:

 var evt = document.createEvent("MouseEvents"); evt.initEvent("mousedown", true, true); document.getElementById("myElement").dispatchEvent(evt); 

Such an event might then be handed to an element (via the element's dispatchEvent( ) method) so that the element's event listener can process the event as if it had been generated by a user clicking the mouse button.


Returned Value

Event object object reference.


Parameters


eventType

String constant for one of the event categories in all supporting browsers: HTMLEvents, KeyEvents (not specified in the W3C DOM Level 2), MouseEvents, MutationEvents, or UIEvents. DOM Level 3 restructures this list with all-new (singular) event categories (supported starting with Mozilla 1.7.5 and Opera 8): Event (formerly HTMLEvents), KeyboardEvent, MouseEvent, MutationEvent, MutationNameEvent, TextEvent, or UIEvent.


createEventObject([ existingEventObject])

Generates in memory an instance of an empty IE DOM event object. After the generic event is created, its properties can be stuffed with pertinent values to help the event be processed. Then the event acts as a parameter to an element's fireEvent( ) method, at which point the event type is associated with the event. The following sequence creates a mousedown event and sends it to an element:

 var evt = document.createEventObject( ); document.getElementById("myElement").fireEvent("onmousedown", evt); 

You can also use an existing event object as a model for a script-generated event. Pass the current event object as a parameter to the createEventObject( ) method, and modify the properties of the new object as you see fit.


Returned Value

event object reference.


Parameters


existingEventObject

Reference to an event object either generated by the user or script. The new event assumes all properties of the existing event object.


createNodeIterator( rootNode, whatToShow, filterFunction, entityRefExpansion)

Generates in memory an instance of a NodeIterator object. This method has the same set of parameters as the createTreeWalker( ) method.


Returned Value

NodeIterator object reference.


Parameters


rootNode

Reference to a node in the document tree that becomes the first node in the NodeIterator object's list of nodes.


whatToShow

Integer value corresponding to one of several built-in filters that allow nodes of a single type to be included in the NodeIterator object returned by the method. The NodeFilter object contains constants that should be used as plain-language substitutes for this value:

NodeFilter.SHOW_ALL
NodeFilter.SHOW_ATTRIBUTE
NodeFilter.SHOW_CDATA_SECTION
NodeFilter.SHOW_COMMENT
NodeFilter.SHOW_DOCUMENT
NodeFilter.SHOW_DOCUMENT_FRAGMENT
NodeFilter.SHOW_DOCUMENT_TYPE
NodeFilter.SHOW_ELEMENT
NodeFilter.SHOW_ENTITY
NodeFilter.SHOW_ENTITY_REFERENCE
NodeFilter.SHOW_NOTATION
NodeFilter.SHOW_PROCESSING_INSTRUCTION
NodeFilter.SHOW_TEXT

filterFunction

Reference to a user function that can further filter nodes that are included in the NodeIterator object. The function has a single parameter (a reference to a node to test, invoked automatically by the NodeIterator object). The value returned by the function determines whether the node being tested is to be included in the list of nodes. Returned values are integers, but the NodeFilter object provides three constants you should use as plain-language substitutes:

NodeFilter.FILTER_ACCEPT
NodeFilter.FILTER_REJECT
NodeFilter.FILTER_SKIP

Because a NodeIterator object does not maintain its list of nodes as a hierarchy, the values NodeFilter.FILTER_REJECT and NodeFilter.FILTER_SKIP pass over a node without any effect on child nodes. See the treeWalker object for an example of this kind of function.


entityRefExpansion

Boolean value that controls whether the content of entity reference nodes (found predominantly in XML documents) should be treated as hierarchical nodes (TRue) or not (false).


createProcessingInstruction(" target", " data")

Generates in memory an instance of a processing instruction node object in an XML document. Only partial support provided in IE 5/Mac.


Returned Value

Processing instruction node object reference.


Parameters


target

String value.


data

String value.


Creates a blank Range object, whose boundary points are collapsed to the point before the first character of the rendered body text. The method returns a reference to that Range object, which you then use to adjust its boundary points, invoke its methods, and so on. See the Range object for details of its language features.


Returned Value

W3C DOM Range object reference.


Parameters

None.


createStyleSheet([" url"[, index]])

This method performs the same actions in IE for Windows and Macintosh, but their returned values differ. Moreover, the specific actions in the document tree depend upon the parameters passed with the method. When no parameters are included, the method inserts a blank style element into the document tree. This style element, however, is not reflected in the document.styleSheets collection until you add one or more style rules to the object. But if you specify a URL to an external .css file as the first parameter, the method creates and inserts a link element into the document's head section, bringing the external style rules to life immediately.

IE for Windows always returns a reference to a styleSheet object; IE for Macintosh returns a reference to the newly inserted element, which will be a style or link element, depending on the parameter makeup. The inserted style element reference is of little help for adding a rule because you can't reference the styleSheet object. For cross-operating-system compatibility, it's best to use this method only for external style sheets.


Returned Value

styleSheet object reference (Windows); style or link element object reference (IE 5 and later for Macintosh).


Parameters


url

A string of the URL of an external .css style sheet definition file.


index

Optional zero-based integer that indicates where among the styleSheets[] collection this new style sheet should be inserted. Default behavior is to append to the end of the collection, but this may affect cascading rules for your document. See Online Section III.


createTextNode(" text")

Generates in memory an instance of a text node (W3C DOM Text object) whose nodeValue consists of the untagged text content passed as a parameter. A newly created text node is not yet part of the document tree. Append or insert the node into the document tree or document fragment being assembled for later document insertion. This sequence is the W3C DOM approach to generating new content (in place of the Microsoft proprietary innerText convenience property implemented in some browsers).


Returned Value

Text node object reference.


Parameters


text

A string of characters to be rendered as content when inserted into the document tree.


createTreeWalker( rootNode, whatToShow, filterFunction, entityRefExpansion)

Generates in memory an instance of a treeWalker object.


Returned Value

treeWalker object reference.


Parameters


rootNode

Reference to a node in the document tree that becomes the first node in the treeWalker object's list of nodes.


whatToShow

Integer value corresponding to one of several built-in filters that allow nodes of a single type to be included in the TReeWalker object returned by the method. The NodeFilter object contains constants that should be used as plain-language substitutes for this value:

NodeFilter.SHOW_ALL
NodeFilter.SHOW_ATTRIBUTE
NodeFilter.SHOW_CDATA_SECTION
NodeFilter.SHOW_COMMENT
NodeFilter.SHOW_DOCUMENT
NodeFilter.SHOW_DOCUMENT_FRAGMENT
NodeFilter.SHOW_DOCUMENT_TYPE
NodeFilter.SHOW_ELEMENT
NodeFilter.SHOW_ENTITY
NodeFilter.SHOW_ENTITY_REFERENCE
NodeFilter.SHOW_NOTATION
NodeFilter.SHOW_PROCESSING_INSTRUCTION
NodeFilter.SHOW_TEXT

filterFunction

Reference to a user function that can further filter nodes that are included in the TReeWalker object. The function has a single parameter (a reference to a node to test, invoked automatically by the TReeWalker object). The value returned by the function determines whether the node being tested is to be included in the list of nodes. Returned values are integers, but the NodeFilter object provides three constants you should use as plain-language substitutes:

NodeFilter.FILTER_ACCEPT
NodeFilter.FILTER_REJECT
NodeFilter.FILTER_SKIP

With a return value of NodeFilter.FILTER_SKIP, descendant nodes of the skipped node may still qualify as members of the TReeWalker node list (provided they survive other filtering). A return value of NodeFilter.FILTER_REJECT removes both the node under test and its descendants from consideration as members of the treeWalker object. See the treeWalker object for an example of this kind of function.


entityRefExpansion

Boolean value that controls whether the content of entity reference nodes (found predominantly in XML documents) should be treated as hierarchical nodes (true) or not (false).


elementFromPoint( x, y)

Returns a reference to the object directly underneath the pixel coordinates specified by the x (horizontal) and y (vertical) parameters. For an element to be recognized, it must be capable of responding to mouse events. Also, if more than one element is positioned in the same location, the element with the highest zIndex value or, given equal zIndex values, the element that comes last in the source code order is the one returned.


Returned Value

Element object reference.


Parameters


x

Horizontal pixel measure relative to the left edge of the window or frame.


y

Vertical pixel measure relative to the top edge of the window or frame.


execCommand(" commandName"[, UIFlag[, value]])

Executes the named command. In IE, most commands require that a TexTRange object be created first for an insertion point, while in the rest, the command impacts either the current text insertion point or selection. See Appendix D for a list of commands.


Returned Value

Boolean value: TRue if command was successful; false if unsuccessful.


Parameters


commandName

A case-insensitive string value of the command name. See Appendix D.


UIFlag

Optional Boolean value: true to display any user interface triggered by the command (if any); false to prevent such display.


value

A parameter value for the command.


See addBinding( ).


See addBinding( ).


See addBinding( ).


getElementById(" elementID")

Returns a reference to an element node from the document tree whose id attribute value matches the parameter value. If there is no match, the method returns null. This method, although a chore to type while observing its case-sensitive name, is the gateway for scripts in W3C DOM-capable browsers to communicate with element objects.


Returned Value

Reference to element node object.


Parameters


elementID

String of the desired element's ID.


getElementsByName(" elementName")

Returns an array of references to all element nodes from the document tree whose name attribute value matches the parameter value. If there is no match, the method returns null. When an element supports both the name and id attribute, IE for Windows and Opera include an element in the returned array even if only the id attribute is set to the parameter value. Other supporting browsers match only elements that have name attributes explicitly set to the parameter value (as prescribed in the W3C DOM spec).


Returned Value

Array of references to element node object.


Parameters


elementName

String of the desired element's name.


getOverrideStyle( elementReference, pseudoElement)

Returns a style object (CSSStyleDeclaration type) for the element passed as a parameter. This method allows a script to get (and then set via setProperty( )) style sheet properties of XML documents, which don't have the style convenience facilities of HTML documents. While Safari 1.3/2 implements the method, the returned value is empty.


Returned Value

Style object of type CSSStyleDeclaration.


Parameters


elementReference

Reference to a single element object in the document.


pseudoElement

String denoting a pseudo-element, if necessary; otherwise null.


In Navigator 4, this method captures the current text selection in the document. The method is deprecated in Mozilla in favor of the window.getSelection( ) method (which returns a sophisticated selection object, rather than just text). Invoking from the document object in Mozilla displays a warning in the JavaScript/Error Console window, but does not throw a full-fledged exception. The IE equivalent is reading the selection property.


Returned Value

String.


Parameters

None.


handleEvent( event)

Instructs the document object to accept and process the Navigator 4-only event whose specifications are passed as the parameter to the method. The object must have an event handler for the event type to process the event.


Returned Value

None.


Parameters


event

A Navigator 4 event object.


Returns Boolean true if the document or any element in the document has focus. A background process, such as a function invoked through setTimeout( ) can find out if the document's window is currently the front window on the Desktop.


Returned Value

Boolean value: true | false.


Parameters

None.


importNode( nodeReference, deepBoolean)

Imports a node object from another loaded document into the current document, but not yet place the node into the document tree. In many ways, importNode( ) works like cloneNode( ), but it assumes that the source node may exist in an entirely different document tree context (especially in an XML document). W3C DOM rules for this method govern what properties and attributes of the source node make the journey and what happens to them upon their arrival. For example, an Attr node loses its ownerElement (i.e., its value becomes null) when imported from an element in one document into a fragment-like state in the new documentuntil the attribute gets added to an element in the new document. Nodes of Document and DocumentType types are not importable.

The importNode( ) method does not assume the responsibility of persistence between documents. That's where, for instance, a JavaScript variable comes into play. As with cloneNode( ), the importNode( ) method does not disturb the source node (unlike adoptNode( ), which removes the source node from its original location).


Returned Value

Reference to the imported copy of the node object.


Parameters


nodeReference

Reference to a node in a different loaded document (including a nonrendered document loaded into the browser by way of the document.implementation.createDocument( ) method).


deepBoolean

Boolean value that controls whether the copy includes all nested nodes (TRue) or only the current node (false). Required, but applicable primarily to element nodes.


See addBinding( ).


Among other actions, performs the equivalent of invoking the normalize( ) method on all elements in the document at once. Other actions may be influenced by specific settings of the DOMConfiguration object for the current document.


Returned Value

None.


Parameters

None.


open([" MIMEType"][, "replace"])

Opens the output stream for writing to the current window or frame. If document.clear( ) has not already been invoked, it is automatically invoked in response to the document.open( ) method. If you are writing HTML text, you can omit this method, and start right in with document.write( ) or document.writeln( ).


Returned Value

None.


Parameters


MIMEType

Advises the browser of the MIME type of the data to be written in subsequent statements. Navigator supports "text/html" | "text/plain" | "image/gif" | "image/jpeg" | "image/xbm" | "plugIn". Only "text/html" is supported in Internet Explorer.


replace

The presence of this parameter directs the browser to replace the entry in the history list for the current document with the document about to be written.


postMessage(" messageText")

Permits the transfer of text data from one document to another, even if the two documents are served from different domains. Both documents have to be loaded and the destination document must have a suitable reference available for the method to work. For example if the main document includes an iframe element containing a document from another domain, the main document can reference the other document and send it a text message:

 var destDoc = document.getElementById("myIframe").contentDocument; destDoc.postMessage("blue"); 

The following event handler binding in the destination document processes the event to change the background color of the document in the iframe element:

 document.addEventListener("message", receiver, false); function receiver(evt) {     if (evt.domain == "example-friendly-place.com") {         document.body.style.backgroundColor = evt.data;     } } 

String data could obviously be assigned to other script variables in the destination document, including data that can be evaluated into arrays and objects (JavaScript Object Notation). This mechanism comes from the WHATWG Web Applications 1.0 specification (http://whatwg.org/specs/web-apps/current-work).


Returned Value

None.


Parameters


messageText

String value to be passed to another document.


queryCommandEnabled(" commandName")

Specifies whether the command can be invoked in light of the current state of the document or selection.


Returned Value

Boolean value: true if enabled; false if not.


Parameters


commandName

A case-insensitive string value of the command name. See Appendix D.


queryCommandIndeterm(" commandName")

Specifies whether the command is in an indeterminate state.


Returned Value

Boolean value: true | false.


Parameters


commandName

A case-insensitive string value of the command name. See Appendix D.


queryCommandState(" commandName")

Determines the current state of the named command.


Returned Value

true if the command has been completed; false if the command has not completed; null if the state cannot be accurately determined.


Parameters


commandName

A case-insensitive string value of the command name. See Appendix D.


queryCommandSupported(" commandName")

Determines whether the named command is supported by the document object.


Returned Value

Boolean value: TRue | false.


Parameters


commandName

A case-insensitive string value of the command name. See Appendix D.


queryCommandText(" commandName")

Returns text associated with the command.


Returned Value

String.


Parameters


commandName

A case-insensitive string value of the command name. See Appendix D.


queryCommandValue(" commandName")

Returns the value associated with the command, such as the name font of the selection.


Returned Value

Depends on the command.


Parameters


commandName

A case-insensitive string value of the command name. See Appendix D.


recalc([ allBoolean])

Forces the recalculation of expressions assigned to element attributes via the setExpression( ) method. Needed only when automatic recalculation isn't triggered by user action, but affected values might have changed.


Returned Value

None.


Parameters


allBoolean

When set to true, forces all dynamic attribute expressions in the document to recalculate. The default false lets browser decide which expressions are affected by changes since the last manual or automatic recalculation.


releaseEvents( eventTypeList)

The opposite of document.captureEvents( ), this method turns off event capture at the document level for one or more specific events named in the parameter list. Although this method is part of the Navigator 4 event model, it continues to be supported in Mozilla, as well as Safari and Opera 8 or later, performing the equivalent of a W3C DOM event listener removal for the document object. While the method may be convenient, you should direct new code to the W3C DOM event listener syntax as described in Online Section VI.


Returned Value

None.


Parameters


eventTypeList

A comma-separated list of case-sensitive event types as derived from the available Event object constants, such as Event.CLICK or Event.MOUSEMOVE.


See addBinding( ).


renameNode( nodeReference, " namespaceURI", " qualifiedName")

Renames an element or attribute node in the current document. An element's name in this context is its tag name.


Returned Value

Reference to the newly renamed node (if the renaming took effect).


Parameters


nodeReference

Reference to the node whose name is to be changed.


namespaceURI

String of the namespace URI, or an empty string of no namespace is involved.


qualifiedName

Full name of the element or attribute, including namespace prefix, if applicable.


routeEvent( event)

Used inside an event handler function, this method directs Navigator 4 to let the event pass to its intended target object. The method does not cause an error in Mozilla, but it does not perform any action.


Returned Value

None.


Parameters


event

A Navigator 4 event object


write(" string1"[, ..." stringN"]) writeln(" string1"[, ..." stringN"])

When invoked as the page loads, these methods can dynamically add content to the page. When invoked after the page has loaded, a single method invocation clears the current document, opens a new output stream, and writes the content to the window or frame. A document.close( ) method is required afterward. Because the first document.write( ) or document.writeln( ) method destroys the current document, do not use two or more writing statements to create a new document. Instead, load the content into one variable and pass that variable as the parameter to a single document.write( ) or document.writeln( ) method.

Using document.write( ) for <script> tags is tricky in many early browsers because it typically interprets the writing of the end script tag as meaning the end of the script doing the writing. You should have success, however, if you split the end script tag into string sections:

 document.write("<" + "/script>"); 

If you include the "hide script" comment trick, write it this way:

 document.write("//" + ">"); 

The difference between the two methods is that document.writeln( ) adds a carriage return to the source code it writes to the document. This is not reflected in the rendered content, but can make reading the dynamic source code easier in browser versions that support dynamic content source viewing.


Returned Value

None.


Parameters


string

Any string value, including HTML tags.


The document object described earlier is, in the W3C DOM structure, more specifically an HTMLDocument node, a member of the HTML module of the standard. The HTMLDocument node inherits the properties and methods of the Document node (with an uppercase "D" described here, and defined in the W3C DOM Core module). This is the pure, abstract Document node, and all that is needed to contain an unrendered XML document.

Mozilla and Opera 9 extend this node with a load( ) method that allows scripts to load XML documents into a plain (and unseen) Document node. Such a node is created via the document.implementation.createDocument( ) method. Scripts can then access the XML data in that document through regular W3C DOM document tree properties and methods. The XMLHttpRequest object, however, is now the preferred way to load external XML data into the browser.

To help reinforce in your mind the heritage of the document object you normally script (that is, the instance of the HTMLDocument node represented in each window's document), I show the lists of properties and methods for the core Document object. For descriptions of all these properties and methodsexcept for the uninherited load( ) methodsee the document object, earlier in this chapter.


Object Model Reference

 documentNodeReference 


Object-Specific Properties

doctype
documentElement
documentURI
domConfig
implementation
inputEncoding
strictErrorChecking
XMLEncoding
XMLStandalone
XMLVersion

Object-Specific Methods

adoptNode( )
createAttribute( )
createAttributeNS( )
createCDATASection( )
createComment( )
createDocumentFragment( )
createElement( )
createElementNS( )
createEntityReference( )
createProcessingInstruction( )
createTextNode( )
getElementById( )
getElementsByTagName( )
getElementsByTagNameNS( )
importNode( )
load( )
normalizeDocument( )
rename( )

Object-Specific Event Properties

None.


load(" URI")

Loads an XML file into the current Document object. Attempting to load other types of files (such as HTML) throws an exception. The server must be configured to send the file as the text/xml content type.


Returned Value

None.


Parameters


URI

A string of the URI to an external XML file.


See document.


The W3C DOM DocumentFragment object is essentially a context-free container of other DOM nodes. In other words, you can use all node properties and methods to assemble a sequence of element and text nodes outside of the document tree, but not influenced by the containment that the DocumentFragment provides. If you then append or insert the DocumentFragment node into the document tree, the DocumentFragment container disappears, and its node contents stand on their own within the context of their position in the document tree. The DocumentFragment isn't necessary to assemble content that is wrapped by an element node, because the element node can act as both the temporary container outside the document tree and the container after insertion into the document tree. But if one or both ends of a content segment end in a text node, the DocumentFragment node provides a transparent bucket to keep the string of nodes together until they are dropped into the document.

Create an empty DocumentFragment container via the document.createDocumentFragment( ) method. A DocumentFragment type of node inherits all properties and methods of the Node object (for inserting and appending other nodes you create), and adds nothing of its own other than its silent ability to hold other nodes. Do not confuse a DocumentFragment node with a string of tagged text that gets assigned to the innerHTML property of an element. The W3C DOM (as of Level 3) provides no such string-to-node-hierarchy conversion.


Object Model Reference

 documentFragmentNodeReference 


Object-Specific Properties

None.


Object-Specific Methods

None.


Object-Specific Events

None.


See document.


See document.


The DocumentTraversal object is defined in the Traversal module of the W3C DOM, where it defines the createNodeIterator( ) and createTreeWalker( ) methods. These methods (and the otherwise invisible DocumentTraversal interface) are blended into the document object so that scripts can access them as document.createTreeWalker( ) and createNodeIterator( ).


Reflects the DOCTYPE element, if one arrives to the browser as part of the document flow. The DocumentType object is its own node type in the W3C DOM, and, just as indicated in its position in a document's source code, exists outside of the content portion of the document tree. Access to this object in supported browsers is via the document.doctype property. If no DOCTYPE element exists in the file, the property returns null.

Properties of the DocumentType object expose individual pieces of the data within the DOCTYPE tag, whose structure is determined by SGML standards. The W3C DOM Level 2 specification provides placeholder properties for these pieces, and both Mozilla and Opera implement most of them to one degree or other. But it is clear from the DOM specification that work on aligning the two worlds is not complete.


Object Model Reference

 documentTypeNodeReference 


Object-Specific Properties

entities
internalSubset
name
notations
publicId
systemId

Object-Specific Methods

None.


Object-Specific Events

None.


Returns an array of nested Entity nodes within the DOCTYPE element. An Entity is formatted according to the following syntax (which would appear inside the DOCTYPE element's angle brackets):

 [<!ENTITY publicID "systemID">] 

Primarily applicable to XML documents.


Value

Array (technically, a NamedNodeMap data type) of Entity node object references.


Default

null


Returns a string value of the internal subset portion of the element.


Value

String.


Default

Empty string.


Returns a string value of the name portion of the element. The name is the first word that follows the DOCTYPE element's tag name. In the context of this book's subject, all HTML and XHTML documents show this value to be html. Note that although this object and property are implemented in IE 5/Macintosh, that browser returns the entire inner string value of the DOCTYPE element, starting with the html name.


Value

String.


Default

html


Returns an array of references to Notation nodes within the DOCTYPE element.


Value

Array (technically, a NamedNodeMap data type) of Notation node object references.


Default

null


Returns a string value of the public identifier portion of the element. This data reveals the type of DTD, as in "-//W3C//DTD XHTML 1.0 Strict//EN".


Value

String.


Default

Empty string.


Returns a string value of the system identifier portion of the element. This data typically reveals the URI of DTD, as in "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd".


Value

String.


Default

Empty string.


See document.


Some operations on W3C DOM objects can trigger errors, or, in the vernacular of JavaScript 1.5, throw exceptions, if something goes wrong. The W3C DOM defines an object that conveys a code number corresponding to a well-defined (if limited) list of exceptions. For example, if you attempt to append one text node as a child of another text node, the appendChild( ) method of such an operation throws an exception whose code number is 3. This number corresponds to the exception that signals an attempt to perform an illegal or logically impossible action on a DOM hierarchy (a text node can't have any child nodes).

The job of conveying the DOM exception information to a scripter falls to the hosting environment, rather than the DOM. Because JavaScript, starting with version 1.5, already has an exception handling mechanism, the task of blending the DOMException system with JavaScript exception handling fell first to Mozilla. The new mechanism permits different kinds of error objects to circulate through the exception handling operations, thus leaving the original system intact, while extending the mechanism to accommodate not only the W3C DOM DOMException object, but some browser-specific errors, as well. Processing of exceptions of all kinds continues to take place in the catch block of a try/catch construction, and all information about the exception is still passed as an object through a single parameter to the catch block.

Mozilla's DOM exception object (which embodies the W3C DOMException object) arrives at the catch block with a longer list of properties and methods associated with it than does an exception arising from other causes (e.g., trying to use a JavaScript variable that has not been initialized). The distinguishing property of a DOMException object, missing from the other types, is the code property. Moreover, any code value between 1 and 17 indicates an exception type known to the formal DOM specification through Level 3. Mozilla uses code numbers starting with 1000 for its list of browser-specific exceptions.

If you wish to process true W3C DOM exceptions along their own execution path, you can use a construction similar to the following (which allows for the DOMException list to grow to 999 in future iterations):

 try {     // your DOM-related statement goes here } catch(e) {     if (typeof e.code == "number") {         if (e.code < 1000) {             // process DOMException object here         } else {             // process Netscape DOM exception object here         }     } else {         // process language or other exceptions here     } } 

Of course, it is highly unlikely that exception details will be of benefit to users, but they are invaluable to you during development. For more on exception handling, see the error object in Chapter 5.


Object Model Reference

 errorObjectReference 


Object-Specific Properties

code


Object-Specific Methods

None.


Object-Specific Events

None.


Provides an integer corresponding to one of the defined DOM error types. The following table lists all code values, their constant equivalents, and examples of what kinds of problems throw the exception.

Code

Constant

Most likely cause

1

INDEX_SIZE_ERR

An integer offset parameter is out of the range of the target object.

2

DOMSTRING_SIZE_ERR

Property string value is too large for the hosting language.

3

HIERARCHY_REQUEST_ERR

Appending a child to a node not capable of children.

4

WRONG_DOCUMENT_ERR

Inserting a node created from a different document (without passing through the import process).

5

INVALID_CHARACTER_ERR

Assigning an identifier with an illegal character.

6

NO_DATA_ALLOWED_ERR

Assigning data to a node that doesn't allow data.

7

NO_MODIFICATION_ALLOWED_ERR

Assigning a value to a read-only property.

8

NOT_FOUND_ERR

Method parameter reference to a nonexistent node in the object's scope.

9

NOT_SUPPORTED_ERR

Invoking an XML-only method in an HTML document.

10

INUSE_ATTRIBUTE_ERR

Method parameter to an Attr node that already belongs to another element (without cloning the Attr first).

11

INVALID_STATE_ERR

Referencing a node that is not readable or writable.

12

SYNTAX_ERR

A slippery keyboard.

13

INVALID_MODIFICATION_ERR

Modifying the type of a node.

14

NAMESPACE_ERR

Namespace mismatch or malformed name.

15

INVALID_ACCESS_ERR

You can't go there.

16

VALIDATION_ERR

An attempted node operation would invalidate the Node.

17

TYPE_MISMATCH_ERR

The object is the wrong type.



Example

 if (e.code == e.INVALID_CHARACTER_ERR) {     // process for an illegal identifier character } 


Value

Integer


Default

Determined by error.


See implementation.


The DOMParser object transforms a string of XML markup into an XML document object (node type of 9). Browsers use this object internally, but the object is available to your scripts, if needed for other tasks. Mozilla exposes the parseFromBuffer( ) and parseFromStream( ) methods of the object, but some of the necessary parameters are data types not available to client-side scripts associated with web pages.


Object Model Reference

 new DOMParser( ) 


Object Properties

None.


Object Methods

parseFromString( )

Object-Specific Events

None.


parseFromString(" string", " MIMEType")

If successful, returns a document object whose content consists of the node tree specified in the string passed as a parameter.


Returned Value

document object.


Parameters


string

XML markup as a string value to be converted into a complete XML document.


MIMEType

A content type (as a string), such as text/xml, application/xml, or application/xhtml+xml.


The dt object reflects the dt element.


HTML Equivalent

<dt>


Object Model Reference

 [window.]document.getElementById("elementID") 


Object-Specific Properties

noWrap


Object-Specific Methods

None.


Object-Specific Events

None.


Specifies whether the browser should render the element as wide as is necessary to display a line of nonbreaking text on one line. Abuse of this attribute can force the user into a great deal of inconvenient horizontal scrolling of the page to view all of the content.


Example

 document.getElementById("wideItem").noWrap = "true"; 


Value

Boolean value: true | false.


Default

false


The W3C DOM Element object is from the Core module and represents the kind of element object you find in true XML documents. This node type inherits properties and methods from the root Node object and adds capabilities that let it act as a container of other nodes. Elements in HTML documents are of the HTMLDocument type, which inherits form this Element object. All properties and methods of the Element object are shared among all HTML element objects, as described at the beginning of this chapter. DOM Level 3 may include some additional properties and methods, which are not yet implemented in any browser.


Object Model Reference

 elementNodeReference 


Object-Specific Properties

tagName

Object-Specific Methods

getAttribute( )
getAttributeNode( )
getAttributeNodeNS( )
getAttributeNS( )
hasAttribute( )
hasAttributeNS( )
removeAttribute( )
removeAttributeNode( )
removeAttributeNS( )
setAttribute( )
setAttributeNode( )
setAttributeNodeNS( )
setAttributeNS( )

Object-Specific Event Properties

None.


The W3C DOM ElementCSSInlineStyle object is from the StyleSheets module and represents style settings assigned to an element through an explicit style attribute. The HTMLElement object (and thus, all elements in HTML documents) gets its style property as a result of its connection with the ElementCSSInlineStyle object (the object's only property is style, which is what HTML elements pick up). Scripts don't ever touch this object, but dynamic styles in the W3C DOM couldn't exist without it in the abstract model.


Object Model Reference

None.


Object-Specific Properties

None.


Object-Specific Methods

None.


Object-Specific Events

None.


A collection of all elements contained within a form. Collection members are sorted in source code order. Because each form element includes a type property, scripts can loop through all elements in search of elements of a specific type (e.g., all checkbox elements).


Object Model Reference

 document.forms[i].elements document.formName.elements 


Object-Specific Properties

length


Object-Specific Methods

item( )
namedItem( )
tags( )

Object-Specific Events

None.


Returns the number of form control elements in the collection.


Example

 var howMany = document.forms[0].elements.length; 


Value

Integer.


item( index[, subindex])


item( index)

Returns a single form control object or collection of form control objects corresponding to the element matching the index value (or, optionally in IE, the index and subindex values).


Returned Value

One form control object or collection (array) of form control objects. If there are no matches to the parameters, the returned value is null.


Parameters


index

When the parameter is a zero-based integer (per the W3C spec), the returned value is a single element that corresponds to the specified item in source code order. When the parameter is a string (IE), the returned value is a collection of elements whose id or name properties match that string.


subindex

In IE only, if you specify a string value for the first parameter, you can use the second parameter to specify a zero-based index that retrieves the specified element from the collection with id or name properties that match the first parameter's string value.


namedItem( IDOrName)

Returns a single form control object or collection of form control objects corresponding to the element matching the parameter string value.


Returned Value

One form control object or collection (array) of form control objects. If there are no matches to the parameters, the returned value is null.


Parameters


IDOrName

The string that contains the same value as the desired element's id or name attribute.


tags( tagName)

Returns a collection of objects (among all objects nested within the current collection) with tags that match the tagName parameter. Implemented in all IE, Safari, and Opera collections (see the all.tags( ) method), but redundant for collections of the same element type.


See abbr.


The embed object reflects the embed element. Although the W3C standards point to the object element as being the one to load external content that trigger things like media players, the Mozilla browser still prefers the embed element for such tasks. Properties and methods exposed by the player pass through the embed object so that scripts treat the embed object as if its list of scriptable powers is extended. Properties listed here are the properties that the element object, rather than an external controller, exposes to scripts.

Note that IE 5 for the Macintosh treats the embed object more like the object object, and exposes properties more closely aligned with an object or applet than an embed object. It's of little consequence, however, because IE/Mac does not let scripts communicate with external players or controllers.


HTML Equivalent

<embed>


Object Model Reference

 [window.]document.getElementById("elementID") [window.]document.embeds[i] 


Object-Specific Properties

align
height
hidden
name
palette
pluginspage
src
type
units
width

Object-Specific Methods

getSVGDocument( )

Object-Specific Events

None.


Defines the alignment of the element within its surrounding container. See the "Alignment Constants" at the beginning of Chapter 1 for the various meanings that different values bring to this property.


Example

 document.getElementById("audioPlayer").align = "center"; 


Value

Any of the alignment constants: absbottom | absmiddle | baseline | bottom | left | middle | right | texttop | top.


Default

left


Provide the height and width in pixels of the element as set by the tag attributes. Changing the values does not necessarily change the actual rectangle of the applet after it has loaded.


Example

 var controllerHeight = document.embeds["audioPlayer"].height; 


Value

Integer.


Default

0


Specifies whether the embedded data's plugin control panel appears on the screen. Changes to this property force the page to reflow its content to make room for the plugin control panel or close up space around a newly hidden panel.


Example

 document.embeds["jukebox"].hidden = true; 


Value

Boolean value: TRue | false.


Default

false


Reflects the name attribute value of the element's tag.


Example

 document.embeds["myEmbed"].name = "tunes"; 


Value

Case-sensitive identifier that follows the rules of identifier naming: it may contain no whitespace, cannot begin with a numeral, and should avoid punctuation except for the underscore character.


Default

None.


Returns the setting of the palette attribute of the embed element object.


Value

String.


Default

None.


Indicates the URL for downloading and installing the plugin necessary to run the current object's embedded data.


Value

A complete or relative URL as a string.


Default

None returned, but Internet Explorer has its own default URL for plugin information.


Indicates URL of the external content file associated with the object. Although some controllers may respond to changes of this attribute, it is more reliable to load a different file into the controller via its own loading method or property.


Example

 document.embeds["myEmbed"].src = "tunes/dannyboy.wav"; 


Value

Complete or relative URL as a string.


Default

None.


Indicates the MIME type of the external data assigned to the element's type attribute.


Example

 var dataMIME = document.embeds["myEmbed"].type; 


Value

Any valid MIME type name as a quoted string, including the type and subtype portions delimited by a forward slash.


Default

None.


Specifies the unit of measure for the height and width dimensions of the element. Internet Explorer appears to treat all settings as pixels.


Example

 document.getElementById("myEmbed").units = "ems"; 


Value

Any of the following case-insensitive constants (as a string): pixels | px | em.


Default

pixels


See height.


Returns a reference to the document object containing the XML data within the .svg document. You can then invoke W3C DOM Core methods on the object.


Returned Value

Reference to the .svg document object loaded into the embed element.


Parameters

None.


A collection of all embed elements contained in the current element. Collection members are sorted in source code order. Internet Explorer lets you use array notation or parentheses to access a single element in the collection.


Object Model Reference

 document.embeds 


Object-Specific Properties

length


Object-Specific Methods

item( )
namedItem( )
tags( )

Returns the number of elements in the collection.


Example

 var howMany = document.embeds.length; 


Value

Integer.


item( index[, subindex])


item( index)

Returns a single embed element object or collection of embed element objects corresponding to the element matching the index value (or, optionally in IE, the index and subindex values).


Returned Value

One embed element object or collection (array) of embed element objects. If there are no matches to the parameters, the returned value is null.


Parameters


index

When the parameter is a zero-based integer (per the W3C spec), the returned value is a single element that corresponds to the specified item in source code order. When the parameter is a string (IE), the returned value is a collection of elements whose id or name properties match that string.


subindex

In IE only, if you specify a string value for the first parameter, you can use the second parameter to specify a zero-based index that retrieves the specified element from the collection with id or name properties that match the first parameter's string value.


namedItem( IDOrName)

Returns a single embed element object or collection of embed element objects corresponding to the element matching the parameter string value.


Returned Value

One form control object or collection (array) of form control objects. If there are no matches to the parameters, the returned value is null.


Parameters


IDOrName

The string that contains the same value as the desired element's id or name attribute.


tags( tagName)

Returns a collection of objects (among all objects nested within the current collection) with tags that match the tagName parameter. Implemented in all IE, Safari, and Opera collections (see the all.tags( ) method), but redundant for collections of the same element type.


The Entity object (one of the node types) is an abstract representation in the W3C DOM of an element that is treated in an XML document as a storage unit. Some entities define a name that can be used by other elements (including other entities) as a shortcut reference to the information stored in the entity. This latter reference is represented in the W3C DOM as an EntityReference node type. You can see many examples of Entity elements in DTD documents. For more details on the application of Entity elements, see the XML specification at http://www.w3.org/TR/REC-xml.


The event object contains information about a user- or system-generated event. But there are three different kinds of event objects, one for each of the event object models deployed in browsers: IE for Windows, Navigator 4, and the W3C DOM (as implemented in Mozilla, Safari, and Opera). IE 5 for Macintosh implements a hybrid of the IE for Windows and W3C DOM version. See Online Section VI for examples of processing events in a cross-browser environment. It is rare that an event object property applies to more than one of the event models, so pay special attention to the browser compatibility listings for each of the following properties.

The W3C DOM event object is more complex in some ways due to the object-oriented nature of the underlying W3C DOM Event object structure. Rather than being an all-encompassing object (as the IE event object is), the W3C DOM event object exposes different sets of properties and methods depending on the classification of event. All event classes share the properties and methods of the W3C DOM root Event object. But actual event object instances belong to one of the Event object's subclasses (and sometimes, sub-subclasses). These subclasses are known as UIEvent (so-called user interface events such as DOMFocusIn), MouseEvent (including the well-known mouse events), MutationEvent (events that signal a scripted change to the node structure of the document), and, in DOM Level 3, TextEvent (typing-related events) and KeyboardEvent (pressing keyboard keys). Prior to the DOM Level 3 keyboard-related events being finalized, Mozilla and other W3C DOM browsers implemented a temporary keyboard events classification under the name KeyEvent, which is a subclass of UIEvent, although it borrows some MouseEvent properties for scripting convenience.

By and large, this functional division of objects won't impact your W3C DOM event processing because an event listener function for a particular kind of event will be looking for properties associated with that event. The event class is of little concern. Still, it is instructive to see the way event object properties and methods cascade through this object-oriented structure. The following table illustrates the distribution of properties (some of them unique to Mozilla) among W3C DOM event classes.

 

Event

UI

Mouse

Keyboard

Text

Mutation

Event properties

      

bubbles

·

·

·

·

·

·

cancelable

·

·

·

·

·

·

cancelBubble[a]

 

·

·

·

·

 

currentTarget

·

·

·

·

·

·

eventPhase

·

·

·

·

·

·

originalTarget

·

·

·

·

 

·

target

·

·

·

·

·

·

timeStamp

·

·

·

·

·

·

type

·

·

·

·

·

·

UIEvent properties

      

detail

 

·

·

·

·

 

view

 

·

·

·

·

 

MouseEvent properties

      

altKey

  

·

·

·

 

button

  

·

   

clientX

  

·

   

clientY

  

·

   

ctrlKey

  

·

·

·

 

metaKey

  

·

·

·

 

relatedTarget

  

·

   

screenX

  

·

   

screenY

  

·

   

shiftKey

  

·

·

·

 

KeyboardEvent properties

      

charCode[b]

   

·

  

isChar[b]

   

·

  

keyCode[b]

   

·

  

rangeOffset[b]

   

·

  

rangeParent[b]

   

·

  

TextEvent property

      

data

    

·

 

MutationEvent properties

      

attrChange

     

·

attrName

     

·

newValue

     

·

prevValue

     

·

relatedNode

     

·

[a]
[b]


[a] IE property implemented in Mozilla for cross-browser convenience.

[b] Implemented in Mozilla and Safari in lieu of final W3C DOM Level 3 keyboard events specification.

And the following table illustrates the distribution of methods among W3C DOM event classes.

 

Event

UI

Mouse

Keyboard

Text

Mutation

Event methods

      

initEvent( )

·

·

·

·

·

·

getPreventDefault( )

·

·

·

·

 

·

preventDefault( )

·

·

·

·

·

·

stopPropagation( )

·

·

·

·

·

·

UIEvent methods

      

initUIEvent( )

 

·

    

MouseEvent methods

      

initMouseEvent( )

  

·

   

KeyboardEvent methods

      

initKeyEvent( )

   

·

  

TextEvent methods

      

initTextEvent( )

    

·

 

MutationEvent methods

      

initMutationEvent( )

     

·


The event object in Mozilla also implements the properties of the old Navigator 4 static Event object, and it inherits an enormous list of W3C DOM TextEvent object constants that represent nonalphanumeric keyboard key codes (which have constant names like eventObject.DOM_VK_PAGE_UP). In the meantime, however, these keyboard constants have been dropped from the proposed DOM Level 3 Events module. Therefore, if you explore the properties of an event object in Mozilla, you will continue to see these constants represented. A list of properties for the Navigator 4 static Event object appears in the Event object discussion following the current foray through an instance of an event.

As described in detail throughout Online Section VI, you must use different script techniques to obtain a reference to an event object in the IE and W3C DOM event models. Once you have that reference, you are well on your way to equalizing event processing across browsers. The example fragments that follow assume that previous script statements have obtained a reference to the browser-specific event object (usually shown in the example as stored in a variable called evt).


Object Model Reference


NN and W3C DOM

eventObj


IE

[window.]event


Object-Specific Properties

altKey
altLeft
attrChange
attrName
behaviorCookie
behaviorPart
bookmarks
boundElements
bubbles
button
cancelable
cancelBubble
charCode
clientX
clientY
contentOverflow
ctrlKey
ctrlLeft
currentTarget
data
dataFld
dataTransfer
detail
eventPhase
explicitOriginalTarget
fromElement
isChar
isTrusted
keyCode
layerX
layerY
metaKey
modifiers
newValue
nextPage
offsetX
offsetY
originalTarget
pageX
pageY
prevValue
propertyName
qualifier
rangeOffset
rangeParent
reason
recordset
relatedNode
relatedTarget
repeat
returnValue
screenX
screenY
shiftKey
shiftLeft
srcElement
srcFilter
srcUrn
target
timeStamp
toElement
type
view
wheelDelta
which
x
y

Object-Specific Methods

getPreventDefault( )
initEvent( )
initKeyEvent( )
initMouseEvent( )
initMutationEvent( )
initUIEvent( )
preventDefault( )
stopPropagation( )

Object-Specific Event Properties

None.


Returns true if the left or right Alt key is down at the time the event fired.


Example

 if (evt.altKey) {     //handle case of Alt key down } 


Value

Boolean value: true | false.


Default

false


Returns true if the left Alt key is down at the time the event fired.


Example

 if (evt.altLeft) {     //handle case of left Alt key down } 


Value

Boolean value: true | false.


Default

false


Returns an integer code corresponding to the type of change made to an Attr node as the result of a DOMAttrModified event type of W3C DOM mutation event. Every mutation event object has three constants that also correspond to the integer values, which you can use to make more verbose, but easier-to-read script comparisons for DOMAttrModified event processing. The values and constants are shown in the following table. Although Safari implements the property, it does not support the event type that triggers events with this property. Manually created mutation events, however, have the property.

Value

Constant

Description

1

evtObj.MODIFICATION

Changed value of existing Attr node

2

evtObj.ADDITION

The Attr node was added to the document tree

3

evtObj.REMOVAL

The Attr node was removed from the document tree



Example

 if (evt.attrChange == evt.MODIFICATION) {     // do post-processing of attribute value change } 


Value

Integer value: 1 | 2 | 3.


Default

None.


Returns a string version of the name of an Attr node affected by a DOMAttrModified event type of W3C DOM mutation event. Although Safari implements the property, it does not support the event type that triggers events with this property. Manually created mutation events, however, have the property.


Example

 var changedAttr = evt.attrName; 


Value

String value.


Default

Empty string.


These properties are returned by the event object in IE 6 and 7 (with values 0, 0, null, and the empty array, respectively), but Microsoft does not document them. Perhaps they will be supported and implemented in a future version.


Returns Boolean true if the default behavior of the event is to allow the event to bubble through the element hierarchy.


Example

 if (evt.bubbles) {     // handle case of the event bubbling } 


Value

Boolean value: TRue | false.


Default

Event type-specific.


Inidicates which mouse button was pressed to trigger the mouse event. Be aware that the typical Macintosh has only a one-button mouse. Also, if you want to intercept the right-click context menu in IE/Windows, use the oncontextmenu event handler.

A significant discrepancy exists between the IE and W3C DOM implementations with respect to the numbers returned for this property. The W3C DOM, as implemented in Mozilla and others, specifies a value of zero to indicate the left (primary) button. IE for Windows supports additional values for mouse button combinations.


Example

 if (evt.button == 2) {     // handle event for right button } 


Value

Integer value according to the following table.

Button(s)

IE

W3C DOM

No button

0

null

Left (primary)

1

0

Middle

4

1

Right

2

2

Left + Right

3

n/a

Left + Middle

5

n/a

Right + Middle

6

n/a

Left + Middle + Right

7

n/a



Default

0


Returns Boolean true if the event is of the type that can have its default behavior on the target element cancelled via the preventDefault( ) method.


Example

 if (evt.cancelable ) {     evt.preventDefault( ); } 


Value

Boolean: true | false.


Default

Event type-specific.


Specifies whether the event should propagate (bubble) up the element container hierarchy. You usually only need to set this property to true to override the default behavior and prevent the event from going any further. Other browsers implements this IE property for convenience. The W3C DOM equivalent is the stopPropagation( ) method of the event object.


Example

 evt.cancelBubble = true; 


Value

Boolean: TRue | false.


Default

false


Returns an integer corresponding to the Unicode value of the character generated by the key that fired the event. The character code is different from the key code, as the character code distinguishes between upper- and lowercase letters (for example, 97 for "a" and 65 for "A"), whereas the keyCode value is the same for that key, regardless of the character created from it. This property generally contains a value only for onkeypress events; the value is zero for keydown and keyup events. For the IE equivalent, see the keyCode property.

(The W3C DOM Level 3 Events module does not offer an exact substitute, but suggests the data property will convey the Unicode value for a character, such as the string U+0041 for the capital letter A.)


Example

 if (evt.charCode > 96 && evt.charCode < 123) {     evt.target.value += String.fromCharCode(evt.charCode - 32);     evt.preventDefault( ); } 


Value

Integer.


Default

Event-specific.


Indicate the horizontal (x) and vertical (y) coordinate of the mouse at the moment the current event fired. These coordinates are relative to the viewable document area of the browser window or frame. To convert these coordinates to the document's in IE, be sure to add the body element's scroll values (or html element's scroll values in IE 6 and 7 standards-compatible mode). For Mozilla, Safari, and Opera, the pageX and pageY properties provide coordinates in the document's space.


Example

 if ((evt.clientX >= 10 && evt.clientX <= 20) && (evt.clientY >= 50 && evt.clientY <= 100)) {     // process code for click in hot zone bounded by 10,50 and 20,100 } 


Value

Integer of pixel values.


Default

None.


Returns Boolean TRue if as-yet unrendered content requires a new layout rectangle to handle the overflow content. The property applies only to the onlayoutcomplete event if you deploy custom print or print preview templates. For more on the C++ programming required for such templates, visit http://msdn.microsoft.com/library/default.asp?url=/workshop/browser/hosting/printpreview/reference/reference.asp.


Value

Boolean: true | false.


Default

false


Returns true if the left or right Control key was pressed at the instant the event fired. See Online Section VI for testing for this key in cross-browser event handling code.


Example

 if (evt.ctrlKey) {     // process for Control key being down } 


Value

Boolean value: true | false.


Default

false


Returns TRue if the left Control key was pressed at the instant the event fired.


Example

 if (evt.ctrlLeft) {     // process for left Control key being down } 


Value

Boolean value: TRue | false.


Default

false


Returns a reference to the node whose event listener is currently processing the event. Allows a function to know whether it is invoked from the actual target node or a different node during event propagation.


Example

 if (evt.currentTarget.nodeType == 1) {     // process at element level for possible text node target } 


Value

Reference to a node in event propagation hierarchy.


Default

Reference to event target.


Provides accessory data associated with the Navigator 4-only dragdrop event. The data property returns the URL of the item being dropped onto the window or frame. This property name may be adopted for the TextEvent in the W3C DOM Level 3 Events module.


Example

 var srcDoc = evtObj.data; 


Value

String.


Default

None.


Used with IE data binding, the dataFld property holds the name of the data source object's field associated with the column of the HTML table. This property contains a value after an oncellchange event in a table generated via data binding.


Value

String.


Default

Empty string.


Returns a reference to the dataTransfer object to facilitate moving customized data between source and destination elements during a drag-and-drop operation. See the dataTransfer object for details of its usage.


Value

Reference to dataTransfer object.


Default

None.


Returns an integer conveying event type-specific additional information. For mouse button events, the number indicates how many times the user clicked the mouse on the same coordinate position as the previous click without moving the cursor away from the location. Moving the cursor resets the counter to zero in preparation for the next press and release of the mouse button. For a DOMActivate event type, the detail property returns 1 for activation by a simple user action (click or tab), and 2 for a more complex action (a double-click).


Example

 if (evt.type == "click" && evt.detail > 5) {     alert("Relax, dude!"); } 


Value

Integer.


Default

Event-type specific.


Returns an integer conveying whether the event listener is processing the event while in the capture phase, at the event target, or in the bubbling phase. W3C DOM event objects also implement plain-language constants corresponding to the three values.


Example

 if (evt.eventPhase == evt.AT_TARGET) {     // process event listener from the event target } 


Value

Integer value from the following table.

Value

Constant

1

eventObjectReference.CAPTURING_PHASE

2

eventObjectReference.AT_TARGET

3

eventObjectReference.BUBBLING_PHASE



Default

2


Returns a reference to the node that received the actual event. Because the target property changed in Mozilla 1.4 to point to an element object (rather than, say, a text node contained by an element), the explicitOriginalTarget property provides access to the precise node that received the event. There is a technical difference between explicitOriginalTarget and originalTarget that concerns what is known as anonymous content that is more of an issue in XUL development for Mozilla browsers. In an HTML document, the two properties reference the same node.


Example

 if (evt.explicitOriginalTarget !== evt.target) {     ... } 


Value

Element or node object reference.


Default

None.


Returns a reference to the object where the cursor was located just prior to the mouseover or mouseout event.


Example

 if (evt.fromElement.id == "lowerLevel") {     ... } 


Value

Element object reference.


Default

None.


Returns TRue if the keyboard event is from a character key. In practice Mozilla returns false for all keys, including function keys. Use onkeydown or onkeyup event handlers to process noncharacter keys.


Value

Boolean value: true | false.


Default

true


Returns TRue if the event was generated as the result of a user action. Events artifically created by script (e.g., via the document.createEvent( ) mechanism) have this event object property set to false.


Value

Boolean value: true | false.


Default

true


You'll find different handling of this property among mainstream browsers for the keypress event, but the all browsers treat the keyCode property the same way for onkeydown and onkeyup event handlers. For these events, the keyCode property returns the code associated with the keyboard key, irrespective of the character that might be generated by that key. On a typical Latin character set keyboard, the A key generates the code 65. Modifier keys generate their own events and codes as they are pressed and released.

For the onkeypress event, IE, Safari, and Opera return a significant value, corresponding to the ASCII integer value of the actual character displayed in a text box by typing the character (e.g., 65 for "A" and 97 for "a"). The equivalent property in Mozilla for the keypress event is charCode. See Online Section VI about processing keyboard events.


Example

 if (evt.keyCode == 65) {     ... } 


Value

Integer.


Default

None.


Provide the horizontal (x) and vertical (y) coordinate of the mouse at the moment the current event fired. These coordinates are relative to the containing layer. If no layers or positionable elements have been defined, the default layer of the base document is used as a reference point, thus equivalent to the pageX and pageY properties. In Mozilla, these properties are measured relative to the element's own rectangular space for text and password input elements, textarea elements, and select elements.


Example

 if ((evt.layerX >= 10 && evt.layerX <= 20) && (evt.layerY >= 50 && evt.layerY <= 100)) {     // process code for click in hot zone bounded by 10,50 and 20,100 } 


Value

Integer of pixel values.


Default

None


Returns true if the keyboard's Meta key (Command key on the Macintosh keyboard) was pressed at the instant the event fired.


Example

 if (evt.metaKey) {     // process for meta key being down } 


Value

Boolean value: true | false.


Default

false


Provides an integer that represents the keyboard modifier key(s) being held down at the time the Navigator 4-only event fired. You can use the & operator with a series of static Event object constants to find out whether a particular modifier key was pressed. See Online Section VI.


Example

 var altKeyPressed = evt.modifiers & Event.ALT_MASK; 


Value

Integer.


Default

0


Return a string with the new and previous values (respectively) of data associated with DOMAttrModified and DOMCharacterDataModified event types of the W3C DOM mutation events class. This information could be useful for creating an undo buffer for changes to an element's attribute or the content of a CharacterData node.


Example

 undoAttrBuffer = {attrNode:evt.relatedNode, oldVal:evt.prevValue}; 


Value

String value.


Default

Empty string.


Returns a string indicating whether the next page of a custom print template will appear on a left- or right-facing page. For more on the C++ programming required for templates, visit http://msdn.microsoft.com/library/default.asp?url=/workshop/browser/hosting/printpreview/reference/reference.asp.


Value

String constant: left | right | (empty string).


Default

Empty string.


Provide the left and top coordinates of the mouse pointer relative to the containing element (exclusive of padding, borders, or margins) when the event fired. You can determine the containing element via the offsetParent property. See the "About client- and offset- Properties at the beginning of this chapter for information on offset measurement anomalies in Internet Explorer.


Example

 if (evt.offsetX <= 20 && evt.offsetY <=40) {     ... } 


Value

Integer pixel count.


Default

None.


Returns a reference to a node that Mozilla internally treats as the genuine first target of the event. By and large, this information isn't helpful to DHTML scripting, because it dives into the internal construction of certain elements (e.g., in early versions of Mozilla, an input element of type text has a div element nested inside of it, but the DOM node tree does not see the div element as a child node of the input element). For many events and event targets, the target and originalTarget properties reference the identical node, but when an element contains a text node, the target property is internally set to the text node's parentthe containing element.


Value

Node object reference


Default

Element-specific.


Provide the left and top coordinates of the element's content relative to the top-left corner of the page area when the event fired. The measurements ignore any scrolling of the page.


Example

 if (evt.pageX <= 20 && evt.pageY <=40) {     ... } 


Value

Integer pixel count.


Default

None.


See newValue.


Returns a string containing the name of the object property that changed during an onpropertychange event. For other event types, the value is an empty string. If the changed property is a property of a property (e.g., a property of an element's style property), the returned value shows the "dot" version, such as style.color.


Example

 if (evt.propertyName.indexOf("style") == 0) {     // perform further processing on a changed style } 


Value

String property name.


Default

Empty string.


For use with IE data binding events (such as ondatasetcomplete). Returns a string value signifying a data source member, which may then be used as a parameter to access a data source's named recordset. Consult the Microsoft documentation for the Data Source Object you use to see if it provides qualifier data.


Value

String.


Default

Empty string.


Returns an integer of the character offset within a node that the Mozilla DOM considers a potential Range endpoint. The reference to the node is found in the associated rangeParent property of the event object. These two values can be passed as parameters to W3C DOM Range object methods for setting a start or endpoint. Thus, a mousedown event listener could establish the start point of a range, while a mouseup event listener function could set the endpointboth functions feeding rangeParent and rangeOffset values to the Range object methods.


Example

 var rng; function processMouseDown(evt) {     rng = document.createRange( );     rng.setStart(evt.rangeParent, evt.rangeOffset); } 


Value

Integer.


Default

0


Returns a reference to a document tree node that would be a suitable start or endpoint for a W3C text range. Use in concert with the rangeOffset property.


Example

 function processMouseUp(evt) {     rng.setEnd(evt.rangeParent, evt.rangeOffset); } 


Value

Reference to a node.


Default

None.


Returns a code associated with an ondatasetcomplete event signifying whether the IE data binding data transfer was successful or, if incomplete, whether the transfer stopped due to an error or a stoppage by the client or user. This property must be examined in an event handler for the ondatasetcomplete event. In IE 4, the property is read-only. Although IE 5/Mac includes this property of the event object, it does not implement the associated event.


Example

 if (evt.reason == 2) {     alert("An error occurred during the most recent update."); } 


Value

One of three possible integer values:


0

Transfer was successful


1

Transfer aborted


2

An error halted the transfer


Default

None.


Returns a reference to an IE data binding recordset object associated with a data-related event.


Value

Object reference.


Default

None.


Returns a reference to a node that is affected by the action that triggers some W3C DOM mutation events. This provides a more direct route to a node that is impacted by the event, according to the following table.

Mutation event type

eventObj.relatedNode reference

DOMNodeInserted

Parent node of inserted node

DOMNodeRemoved

Original parent node of removed node

DOMAttrModified

Attr node


For other mutation event types, the property returns null; for other event classes, the property returns undefined.


Example

 var newParent = evt.relatedNode; 


Value

Reference to a node, null, or undefined.


Default

None.


Returns a reference to a rendered node in the document tree that was the previous or next target for events, depending on the event type. For a mouseover event type, the relatedTarget property refers to the node from which the cursor arrived; for a mouseout event, the relatedTarget property refers to the node to which the cursor departed. The corresponding IE functionality is in the fromElement and toElement properties of the IE event object.


Example

 var beenThere = evt.relatedTarget; 


Value

Reference to a node.


Default

None.


For an onkeydown event only, returns Boolean TRue if the key has been down long enough to enter auto-repeat mode. You can prevent auto-repeated keys from being entered into a field with the following example.


Example

 function handleKeyDown( ) {     if (evt.repeat) {         evt.returnValue = false;     } } 


Value

Boolean value: true | false.


Default

false


Provides the value to be returned to the event's source element to allow or prohibit the element's default action connected with the event. If you set event.returnValue to false, the element does not carry out its normal operation, such as navigating to a link or submitting the form. This property does not influence an actual value you may wish to return from an event handler function.


Example

 evt.returnValue = false; 


Value

Boolean value: true | false, or undefined.


Default

undefined


Provide the horizontal and vertical pixel coordinate points where the cursor was located on the video screen when the event occurred. The top-left corner of the screen is point 0,0. There is no particular coordination with the browser window or document, unless you have positioned the window and know where the active window area is in relation to the screen.


Example

 if (evt.screenX < 5 || evt.screenY < 5) {     alert("You\'re too close to the edge!"); } 


Value

Any positive integer or zero.


Default

0


Returns true if the left or right Shift key was pressed at the instant the event fired.


Example

 if (evt.shiftKey) {     // process for Shift key being down } 


Value

Boolean value: TRue | false.


Default

false


Returns true if the left Shift key was pressed at the instant the event fired.


Example

 if (evt.shiftLeft) {     // process for left Shift key being down } 


Value

Boolean value: true | false.


Default

false


Refers to the element object that initially received the current event. This property is convenient in switch constructions for an event handler function that handles the same event type for a number of different elements. The corresponding property for the W3C DOM is target.


Example

 switch (evt.srcElement.id) {     case "myDIV":         ...     ... } 


Value

Element object reference.


Default

None.


Refers to the filter object that fired an onfilterchange event.


Value

Filter object reference.


Default

None.


String of the URN of an attached behavior that fired an event.


Value

String.


Default

null


Refers to the object that is the intended destination of the current event. In early versions of Mozilla and Safari prior to version 2.02, the target property can refer to a text node, even if the event handler is defined for the element that surrounds the text node. Your event processing for such a scenario must take the nodeType into account to equalize the reference to the surrounding element for both IE and Navigator. Beginning with version 1.4, Mozilla's event target is automatically redirected to a text node's containing element. If you need a reference to the receiving text node in Mozilla, use originalTarget or explicitOriginalTarget.


Example

 var elem = (evt.target) ? evt.target : evt.srcElement; 


Value

Node object reference.


Default

None.


Provides an integer signifying a milliseconds value you can use as a relative indicator of when an event occurred. Although the W3C DOM suggests the value should be the time since 1 January 1970 (the Java and JavaScript epoch), you cannot rely on that value. But you can compare the timeStamp property value for two events to derive the elapsed time between events.


Example

 var clickTime = evt.timeStamp; 


Value

Integer.


Default

Current timestamp.


Returns a reference to the element object to which the cursor has moved that triggered the onmouseout event.


Example

 if (evt.toElement.id == "upperLevel") {     ... } 


Value

Element object reference.


Default

None.


Indicates the type of the current event (without the "on" prefix). Values are all lowercase.


Example

 if (evt.type == "change") {     ... } 


Value

Any event name (without the "on" prefix) as a string.


Default

None.


Returns a reference to the W3C DOM view (i.e., the window or frame object in Mozilla's implementation, and the document.defaultView in Safari and Opera) in which the event occurred.


Example

 var whichWin = evt.view; 


Value

Reference to a window type of object.


Default

Current window.


Returns an integer indicating which direction the user rolled the mouse wheel (for a mouse equipped with a wheel) during an onmousewheel event. A positive value means the user rolled the wheel toward the screen; a negative value means the opposite direction.


Example

 if (evt.wheelDelta > 0) {     ... } 


Value

Integer, typically 120 or -120.


Default

None.


Returns a value relevant to the type of event. For mouse events, the property value is an integer indicating which mouse button was used (1 is the left button; 3 is the right button). For keyboard events, the property value is an integer of the keyboard character ASCII code. This property survives in Mozilla and elsewhere as a carryover from the Navigator 4 event model. Use the button, charCode, and keyCode properties if you no longer need to support Navigator 4.


Example

 if (evt.which == 65) {     ... } 


Value

Integer.


Default

None.


Return the horizontal and vertical pixel coordinates of the mouse pointer at the time the event occurred. For all but relative-positioned elements, the coordinate system is the body element (or html element in IE 6 and later standards-compatible mode). If the event occurs inside a relative-positioned element's rectangle, the coordinate system is limited to that element's space (the element's top left corner being 0,0). A value of -1 is returned if the pointer was outside of the document area of the browser window.


Example

 if (evt.x < 20 && evt.y < 30) {     ... } 


Value

Integer.


Default

None.


Returns Boolean TRue if the preventDefault( ) method has been invoked for the current event object. Essentially lets a script inquire about the prevent-default state. This method is a Mozilla extension to the W3C DOM events module.


Returned Value

Boolean value: TRue | false.


Parameters

None.


initEvent(" eventType", bubblesFlag, cancelableFlag)

Performs the minimum initialization required on an event object that is generated by document.createEvent( ). After a script-generated event is initialized, it may be used as a parameter to a node's dispatchEvent( ) method.


Returned Value

None.


Parameters


eventType

String identifier for the event's type, such as click, mousedown, keypress, DOMAttrModified, and so on. You should limit the event type to those suitable to the classification of the event you created (e.g., a click event type for document.createEvent("MouseEvent")).


bubblesFlag

Boolean value (true | false) determining whether the event's default propagation behavior is to bubble.


cancelableFlag

Boolean value (TRue | false) determining whether the event's default action may be prevented via the preventDefault( ) method.


initKeyEvent(" eventType", bubblesFlag, cancelableFlag, view, ctrlKeyFlag, altKeyFlag, shiftKeyFlag, metaKeyFlag, keyCode, charCode)

Initializes a newly created event object with a complete set of property values associated with any keyboard event. Mozilla implemented its own version of the keyboard event initialization method because the W3C DOM had not yet addressed keyboard events. Safari has also adopted it for now. All parameters must be present, and must be set to default values (such as false for Boolean key flags or zero for integer code numbers) if the values are not significant for the event type.


Returned Value

None.


Parameters


eventType

String identifier for the event's type: keydown, keypress, keyup.


bubblesFlag

Boolean value (true | false) determining whether the event's default propagation behavior is to bubble.


cancelableFlag

Boolean value (TRue | false) determining whether the event's default action may be prevented via the preventDefault( ) method.


view

Reference to the window or frame object (Mozilla) or document.defaultView (Safari) in which the dynamically generated event is supposed to have occurred.


ctrlKeyFlag

Boolean value (true | false) of the Control key state for this event.


altKeyFlag

Boolean value (true | false) of the Alt key state for this event.


shiftKeyFlag

Boolean value (TRue | false) of the Shift key state for this event.


metaKeyFlag

Boolean value (true | false) of the Meta key(e.g., Macintosh Command key) state for this event.


keyCode

Integer key code for this event.


charCode

Integer character code for this event.


initKeyEvent(" eventType", bubblesFlag, cancelableFlag, view, keyIdentifier, keyLocation, modifierList)

Initializes a newly created event object with a complete set of property values associated with any keyboard event. Parameters for this method may change because as of this writing, the Level 3 Events module is not finalized. All parameters must be present, and must be set to default values (such as false for Boolean key flags or zero for integer code numbers) if the values are not significant for the event type.


Returned Value

None.


Parameters


eventType

String identifier for the event's type: keydown, keypress, keyup.


bubblesFlag

Boolean value (true | false) determining whether the event's default propagation behavior is to bubble.


cancelableFlag

Boolean value (true | false) determining whether the event's default action may be prevented via the preventDefault( ) method.


view

Reference to the window or frame object in which the dynamically generated event is supposed to have occurred.


keyIdentifier

String value denoting which key the event is simulating. Values come from a long list of constant values (e.g., F1 and Home) and Unicode character references (e.g., U+0041). A complete list is available at http://www.w3.org/TR/DOM-Level-3-Events/events.html#Events-KeyboardEvent-keyIdentifier.


keyLocation

Integer indicating which section of the keyboard is to be simulated for the event: 0 (standard); 1 (left); 2 (right); 3 (numeric keypad).


modifierList

A space-delimited string of modifier keys to be signaled as being pressed during this simulated event. Common values include: Alt, AltGraph, CapsLock, Control, Meta, NumLock, Scroll, Shift.


initMouseEvent(" eventType", bubblesFlag, cancelableFlag, view, detailVal, screenX, screenY, clientX, clientY, ctrlKeyFlag, altKeyFlag, shiftKeyFlag, metaKeyFlag, buttonCode, relatedTargetNodeRef)

Initializes a newly created event object with a complete set of property values associated with any mouse event. All parameters must be present, and must be set to default values (such as false for Boolean key flags, zero for integer values, or null for a node reference) if the values are not significant for the event type.


Returned Value

None.


Parameters


eventType

String identifier for the event's type, such as click, mousedown, mousemove, mouseout, mouseover, mouseup.


bubblesFlag

Boolean value (true | false) that determines whether the event's default propagation behavior is to bubble.


cancelableFlag

Boolean value (true | false) that determines whether the event's default action may be prevented via the preventDefault( ) method.


view

Reference to the window or frame object in which the dynamically generated event is supposed to have occurred.


detailVal

Integer code for detail data associated with the event.


screenX

Integer for horizontal screen coordinate.


screenY

Integer for vertical screen coordinate.


clientX

Integer for horizontal browser window coordinate.


clientY

Integer for vertical browser window coordinate.


ctrlKeyFlag

Boolean value (TRue | false) of the Control key state for this event.


altKeyFlag

Boolean value (true | false) of the Alt key state for this event.


shiftKeyFlag

Boolean value (true | false) of the Shift key state for this event.


metaKeyFlag

Boolean value (TRue | false) of the Meta key(e.g., Macintosh Command key) state for this event.


buttonCode

Integer button code for this event.


relatedTargetNodeRef

Reference to node receiving the previous or next mouse event.


initMutationEvent(" eventType", bubblesFlag, cancelableFlag, relatedNodeRef, prevValue, newValue, attrName, attrChangeCode)

Initializes a newly created event object with a complete set of property values associated with any mutation event. All parameters must be present, and must be set to default values (such as false for Boolean key flags or zero for integer code numbers) if the values are not significant for the event type.


Returned Value

None.


Parameters


eventType

String identifier for the event's type: DOMAttrModified, DOMCharacterDataModified, DOMNodeInserted, DOMNodeInsertedIntoDocument, DOMNodeRemoved, DOMNodeRemovedFrom-Document, DOMSubtreeModified.


bubblesFlag

Boolean value (TRue | false) determining whether the event's default propagation behavior is to bubble.


cancelableFlag

Boolean value (true | false) determining whether the event's default action may be prevented via the preventDefault( ) method.


relatedNode

Reference to a node associated with the event. Applicable only to DOMNodeInserted, DOMNodeRemoved, DOMAttrModified event types.


prevValue

String of previous value for an Attr or CharacterData node. Applicable only to DOMAttrModified and DOMCharacterDataModified event types.


newValue

String of new value for an Attr or CharacterData node. Applicable only to DOMAttrModified and DOMCharacterDataModified event types.


attrName

String of the name of an Attr node. Applicable only to the DOMAttrModified event type.


attrChangeCode

Integer for the code corresponding to the type of change the event simulates. Applicable only to the DOMAttrModified event type.


initUIEvent(" eventType", bubblesFlag, cancelableFlag, view, detailVal)

Initializes a newly created event object with a complete set of property values associated with any UI event. All parameters must be present, and must be set to default values (such as false for Boolean key flags or zero for integer values) if the values are not significant for the event type.


Returned Value

None.


Parameters


eventType

String identifier for the event's type, such as DOMFocusIn, DOMFocusOut, DOMActivate.


bubblesFlag

Boolean value (TRue | false) determining whether the event's default propagation behavior is to bubble.


cancelableFlag

Boolean value (true | false) determining whether the event's default action may be prevented via the preventDefault( ) method.


view

Reference to the window or frame object in which the dynamically generated event is supposed to have occurred.


detailVal

Integer code for detail data associated with the event.


Instructs the current event to bypass the normal operation it performs on the node. Once set, the mode cannot be undone for the current event. The following W3C DOM event listener function for an keypress event allows only numbers to be entered into a text field:

 function numsOnly(evt) {     if (evt.charCode < 48 || evt.charCode > 57) {         evt.preventDefault( );     } } 

This method is the equivalent of assigning false to the IE event.returnValue property, or having an event handler evaluate to return false.


Returned Value

None.


Parameters

None.


Prevents the current event from propagating through the capture or bubbling hierarchy beyond the node currently processing the event. This method performs the same action as assigning false to the event object's cancelBubble property (for bubbling propagation only).


Returned Value

None.


Parameters

None.


The Event object is a static object (originating in Navigator 4) that contains a large set of case-sensitive constant values you can use to test user- or system-generated events for keyboard modifiers and event types (see the modifiers and type properties of the event object). These constant values evaluate to mathematically related integers. This same object continues to be supported in Mozilla and Safari, primarily for backward compatibility with the Navigator 4 event capture syntax.


Object Model Reference

 Event 


Object-Specific Properties

ABORT
ALT_MASK
BACK
BLUR
CHANGE
CLICK
CONTROL_MASK
DBLCLICK
DRAGDROP
ERROR
FOCUS
FORWARD
HELP
KEYDOWN
KEYPRESS
KEYUP
LOAD
LOCATE
META_MASK
MOUSEDOWN
MOUSEDRAG
MOUSEMOVE
MOUSEOUT
MOUSEOVER
MOUSEUP
MOVE
RESET
RESIZE
SCROLL
SELECT
SHIFT_MASK
SUBMIT
UNLOAD
XFER_DONE

The W3C DOM Event object is an abstract object that contains the properties and methods shared by every instance of a W3C DOM event. This object type is also the generic event object created from the document.createEvent( ) method. See the discussion of the event object earlier in this chapter for property and method support for this object and how these items are inherited by more specific event types.


Object Model Reference

 Event 


Object-Specific Properties

AT_TARGET
bubbles
BUBBLING_PHASE
cancelable
CAPTURING_PHASE
currentTarget
eventPhase
target
timeStamp
type

Object-Specific Methods

initEvent( )
preventDefault( )
stopPropagation( )

The W3C DOM EventListener object is nothing more than a reference to a script function that is invoked by a node in response to an event. Its existence in the W3C DOM offers a convenient way for the specification to signify the data type of the second parameter to the nodeObject.addEventListener( ) and nodeObject.removeEventListener( ) methods, described earlier in this chapter.


The W3C DOM EventTarget object is the Events module connection with nodes that actually receive events. All node objects (especially text and element nodes in an HTML document tree) implement the EventTarget object, thus giving those nodes the three methods that belong to the EventTarget object: addEventListener( ), dispatchEvent( ), and removeEventListener( ). In other words, every node in a document is also a potential EventTarget object.


The external object is used primarily by developers who use Internet Explorer as a component for their applications and require access to custom extensions to the document object model. But you might add one or two of this object's methods into your work for an IE/Windows audience.

The following syntax example asks a user for permission to insert a script-controlled bookmark into the browser's Favorites list:

 external.AddFavorite("URL", "Favorites List Label"); 

The following syntax example loads another URL into the a target window or frame (or the current window if the third parameter is an empty string), and then performs a text find for the third parameter string:

 external.NavigateAndFind("URL", "searchString", "targetFrameName"); 

For more details, visit http://msdn.microsoft.com/workshop/browser/overview/overview.asp.


The fieldset object reflects the fieldset element. IE 5 for Macintosh implements the client and scroll measurement properties for this object.


HTML Equivalent

<fieldset>


Object Model Reference

 [window.]document.getElementById("elementID") 


Object-Specific Properties

align
form

Object-Specific Methods

None.


Object-Specific Events

None.


Defines the horizontal alignment of the element within its surrounding container. In practice, this property has little effect on the fieldset object or its contents in IE 4. It behaves erratically in IE 6 for Windows, but responds as expected in IE 5 for Macintosh.


Example

 document.getElementById("myFieldset").align = "center"; 


Value

Any of the three horizontal alignment constants: center | left | right.


Default

left


Returns a reference to the next outermost form element object in the document tree. Multiple fieldset element objects within the same form element reference the same form element object.


Example

 var theForm = document.getElementById("myFieldset").form; 


Value

Reference to a form element object.


Default

None.


See input.


Provides a collection of all filters associated with the current element. Internet Explorer lets you use array notation or parentheses to access a single element in the collection. Filters are not available in IE for the Macintosh.


Object Model Reference

 document.getElementById("elementID").filters 


Object-Specific Properties

length

Object-Specific Methods

item( )
namedItem( )

Returns the number of filters in the collection.


Example

 var howMany = document.body.filters.length; 


Value

Integer.


item( index)

Returns a filter object corresponding to the filter that matches the index value in source code order.


Returned Value

Reference to a filter object. If there are no matches to the parameter, the returned value is null.


Parameters


index

A zero-based integer corresponding to the specified item in source code order.


namedItem( IDOrName)

Returns a filter object or collection of objects corresponding to the filter matching the parameter string value.


Returned Value

One filter object or collection (array) of filter objects. If there are no matches to the parameters, the returned value is null.


Parameters


IDOrName

The string that contains the same value as the desired filter's name.


The font object reflects the font element.


HTML Equivalent

<font>


Object Model Reference

 [window.]document.getElementById("elementID") 


Object-Specific Properties

color
face
size

Object-Specific Methods

None.


Object-Specific Events

None.


Sets the font color of all text contained by the font element.


Example

 document.getElementById("myFont").color = "red"; 


Value

Case-insensitive hexadecimal triplet or plain-language color name as a string. See Appendix A for acceptable plain-language color names.


Default

Browser default.


Provides a hierarchy of font faces to use for the content surrounded by the current font object. The browser looks for the first font face in the comma-delimited list of font face names until it either finds a match in the client system or runs out of choices, at which point the browser default font face is used. Font face names must match the system font face names exactly.


Example

 document.getElementById("myFont").face = "Bookman, Times Roman, serif"; 


Value

One or more font face names in a comma-delimited list within a string. You may use real font names or the recognized generic faces: serif | sans-serif | monospace.


Default

Browser default.


The size of the font in the 17 browser relative scale. For more accurate font size settings, see the style.fontSize property later in this chapter.


Example

 document.getElementById("fontSpec2").size = "+1"; 


Value

Either an integer (as a quoted string) or a quoted relative value consisting of a + or - symbol and an integer value.


Default

3


For details on this IE/Windows object, see the fonts property of the Dialog Helper object earlier in this chapter.


The form object reflects the form element. The form object can be referenced in all scriptable browsers via the value assigned to its tag name attribute or by the index of the forms array contained by every document. For browsers that support the id attribute (IE 4 and later and W3C DOM browsers), you may also use the element object reference formats that employ the element's ID. To assemble a reference to a nested form control object (such as input and textarea element objects), you have a choice again of using backward compatible references that include the form object as part of the reference (as in document.formName.controlName); or in more modern browsers, you can reference the control element directly via its unique ID.


HTML Equivalent

<form>


Object Model Reference

 [window.]document.formName [window.]document.forms[i] [window.]document.form["formName "][window.]document.getElementById("elementID") 


Object-Specific Properties

accept
acceptCharset
action
autocomplete
data
elements[]
encoding
enctype
length
method
name
replace
target
templateElements

Object-Specific Methods

checkValidity( )
dispatchFormChange( )
dispatchFormInput( )
handleEvent( )
reset( )
resetFromData( )
submit( )

Object-Specific Events

Events

IE

Mozilla

Safari

Opera

W3C DOM

formchange[a]

·

forminput[a]

·

reset

·

·

·

·

·

submit

·

·

·

·

·

[a]


[a] Web Forms 2.0 event implemented in Opera 9.


Controls the type(s) of files that all file-type input elements in the current form may upload.


Example

 document.entryForm.accept= "image/gif, image/jpeg"; 


Value

String of MIME types. Multiple MIME types should be delimited by commas.


Default

Empty string.


A server advisory (for servers that are equipped to interpret the information) about which character sets it must receive from a client form.


Example

 document.entryForm.acceptCharset= "it, es"; 


Value

Case-insensitive string from the character set registry (ftp://ftp.isi.edu/in-notes/iana/assignments/character-sets). Multiple character sets may be delimited by commas.


Default

Empty string, except in IE/Windows, with a default of UNKNOWN.


Provides the URL to be accessed when a form is being submitted. Script control of this property lets one form be submitted to different server processes based on user interaction with the rest of the form.


Example

 document.entryForm.action = "http://www.megacorp.com/cgi-bin/altEntry"; 


Value

Complete or relative URL.


Default

None.


When an IE user has automatic form completion preference enabled and the page author has set the autocomplete attribute of the form element, this property lets you control whether automatic completion is to be enabled. For more details on how AutoComplete works in HTML forms, visit http://msdn.microsoft.com/workshop/author/forms/autocomplete_ovr.asp.


Example

 document.entryForm.autocomplete = "off"; 


Value

String values: on | off.


Default

None.


Web Forms 2.0 extension that allows a form to retrieve initial values for controls from an external XML file. The specification provides some details of the structure and namespaces to be used for the file. Visit http://www.whatwg.org/ for further information.


Example

 document.entryForm.autocomplete = "off"; 


Value

URL string.


Default

Empty string.


Returns an array of all form control objects contained by the current form.


Example

 for (var i = 0; i < document.entryForm.elements.length; i++) {     if (document.entryForm.elements[i].type == "text") {         document.entryForm.elements[i].value = "";     } } 


Value

Array of element object references.


Default

Array of length zero.


Specifies the MIME type for the data being submitted to the server with the form. For typical form submissions (where the method attribute is set to post), the default value is the proper content type. But if you change the action property for a form by script, consider whether you require a custom encoding for the purpose. See also the encType property.


Example

 document.orderForm.encoding = "text/plain"; 


Value

Case-insensitive MIME type (content type) value as a string. For multiple items, a comma-delimited list is allowed in a single string.


Default

"application/x-www-form-urlencoded" in IE and Opera; empty string in Mozilla.


Provides the W3C DOM property name for what had been the encoding property of earlier DOM implementations. Current browsers support both property names. See the encoding property.


Example

 document.orderForm.enctype = "text/plain"; 


Value

Case-insensitive MIME type (content type) value as a string. For multiple items, a comma-delimited list is allowed in a single string.


Default

"application/x-www-form-urlencoded" in IE and Opera. Empty string in Mozilla and Safari.


Specifies the number of form control elements in the form. You can use this property in lieu of the length of the form's elements array.


Example

 for (var i = 0; i < document.forms[0].length; i++)     ... } 


Value

Integer.


Default

0


Forms may be submitted via two possible HTTP methods: get and post. These methods determine whether the form element data is sent to the server appended to the action attribute URL (get) or as a transaction message body (post). In practice, when the action and method attributes are not assigned in a form element, the form performs an unconditional reload of the same document, restoring form controls to their default values.


Example

 document.entryForm.method = "post"; 


Value

Either of the following constant values as a string: get | post.


Default

get


This is the identifier associated with the form. This information is not submitted with the form, but a form's name is used in references to the form and nested form elements. Despite the modern standards' preference for the id attribute, many browsers still require that a form be assigned a name attribute to allow the form to be submitted.


Example

 var firstFormName = document.forms[0].name; 


Value

Case-sensitive identifier that follows the rules of identifier naming: it may contain no whitespace, cannot begin with a numeral, and should avoid punctuation except for the underscore character.


Default

None.


Web Forms 2.0 extension that associates instructions to a form with how to process the data returned from the server after the form is submitted. The choice is whether the response replaces the original document in the browser (the default) or the browser should apply returned values to the form, rather than retrieve initial form data (if a URL is assigned to the data attribute of the form element).


Example

 document.getElementById("myform").replace = "values"; 


Value

One of two string values: document | values.


Default

document


The name of the window or frame that is to receive content returned by the server after the form is submitted. Such names are assigned to frames by the frame element's name attribute; for subwindows, the name is assigned via the second parameter of the window.open( ) method. Because the corresponding target attribute is not recognized by strict HTML or XHTML validators, you can omit the attribute to survive validation, yet still direct form results to another window by assigning a value to the form's target property in script after the page has loaded or at submit time.


Example

 document.getElementById("myForm").target = "_blank"; 


Value

String value of the window or frame name, or any of the following constants (as a string): _parent | _self | _top | _blank. The _parent value targets the frameset to which the current document belongs; the _self value targets the current window; the _top value targets the main browser window, thereby eliminating all frames; and the _blank value (or any unused identifier, for that matter) creates a new window of default size.


Default

None (which implies the current window or frame).


Web Forms 2.0 extension that returns an array of form control elements in the current form that make up repetition templates.


Value

Array (collection) of HTML element object references.


Default

Empty array.


Web Forms 2.0 extension that forces validity checking on all form controls set up for automatic validation. Returns a Boolean true if all controls validate per their individual specifications.


Returned Value

Boolean: true | false.


Parameters

None.


Web Forms 2.0 extension that forces the formchange event to fire on all elements in the form, thereby causing any event handlers for formchange events on individual elements to fire.


Returned Value

None.


Parameters

None.


Web Forms 2.0 extension that forces the forminput event to fire on all elements in the form, thereby causing any event handlers for forminput events on individual elements to fire.


Returned Value

None.


Parameters

None.


handleEvent( event)

Instructs the object to accept and process the event whose specifications are passed as the parameter to the method. The object must have an event handler for the event type to process the event.


Returned Value

None.


Parameters


event

A Navigator 4 event object.


Performs the same action as a click of a reset-type input element. All form controls revert to their default values.


Returned Value

None.


Parameters

None.


resetFromData( XMLDocument)

Web Forms 2.0 extension that sets initial values to control elements in the current form according to specifications in the XML document object passed as a parameter. The Web Forms 2.0 specification contains details on the specialized structure of this type of document. Visit http://www.whatwg.org/ for further information.


Returned Value

None.


Parameters


XMLDocument

An XML document object in the same structure as the ones that load externally from a URL you can assign to the data property.


Performs the same action as a click of a submit-type input element. This method does not fire the onSubmit event handler.


Returned Value

None.


Parameters

None.


A collection of all form objects in the document.


Object Model Reference

 document.forms 


Object-Specific Properties

length

Object-Specific Methods

item( )
namedItem( )
tags( )
urns( )

Object-Specific Events

None.


Returns the number of elements in the collection.


Example

 var howMany = document.forms.length; 


Value

Integer.


item( index[, subindex]) item( index)

Returns a single object or collection of objects corresponding to the element matching the index value (or, optionally in IE/Windows, the index and subindex values).


Returned Value

One object or collection (array) of objects. If there are no matches to the parameters, the returned value is null.


Parameters


index

When the parameter is a zero-based integer (as required for the W3C DOM), the returned value is a single element corresponding to the said numbered item in source code order (nested within the current element). When the parameter is a string (allowed by IE/Windows), the returned value is a collection of elements with id or name properties that match that string.


subindex

If you specify a string value for the first parameter (in IE/Windows), you may use the second parameter to specify a zero-based integer to retrieve a specific element from the collection with id or name properties that match the first parameter's string value.


namedItem( IDOrName)

Returns a single object (W3C DOM) or collection of objects corresponding to the element matching the parameter string value.


Returned Value

One object (W3C DOM) or collection (array) of objects. If there are no matches to the parameters, the returned value is null.


Parameters


IDOrName

The string that contains the same value as the desired element's id or name attribute.


tags( tagName)

Returns a collection of objects (among all objects within the current collection) with tags that match the tagName parameter. Redundant here, because all elements have the same form tag.


Returned Value

A collection (array) of objects. If there are no matches to the parameters, the returned value is an array of zero length.


Parameters


tagName

A string that contains the element tag, as in document.forms.tags("form").


urns( URN)

Returns a collection of nested element objects that have behaviors attached to them and URNs that match the URN parameter.


Returned Value

A collection (array) of objects. If there are no matches to the parameters, the returned value is an array of zero length.


Parameters


URN

A string with a local or external behavior file URN.


The frame object reflects the frame element, which can be generated only inside a frameset element. Be sure to distinguish the difference between the frame element object (described here) and the window object that a frame makes possible. Properties and methods of a frame element object tend to reflect the aspects associated with the HTML element and its attributes. The content of the frame is a window (a view in the W3C DOM terminology), which has been scriptable from the beginning, and contains a document. Reference a frame element object via its ID, even if you assign the same identifier to a frame element's id and name attributes. For example, from a script residing in one frame's document, reach the frame element object via:

 parent.document.getElementById("TOCFrame") 

But to reach the same frame in its capacity as a window (and thus access its scripts and document), the reference from the same script would be either of the following:

 parent.TOCFrame parent.frames["TOCFrame"] 

If a script is processing a reference to the frame element object, you can jump the fence between the element object and its content via the contentDocument or contentWindow properties described below, provided the document containing the script and the target frame's document are served from the same server and domain. But there are numerous security pitfalls in attempting to access content in another frame. Internet Explorer, in particular, is quick to generate an "Access denied" error because the browser maker has had to tighten its security bolts further than is convenient for many scripters.


HTML Equivalent

<frame>


Object Model Reference

 [windowRef.]document.getElementById("frameID") 


Object-Specific Properties

allowTransparency
borderColor
contentDocument
contentWindow
dataFld
dataSrc
frameBorder
height
longDesc
marginHeight
marginWidth
name
noResize
scrolling
src
width

Object-Specific Methods

None.


Object-Specific Events

None.


Specifies whether the frame background can be transparent. Because an underlying frameset does not have a background color or image, this property is not helpful for a frame. It does apply, however, to the related iframe element object.


Value

Boolean value: TRue | false.


Default

false


Color of the frame's border. This property more accurately belongs to the frameset element, but is exposed as a frame object property in the IE DOM.


Example

 parent.document.getElementById("myFrame").borderColor = "salmon"; 


Value

A hexadecimal triplet or plain-language color name. A setting of empty is interpreted as "#000000" (black). See Appendix A for acceptable plain-language color names.


Default

Varies with operating system.


Returns a reference to the document object loaded into the frame element object. Through that document object, you can access one of the document's elements via the getElementById( ) method, or access the containing window object via the document's defaultView property. For IE/Windows, use the contentWindow property to jump from frame element object to its content.


Example

 var frameElem = parent.document.getElementById("myFrame"); var doc = frameElem.contentDocument; 


Value

Reference to a document node.


Default

Current document node.


Returns a reference to the window object generated by the frame element. Through that window object, you can access the document object and then any one of the document's elements. The W3C DOM provides the contentDocument property to jump from frame element object to its content. But if you are trying to reach script variables or functions in the frame, the contentWindow (or W3C DOM-friendly contentDocument.defaultView) provides access to the script context.


Example

 var frameElem = parent.document.getElementById("myFrame"); var win = frameElem.contentWindow; 


Value

Reference to a window object.


Default

Current window object.


Used with IE data binding to associate a remote data source column name to the frame's src attribute. A datasrc attribute must also be set for the element. Setting both the dataFld and dataSrc properties to empty strings breaks the binding between element and data source. Works only with text file data sources in IE 5/Mac.


Example

 parent.document.getElementById("myFrame").dataFld = "srcURL"; 


Value

Case-sensitive identifier of the data source column.


Default

None.


Used with IE data binding to specify the ID of the page's object element that loads the data source object for remote data access. Setting both the dataFld and dataSrc properties to empty strings breaks the binding between element and data source. Works only with text file data sources in IE 5/Mac.


Example

 parent.document.getElementById("myFrame").dataSrc = "DBSRC3"; 


Value

Case-sensitive identifier of the data source.


Default

None.


Controls whether an individual frame within a frameset displays a border. Controlling individual frame borders appears to be a problem for most browsers in most operating system versions. Turning off the border of one frame may have no effect if all adjacent frames have their borders on. Feel free to experiment with the effects of turning some borders on and some borders off, but be sure to test the final effect on all browsers and operating systems used by your audience. Rely more comfortably on the frameborder attribute or frameBorder property of the entire frameset.


Example

 parent.document.getElementById("frame2").frameBorder = "no"; 


Value

String values of 1 (on) and 0 (off) as well as yes and no.


Default

yes


Return the height and width in pixels of the frame. Dimensions include frame chrome (scrollbars). Adjust a frame's size via the frameset object's rows or cols properties.


Example

 var frHeight = parent.document.getElementById("myFrame").height; 


Value

Integer.


Default

Current height and width.


Reflects the longDesc attribute of the frame element. Modern mainstream browsers provide no significant functionality for this attribute or property.


Value

URL string.


Default

Empty string.


Indicate the number of pixels between the inner edge of a frame and the content rendered inside the frame. The marginHeight property controls space along the top and (when scrolled) bottom edges of a frame; the marginWidth attribute controls space on the left and right edges of a frame.

Without any prompting, browsers automatically insert a small margin inside a frame (generally between 8 and 14 pixels depending on browser and operating system). But if you attempt to override the default behavior, be aware that setting any one of these two attributes causes the value of the other to go to zero. Therefore, unless you want the content to be absolutely flush with various frame edges, you need to assign values to both attributes.


Example

 parent.document.getElementById("myFrame").marginHeight = 14; parent.document.getElementById("myFrame").marginWidth = 5; 


Value

Positive integer value or zero.


Default

Varies with browser and operating system.


This is the identifier associated with a frame for use as the value assigned to target attributes or as script references to the frame. The value is usually assigned via the name attribute, but it can be modified by script if necessary.


Example

 parent.document.getElementById("myFrame").name = "results"; 


Value

Case-sensitive identifier that follows the rules of identifier naming: it may contain no whitespace, cannot begin with a numeral, and should avoid punctuation except for the underscore character.


Default

None.


Indicates whether the frame can be resized by the user. All border edges of the affected frame element become locked, meaning all edges that extend to other frames in the frameset remain locked as well.


Example

 parent.document.getElementById("myFrame").noResize = "true"; 


Value

Boolean value: TRue | false.


Default

false


Controls the treatment of scrollbars for a frame when the content exceeds the visible area of the frame. You can force a frame to display scrollbars at all times or never. Or you can let the browser determine the need for scrolling. In many supporting browsers, changing the value of this property has no effect.


Example

 parent.document.getElementById("mainFrame").scrolling = "yes"; 


Value

String values of 1 (on) and 0 (off) as well as yes, no, and auto.


Default

auto


Provides the URL of the external content file loaded into the frame. To change the content, assign a new URL to the property. For cross-platform applications, you can also set the location.href property of the frame to load a different document into the frame using window-related references (parent.frameName.location.href = "newDoc.html").


Example

 parent.document.getElementById("myFrame").src = "images/altNavBar.jpg"; 


Value

Complete or relative URL as a string.


Default

None.


See height.


A collection of all frame objects defined in the window or frame. Only the first-level frames are exposed to the frameset object. To find further nested frames requires digging into the frames collections of nested frameset objects. The collection also includes iframe elements defined in the window's document.


Object Model Reference

 [windowRef.]frames 


Object-Specific Properties

length

Object-Specific Methods

item( )
namedItem( )

Returns the number of child frames defined in the frameset whose window starts the reference. Broken in some sub-versions of pre-1.0 versions of Mozilla.


Example

 var howMany = parent.frames.length; 


Value

Integer.


item( index)

Returns a single window object corresponding to the element matching the index value in source code order.


Returned Value

window object.


Parameters


index

A zero-based integer.


namedItem( IDOrName)

Returns a single object or collection of objects corresponding to the element matching the parameter string value.


Returned Value

One object or collection (array) of objects. If there are no matches to the parameters, the returned value is null.


Parameters


IDOrName

The string that contains the same value as the desired element's id or name attribute.


The frameset object reflects the frameset element. Be sure to distinguish the difference between the frameset element object (described here) and the window object that a frameset makes possible. Properties and methods of a frameset element object tend to reflect the aspects associated with the HTML element and its attributes. The content of the frameset element is a window (a view in the W3C DOM terminology), which has been scriptable from the beginning, and contains a document (although with no renderable elements beyond the nested frame elements). Reference a frameset element object via its ID. For example, from a script residing in one frame's document, reach the frameset element object via:

 parent.document.getElementById("myFrameset") 

But to reach the frameset's window (and thus access its scripts and document), the reference from the same script would be either of the following:

 parent top 

If a script is processing a reference to the frameset element object, you can jump the fence between the element object and its content via the ownerDocument property of the element (described among the shared properties earlier in this chapter).


HTML Equivalent

<frameset>


Object Model Reference

 [windowRef.]document.getElementById("framesetID") 


Object-Specific Properties

border
borderColor
cols
frameBorder
frameSpacing
rows

Object-Specific Methods

None.


Object-Specific Events

Event

IE

Mozilla

Safari

Opera

W3C DOM

afterprint

·

beforeprint

·

beforeunload

·

load

·

·

·

·

·

resize

·

·

·

·

unload

·

·

·

·

·



Thickness of the spaces between frames in a frameset in pixels. Only the outermost frameset element of a system of nested framesets responds to the border property setting. Internet Explorer treats the default thicknesses for Windows and Macintosh differently, so be aware that the same value may look different on each operating system platform.


Example

 top.document.getElementById("myFrameset").border = 4; 


Value

An integer value. A setting of zero eliminates the border entirely. While the value is supposed to represent the precise pixel thickness of borders in the frameset, this is not entirely true for all operating systems or browsers.


Default

6 (IE Windows); 1 (IE Mac).


Color of borders between frames of the frameset. The borderColor property of an individual frame overrides the frameset object's setting.


Example

 parent.document.getElementById("myFrameset").borderColor = "salmon"; 


Value

A hexadecimal triplet or plain-language color name. A setting of empty is interpreted as "#000000" (black). See Appendix A for acceptable plain-language color names.


Default

Varies with operating system.


Defines the sizes or proportions of the column arrangement of frames in a frameset. Column size is defined in one of three ways:

  • An absolute pixel size

  • A percentage of the width available for the entire frameset

  • A wildcard (*) to represent all available remaining space after other pixels and percentages have been accounted for

Exercise extreme care when scripting a change to this property. Altering the composition of a frameset on the fly might disrupt scripts that communicate across frames. Reducing the number of columns may destroy documents whose scripts or objects support scripts in other frames or the parent. It is safest to maintain the same number of columns, but use this property to adjust the widths of existing frame columns. If your scripts rely on the frameset's onresize event handler, be sure to test on as many platforms as possible that the event is firing in response to script changes of these properties.


Example

 parent.document.getElementById("framesetter").cols = "40%,60%"; 


Value

Comma-separated list (as a string) of pixel, percentage, or wildcard (*) values.


Default

100%


Controls whether the frameset displays borders between frames. Adjusting this property does not dynamically change the border visibility in Internet Explorer for Windows.


Example

 parent.document.getElementById("framesetter").frameBorder = "no"; 


Value

Internet Explorer 4 accepts the string values of 1 (on) and 0 (off) as well as yes and no.


Default

yes


The amount of spacing in pixels between frames within a frameset. Adjusting this property does not dynamically change the frame spacing in Internet Explorer for Windows.


Example

 parent.document.getElementById("framesetter").frameSpacing = 5; 


Value

Integer.


Default

2


The sizes or proportions of the row arrangement of frames in a frameset. See the cols property for additional details of selecting values for the rows property.


Example

 document.getElementById("myFrameset").rows = "20%, 300, *"; 


Value

String of comma-delimited list of pixel or percentage values, or the * wildcard character.


Default

None.


These objects reflect the HTML header elements of the same names. See the description of the elements in Chapter 1 for examples of how various browsers render each of the header sizes.


HTML Equivalent

 <h1> <h2> <h3> <h4> <h5> <h6> 


Object Model Reference

 [window.]document.getElementById("elementID") 


Object-Specific Properties

align


Object-Specific Methods

None.


Object-Specific Events

None.


Defines the horizontal alignment of the element within its surrounding container.


Example

 document.getElementById("myHeader").align = "center"; 


Value

Any of the three horizontal alignment constants: center | left | right.


Default

left


The head object reflects the head element. Accessing this object via its ID reference may not work in the Windows version of IE 4. You should use the document.all.tags[] collection instead. For IE 5 and later and W3C DOM browsers, you can reference the element via its ID, the document.getElementsByTagName("head")[0] array reference, or document.body.previousSibling.


HTML Equivalent

<head>


Object Model Reference

 [window.]document.getElementById("elementID") [window.]document.getElementsByTagName("head")[0] 


Object-Specific Properties

profile


Object-Specific Methods

None.


Object-Specific Events

None.


Returns the URL string assigned to the optional profile attribute. In modern mainstream browsers, nothing special occurs as a result of assigning a value to this property.


Value

URL string.


Default

Empty string.


See input.


During a browser session, the browser uses the history object to maintain a list of URLs visited by the user. This list (stored as an array) is used by the browser to assist with navigation via the Back and Forward buttons. Due to the sensitive nature of the private information stored in the history object, not many of the details are exposed to scripts that could capture such information and surreptitiously submit it to a server. In more recent browser versions, each window maintains its own history object.

To answer a frequently asked question: no, you cannot block or disable the Back button's action. At most, you can prevent the current page from being entered into the browser's history when a user clicks on a link from the page. Accomplish this by scripting the links with the location.replace( ) navigation method. Navigator 4 and Mozilla (with signed scripts and the user's explicit approval) can remove the toolbar from the browser window (see the locationbar object discussion). Or, you can open a new window without the toolbar (see the window.open( ) method).


Object Model Reference

 [window.]history 


Object-Specific Properties

current
length
navigationMode
next
previous

Object-Specific Methods

back( )
forward( )
go( )
item( )

Object-Specific Events

None.


The URL of the current, next, and previous URLs in the history array. Opera supports only the current property. The next and previous property information is private and can be retrieved in Navigator 4 or Mozilla only with signed scripts and the user's approval.


Example

 netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead"); var prevURL = parent.otherFrame.history.previous; netscape.security.PrivilegeManager.revertPrivilege("UniversalBrowserRead"); 


Value

URL string.


Default

None.


The number of items in the history list. Even with this information, you are not allowed to extract a specific history entry except with signed scripts and the user's permission in Navigator 4 or Mozilla.


Example

 if (history.length > 4) {     ... } 


Value

Integer.


Default

None.


Opera 9 lets users and page authors control whether the browser should always use "fast" history navigation (which does not trigger load and unload events and thus displays pages from history faster), the compatible way (which does trigger those events), or its best guess at which mode should be used on a page-by-page basis.


Example

 history.navigationMode = "fast"; 


Value

String values: automatic | compatible | fast.


Default

automatic


The basic action is to navigate to the previously viewed document, similar to the click of the browser's Back button. You can direct the back( ) method to a specific window or frame, thus bypassing the default behavior of the Back button. For example, repeated calls to parent.otherFrame.history.back( ) eventually run out of history for the frame and then cease to do anything further. On the other hand, repeated calls to top.history.back( ) are the same as clicking the Back button, conceivably backing out of the frameset entirely if it wasn't the first document loaded in the current browser session.


Returned Value

None.


Parameters

None.


The basic action is to navigate to the same URL that the browser's Forward button leads to (if it is active). Similar cautions about the window's history from the history.back( ) method apply here, as well.


Returned Value

None.


Parameters

None.


go( stepCount | " URL")

Navigates to a specific position in the history listing.


Returned Value

None.


Parameters


stepCount

An integer representing how many items away from the current listing the browser should use to navigate. A value of zero causes the current page to reload; a value of -1 is the same as back( ); a value of -2 is the URL two steps back from the current item in history.


URL

A URL or (in Navigator) document title stored in the history listing.


item( itemNumber)

Returns the URL at a specific location in the history list. Requires Netscape/Mozilla signed scripts and the user's explicit permission to retrieve this private information.


Returned Value

URL string.


Parameters


itemNumber

An integer representing the number of item within the history list. The range of acceptable values is 0 through the history.length minus 1.


The HR object reflects the hr element.


HTML Equivalent

<hr>


Object Model Reference

 [window.]document.getElementById("elementID") 


Object-Specific Properties

align
color
noShade
size
width

Object-Specific Methods

None.


Object-Specific Events

None.


Defines the horizontal alignment of the element within its surrounding container.


Example

 document.getElementById("myHR").align = "center"; 


Value

Any of the three horizontal alignment constant strings: center | left | right.


Default

center


Sets the color scheme of the horizontal rule. If the rule is rendered in 3D, complementary colors are automatically assigned to the shaded area.


Example

 document.getElementById("myHR").color = "red"; 


Value

Case-insensitive hexadecimal triplet or plain-language color name as a string. See Appendix A for acceptable plain-language color names.


Default

Browser default.


Indicates whether the browser should render the rule as a flat (not 3D) line. In Internet Explorer only, if you set the color property, the browser changes the default line style to a no-shade style. In IE, once noShade is set to TRue, shading cannot later be restored.


Example

 document.getElementById("bar2").noShade = "true"; 


Value

Boolean value: true | false.


Default

false


Provides the thickness in pixels of the horizontal rule.


Example

 document.getElementById("rule2").size = 3; 


Value

Positive integer.


Default

2


Provides the width of the rule either in pixels (as an integer) or a percentage (as a string) of the next outermost block-level container.


Example

 document.getElementById("bar3").width = "70%"; 


Value

Integer (for pixels) or string (for pixels or percentage).


Default

100%


The html object reflects the html element.


HTML Equivalent

<html>


Object Model Reference

 [window.]document.getElementById("elementID") [window.]document.body.parentNode [window.]document.documentElement 


Object-Specific Properties

version


Object-Specific Methods

None.


Object-Specific Events

None.


Reflects the deprecated version attribute of the html element. Present in modern browsers, but not functional. See the DocumentType object.


Value

String.


Default

Empty string.


The HTMLCollection object is an abstract representation in the W3C DOM of any collection of HTML element objects, all of which exist in the same document tree and have the same tag. For example, in the eyes of the W3C DOM, the document.images array is an HTMLCollection object. All entries are img element object references. JavaScript treats such collections as arrays for access to individual entries via array notation, along with the help of the HTMLCollection's sole property, length. Alternatively, you can use the two methods (item( ) and namedItem( )) to reference a single entry in the collection. All instances of the HTMLCollection object (such as document.images) inherit the property and methods listed below from the abstract HTMLCollection object. See descriptions of each instance in this chapter (anchors, applets, areas, cells, elements, forms, images, links, options, rows, tBodies, and non-W3C DOM element collections all, children, embeds, and frames).


Object-Specific Properties

length

Object-Specific Methods

item( )
namedItem( )

Object-Specific Events

None.


Returns the number of elements in the collection.


Example

 var howMany = document.myForm.elements.length; 


Value

Integer.


item( index)

Returns one object from the collection corresponding to the object matching the index value in source code order. IE implements another variation of this method for some (but not all) of its collections with an optional secondary parameter.


Returned Value

Reference to an element object. If there are no matches to the parameter, the returned value is null.


Parameters


index

A zero-based integer corresponding to the specified item in source code order.


namedItem( IDOrName)

Returns one object from the collection corresponding to the object matching the parameter string value.


Returned Value

Reference to an element object. If there are no matches to the parameters, the returned value is null.


Parameters


IDOrName

The string that contains the same value as the desired filter's name.


The HTMLDocument object is an abstract representation in the W3C DOM of the document node for an HTML document tree. Scripts reference this object via the document object.

This object inherits properties and methods from a chain of node objects in the W3C DOM core module, namely the root Node object and the Document object. To this set of properties and methods, the HTMLDocument object adds properties and methods that apply specifically to HTML documents (in contrast to XML documents)properties such as referrer and body, and methods such as write( ). Browser implementations add numerous additional proprietary properties and methods. See the full discussion of the scriptable implementations of the HTMLDocument object within the document object discussion earlier in this chapter.


Object-Specific Properties

anchors[ ]
applets[ ]
body
cookie
domain
forms[ ]
images[ ]
links[ ]
referrer
title
URL

Object-Specific Methods

close( )
getElementsByName( )
open( )
write( )
writeln( )

Every scriptable element object in modern browsers is, at its core, a descendant of the basic HTMLElement abstract object in the W3C DOM. The HTMLElement, itself, inherits properties and methods from the Node and Element chain in the core DOM module. To this inherited set of features, the HTMLElement adds properties that apply to HTML elements (in contrast to XML elements), including the className, dir, id, lang, and title properties. All individual HTML element objects, such as HTMLBodyElement and HTMLFormElement, inherit their characteristics from the HTMLElement object. That's one reason why the list of shared properties and methods at the beginning of this chapter is so long: it includes items inherited from the long chain of Node to Element to HTMLElement.

Knowing the terminology of the DOM abstract object names (e.g., HTMLBodyElement) is not essential knowledge to scripting element objects. That is to say, the abstract object names almost never appear in scripts because scripts reference instances of such HTML objects by way of their identifiers or through properties of other objects (such as eventObject.target). The only time you are likely to see these abstract names is during debugging, when you use alert( ) methods or other tools to inspect the object referenced by a variable. Mozilla reports such object references as instances of a specific HTML element class (e.g., HTMLParagraphElement or HTMLInputElement). This information, in itself, is often far more helpful than IE's reporting of the reference being just [object].


Object-Specific Properties

className
dir
id
lang
title

Object-Specific Methods

None.


See b.


The iframe object reflects the iframe element. Be aware that, in Internet Explorer, a number of properties defined for this object have no effect on the object nor any default value, but are implemented because the element shares its internal structure with other elements that use those properties.


HTML Equivalent

<iframe>


Object Model Reference

 [window.]document.getElementById("elementID") 


Object-Specific Properties

align
allowTransparency
border
contentDocument
contentWindow
dataFld
dataSrc
frameBorder
frameSpacing
height
hspace
location
longDesc
marginHeight
marginWidth
name
noResize
scrolling
src
vspace
width

Object-Specific Methods

None.


Object-Specific Events

None.


Defines how the element is aligned relative to surrounding text content. Most values set the vertical relationship between the element and surrounding text. For example, to align the bottom of the element with the baseline of the surrounding text, the align property value would be baseline. An element can be "floated" along the left or right margin to let surrounding text wrap around the element.


Example

 document.getElementById("myIframe").align = "absmiddle"; 


Value

Any of the following alignment constant values (as a string): absbottom | absmiddle | baseline | bottom | right | left | none | texttop | top.


Default

bottom


Specifies whether the iframe background can be transparent. For the background of the main document to show through both the iframe and its document, the document's background-color style attribute must be set to transparent.


Example

 document.getElementById("myIframe").allowTransparency = true; 


Value

Boolean value: true | false.


Default

false


Although defined for the iframe element object in IE/Windows, the border property has no value nor does assigning a value affect the appearance of the element.


Returns a reference to the document object loaded into the iframe element object. Through that document object, you can access one of the document's elements via the getElementById( ) method, or access the containing window object via the document's defaultView property. For IE/Windows, use the contentWindow property to jump from iframe element object to its content.


Example

 var iframeElem = parent.document.getElementById("myIframe"); var doc = iframeElem.contentDocument; 


Value

Reference to a document node.


Default

Current document node.


Returns a reference to the window object generated by the iframe element. Through the window object, you can access the document object and then any one of the document's elements. The W3C DOM provides the contentDocument property to jump from iframe element object to its content. But if you are trying to reach script variables or functions in the frame, the contentWindow (or W3C DOM-friendly contentDocument.defaultView) provides access to the script context.


Example

 var iframeElem = parent.document.getElementById("myIframe"); var win = iframeElem.contentWindow; 


Value

Reference to a window node.


Default

Current window node.


Used with IE data binding to associate a remote data source column name with the value of the src property. A datasrc attribute must also be set for the element. Setting both the dataFld and dataSrc properties to empty strings breaks the binding between element and data source. Works only with text file data sources in IE 5/Mac.


Example

 document.getElementById("myIframe").dataFld = "frameURL"; 


Value

Case-sensitive identifier of the data source column.


Default

None.


Used with IE data binding to specify the ID of the page's object element that loads the data source object for remote data access. Setting both the dataFld and dataSrc properties to empty strings breaks the binding between element and data source. Works only with text file data sources in IE 5/Mac.


Example

 document.getElementById("myIframe").dataSrc = "DBSRC3"; 


Value

Case-sensitive identifier of the data source.


Default

None.


Controls whether the iframe element displays a border.


Example

 document.getElementById("myIframe").frameBorder = "0"; 


Value

String values: 1 (on) | 2 (off)


Default

Empty string or 1.


The amount of spacing in pixels between frames within a frameset. This property has no effect on an inline frame in Internet Explorer.


Provide the pixel or percentage measure of the iframe element's height and width.


Example

 document.getElementById("myIframe").height = "200"; document.getElementById("myIframe").width = "500"; 


Value

Length string.


Default

300 (width); 150 (height).


Provide the pixel measure of horizontal and vertical margins surrounding an inline frame. The hspace property affects the left and right edges of the element equally; the vspace property affects the top and bottom edges of the element equally. These margins are not the same as margins set by style sheets, but they have the same visual effect.


Example

 document.getElementById("myIframe").hspace = 5; document.getElementById("myIframe").vspace = 8; 


Value

Integer of pixel count.


Default

0


This property borrows the location property of the window object created by the iframe element. It is a full-fledged location object, but if you wish to load a new URL into an iframe, use the cross-browser src property.


Reflects the longDesc attribute of the iframe element. Mainstream browsers provide no significant functionality for this attribute or property.


Value

URL string.


Default

Empty string.


Control the number of pixels between the inner edge of a frame and the content rendered inside the frame. An adjustment to either property sets the other property to zero, eliminating the default margin provided by the browser.


Value

Positive integer value or zero.


Default

Varies with browser and operating system.


This is the identifier associated with an iframe for use as the value assigned to target attributes or as script references to the frame. The value is usually assigned via the name attribute, but it can be modified by script if necessary.


Value

Case-sensitive string identifier that follows the rules of identifier naming: it may contain no whitespace, cannot begin with a numeral, and should avoid punctuation except for the underscore character.


Default

None.


Specifies whether the frame can be resized by the user. Not applicable to an iframe element.


Specifies the treatment of scrollbars for an iframe when the content exceeds the visible area of the iframe. You can force an iframe to display scrollbars at all times or never. Or you can let the browser determine the need for scrolling. It is not uncommon for browsers to ignore scripted changes to this property. Make your choice in the element's scrolling attribute.


Example

 document.getElementById("myIframe").scrolling = "no"; 


Value

One of three constants (as a string): auto | no | yes.


Default

auto


Indicates the URL of the external content file loaded into the current element. To change the content, assign a new URL to the property.


Example

 document.getElementById("myIframe").src = "section2.html"; 


Value

Complete or relative URL as a string.


Default

None.


See hspace.


See height.


See layer.


Use the constructor function the static Image object (new Image( )) to create a nondisplayed img object in the browser's memory. By assigning an image file's URL to the src property of such an instance, you instruct the browser to precache the image in the browser. You may then assign the src property of the undisplayed instance to the src property of an img object in the document tree to swap the existing image with the pre-cached one. An instance of the Image object is a DOM img element, whose properties, methods, and events are described with that object.


Object Model Reference

 Image 


Object-Specific Properties

prototype

Object-Specific Methods

None.


This is a property of the static Image object. Use the prototype property to assign new properties and methods to future instances of images created in the current document. See the Array.prototype property in Chapter 5 for usage of this object property.


Example

 Image.prototype.exif = ""; 


Value

Any data, including function references.


A collection (array) of all img objects contained by the document. This object is implemented only in browser versions that treat images as objects. Therefore, you can use the existence of this array object as a conditional switch surrounding statements that swap or preload images:

 if (document.images) {     // process img element objects here } 


Object Model Reference

 document.images 


Object-Specific Properties

length

Object-Specific Methods

item( )
namedItem( )
tags( )
urns( )

Returns the number of elements in the collection.


Example

 var howMany = document.images.length; 


Value

Integer.


item( index[, subindex]) item( index)

Returns a single image object or collection of image objects corresponding to the element matching the index value (or, optionally in IE, the index and subindex values).


Returned Value

One object or collection (array) of objects. If there are no matches to the parameters, the returned value is null.


Parameters


index

When the parameter is a zero-based integer (required in W3C DOM implementations), the returned value is a single element corresponding to the said numbered item in source code order (nested within the current element). When the parameter is a string, the returned value is a collection of elements with id or name properties that match that string.


subindex

If you specify a string value for the first parameter (IE only), you may use the second parameter to specify a zero-based integer to retrieve a specific element from the collection with id or name properties that match the first parameter's string value.


namedItem( IDOrName)

Returns a single object corresponding to the element matching the parameter string value.


Returned Value

One object reference. If there are no matches to the parameters, the returned value is null.


Parameters


IDOrName

The string that contains the same value as the desired element's id or name attribute.


tags( tagName)

Returns a collection of objects (among all objects within the current collection) with tags that match the tagName parameter. Redundant here, because all elements have the same img tag.


Returned Value

A collection (array) of objects. If there are no matches to the parameters, the returned value is an array of zero length.


Parameters


tagName

A string that contains the element tag, as in document.images.tags("img").


urns( URN)

Returns a collection of nested element objects that have behaviors attached to them and URNs that match the URN parameter.


Returned Value

A collection (array) of objects. If there are no matches to the parameters, the returned value is an array of zero length.


Parameters


URN

A string with a local or external behavior file URN.


The img object reflects the img element. This object shares the same properties as the static Image object, which you can use to pre-cache images without rendering them on the page.


HTML Equivalent

<img>


Object Model Reference

 [window.]document.imageName [window.]document.images[i] [window.]document.images["imageName"] [window.]document.getElementById("elementID") 


Object-Specific Properties

align
alt
border
complete
dataFld
dataFormatAs
dataSrc
dynsrc
fileCreatedDate
fileModifiedDate
fileSize
fileUpdatedDate
height
HRef
hspace
isMap
longDesc
loop
lowsrc
lowSrc
mimeType
name
nameProp
naturalHeight
naturalWidth
protocol
src
start
useMap
vspace
width
x
y

Object-Specific Methods

None.


Object-Specific Events

Events

IE

Mozilla

Safari

Opera

W3C DOM

abort

·

·

·

·

·

error

·

·

·

·

·

load

·

·

·

·



Defines how the element is aligned relative to surrounding text content. Most values set the vertical relationship between the element and surrounding text. For example, to align the bottom of the element with the baseline of the surrounding text, the align property value would be baseline. An element can be "floated" along the left or right margin to let surrounding text wrap around the element.


Example

 document.logoImg.align = "absmiddle"; 


Value

Any of the following alignment constant values (as a string): absbottom | absmiddle | baseline | bottom | right | left | none | texttop | top.


Default

bottom


Indicates the text to be displayed (or spoken) where the img element appears on the page when a browser does not download graphics (or is waiting for the image to download). The text is usually a brief description of what the image is. Be aware that the size of the image area on the page may limit the amount of assigned text visible on the page. Make sure the description is readable.


Example

 document.corpLogo.alt = "MegaCorp Logo"; 


Value

String value.


Default

None.


Provides the thickness of the border around an element (in pixels). This property is read-only in Navigator up to version 4.


Example

 document.logoImage.border = 4; 


Value

An integer value. A setting of zero removes the border entirely.


Default

0


Reveals whether the img element's src or lowsrc image file has fully loaded. Note that Navigator 4 provides an incorrect TRue reading before the image has completely loaded.


Example

 if (document.logo.complete) {     // safe to process the image object } 


Value

Boolean value: TRue | false.


Default

false


Used with IE data binding to associate a remote data source column name with the src property of the img object. A datasrc attribute must also be set for the element. Setting both the dataFld and dataSrc properties to empty strings breaks the binding between element and data source. Works only with text file data sources in IE 5/Mac.


Example

 document.myImage.dataFld = "logoURL"; 


Value

Case-sensitive identifier of the data source column.


Default

None.


This property is a member of the img element object in IE, but does not apply to img because data binding values are linked to the src attribute, rather than rendered content.


Used with IE data binding to specify the ID of the page's object element that loads the data source object for remote data access. Setting both the dataFld and dataSrc properties to empty strings breaks the binding between element and data source. Works only with text file data sources in IE 5/Mac.


Example

 document.myImage.dataSrc = "DBSRC3"; 


Value

Case-sensitive identifier of the data source.


Default

None.


URL of a video clip to be displayed through the img element. Changing this property loads a new video clip into the image object. See also the loop property for controlling the frequency of video clip play.


Example

 document.images[3].dynsrc = "snowman.avi"; 


Value

Complete or relative URL as a string.


Default

None.


Returns a string of the date (but not the time) that the server (or local filesystem) reports the currently loaded file was created. By loading an image into a nonrendered Image object, a script can determine the date of the image (but more accurately from the fileUpdatedDate property). IE 4's value is a long date format, but starting with IE 5, the date information is formatted as mm/dd/yyyy. The value may be corrupted if the server supplies the data in a format that IE does not expect. Implemented in IE 5/Mac, but the value is empty.


Example

 var dateObj = new Date(document.logoImg.fileCreatedDate); 


Value

Date string.


Default

None.


Returns a string of the date (but not the time) that the server (or local filesystem) reports the currently loaded file was most recently modified. IE 4's value is a long date format, but starting with IE 5, the date information is formatted as mm/dd/yyyy. The value may be corrupted or incorrect if the server supplies the data in a format that IE does not expect. Implemented in IE 5/Mac, but the value is empty.


Example

 var dateObj = new Date(document.logoImg.fileModifiedDate); 


Value

Date string.


Default

None.


Returns the number of bytes for the size of the currently loaded image. IE for Windows returns this value as a string, while IE for Macintosh returns a number value (although its value is 0).


Example

 var byteCount = parseInt(document.fileSize, 10); 


Value

Integer as string (Windows) or number (Mac).


Default

None.


For an image file retrieved from a server, this property may more accurately reflect the date the file was last uploaded to the server than the other date-related properties. Local files commonly return an empty string. Implemented in IE 5/Mac, but the value is empty.


Example

 var dateObj = new Date(document.logoImg.fileUpdatedDate); 


Value

Date string.


Default

None.


Provide the height and width in pixels of the image rendered in the img element. Changes to these values are immediately reflected in reflowed content on the page in all supporting browsers except NN 4 and earlier. Be aware that images scale to fit the new dimension.


Example

 document.prettyPicture.height = 250; 


Value

Integer.


Default

None.


The URL specified by the element's src attribute. Identical to, and deprecated in favor of, the src property.


Example

 document.logoImage.href = "images/fancyLogo.gif"; 


Value

String of complete or relative URL.


Default

None.


Provide the pixel measure of horizontal and vertical margins surrounding an image object. The hspace property affects the left and right edges of the element equally; the vspace affects the top and bottom edges of the element equally. These margins are not the same as margins set by style sheets, but they have the same visual effect. Properties are read-only in NN 4 and earlier.


Example

 document.logo.hspace = 5; document.logo.vspace = 8; 


Value

Integer of pixel count.


Default

0 (IE, Safari, Opera), -1 (Mozilla).


Indicates whether the img element is acting as a server-side image map. For an image to be a server-side image map, it must be wrapped with an a element whose href attribute points to the URL of the CGI program that knows how to interpret the click coordinate information. The browser appends coordinate information about the click to the URL as a get form method appends form element data to the action attribute URL.

More recent browsers allow client-side image maps (see the useMap property), which operate more quickly for the user, because there is no communication with the server to carry out the examination of the click coordinate point.


Example

 document.navMap.isMap = true; 


Value

Boolean value: true | false.


Default

false


Reflects the longDesc attribute of the img element. Mainstream browsers provide no significant functionality for this attribute or property.


Value

URL string.


Default

Empty string.


If you specify a video clip with the dynsrc attribute, the loop property controls how many times the clip should play (loop). Changing to a value of -1 is equal to a continuous loop.


Example

 document.movieImg.loop = 3; 


Value

Integer.


Default

1


Indicates the URL of a lower-resolution (or alternate) image to download into the document space if the image of the src attribute will take a long time to download. The lowsrc image should be the same pixel size as the primary src image. It makes sense to change the lowsrc property only if you are also going to change the src property. In this case, make sure you change the lowsrc property first so that the browser knows how to handle the long download for the src image.

Note that early Mozilla versions also implemented a second variation of this property with a different capitalization: lowSrc. Neither version is indicated in the W3C DOM.


Example

 document.productImage.lowsrc = "images/widget43LoRes.jpg"; 


Value

Any complete or relative URL as a string.


Default

None.


Returns a plain-language description of the MIME type for the image. This property may not be officially supported by Microsoft, but it correctly reports values for typical image types served from both local disks and servers.


Example

 if (document.productImage.mimeType.indexOf("JPEG") != -1) {     // process condition for jpeg image } 


Value

String value such as JPEG Image or GIF Image.


Default

None.


This is the identifier associated with the image object for use in scripted references to the object, such as via the document.images array.


Example

 var imgName = document.images[3].name; 


Value

Case-sensitive string identifier that follows the rules of identifier naming: it may contain no whitespace, cannot begin with a numeral, and should avoid punctuation except for the underscore character.


Default

None.


Returns the filename (without the rest of the URL path) of the current image. Simplifies examination of current image content.


Example

 if (document.images[3].nameProp == "menuOn.jpg") {     document.image[3].src = "../images/menuOff.jpg"; } 


Value

Case-sensitive string filename and extension.


Default

None.


Return the unscaled height and width of the image, in pixels. Allows scripts to find the true dimensions of the original image in case scripts or incorrect element attributes have scaled the image.


Example

 document.logoImg.height = document.logoImg.naturalHeight; document.logoImg.width = document.logoImg.naturalWidth; 


Value

Integer.


Default

None.


Returns the protocol component of the URL associated with the element. Windows and Macintosh versions return values in different formats. For the Windows version, the values are in expanded plain language (e.g., File Protocol or HyperText Transfer Protocol); for the Mac version, values resemble location.protocol values (e.g., file: or http:).


Value

String.


Default

None.


Provides the relative or complete URL of the image file currently loaded or to be loaded into the img element. Loading an image of a different size into an existing img element forces the element to resize to the new image's dimensions except in the following browsers: Netscape 3, Netscape 4, and IE 3 for the Macintosh. Reading this property returns the complete URL, regardless of how the URL form assigned the value originally.


Example

 document.image[3].src = "../images/menuOff.jpg"; 


Value

URL string.


Default

None.


If you specify a video clip with the dynsrc attribute, the start property controls the action that causes the clip to start running.


Example

 document.movieImg.start = "mouseover"; 


Value

String constant: fileopen | mouseover.


Default

fileopen


Provides the URL of the map element in the same document that contains client-side image map hot areas and links. The value includes the hashmark assigned with the map name in the usemap attribute of the img element.


Example

 document.images[0].useMap = "#altMap"; 


Value

A string starting with a hashmark and the name of the map element.


Default

None.


See hspace.


See height.


Provide the horizontal and vertical pixel coordinates of the top-left corner of the image relative to the page. These are Navigator-only properties, corresponding to the offsetLeft and offsetTop properties of Internet Explorer.


Example

 var imageFromTop = document.logoImg.y; 


Value

Integer.


Default

None.


The implementation object (the JavaScript reference for the W3C DOMImplementation object) represents, to a limited degree, the environment that makes up the document containerthe browser for our purposes. You can reach this object via the document.implementation property.

Methods of the object let you see which DOM modules the browser reports supporting. In W3C DOM browsers, this object is also a gateway to creating virtual W3C Document and DocumentType objects outside of the current document tree. Thus, in supporting W3C DOM browsers you can use the document.implementation property as a start to generating a nonrendered document for external XML documents.

Opera implements several methods that are defined in the W3C DOM Level 3 Load and Save module: createLSInput( ), createLSOutput( ), createLSParser( ), and createLSSerializer( ). For details on these methods, consult the W3C recommendation at http://www.w3.org/TR/DOM-Level-3-LS/load-save.html.


Object Model Reference

document.implementation


Object-Specific Properties

None.


Object-Specific Methods

createCSSStyleSheet( )
createDocument( )
createDocumentType( )
createHTMLDocument( )
hasFeature( )

Object-Specific Events

None.


createCSSStyleSheet(" title", " mediaList")

Returns a reference to a newly created virtual styleSheet object with no rules. You can add rules via the styleSheet.addRule( ) method. Unfortunately, as the W3C DOM recommendation admits, there is no mechanism for associating a styleSheet object created in this manner with a document to offer any practical application. For programmatic insertion of style sheet settings, use the addRule( ) method for an existing styleSheet object in the document tree.


Returned Value

Reference to a styleSheet object not yet associated with a Document object.


Parameters


title

String containing an advisory title.


mediaList

String of comma-delimited media (e.g., screen, print) for which the style sheet is intended.


createDocument(" namespaceURI", " qualifiedName", docTypeReference)

Returns a reference to a newly created virtual W3C DOM Document (not the document node of an HTML document) object. Mozilla extends this Document object with a load( ) method that permits the loading of XML documents into the browser's memorynow superceded by the XMLHttpRequest object.


Returned Value

Reference to an empty Document node object.


Parameters


namespaceURI

String of the namespace URI for a new XML document element.


qualifiedName

String identifier for the qualified name for the new document element.


docTypeReference

Reference to a DocumentType node (which may be generated from the document.implementation.createDocumentType( ) method).


createDocumentType(" qualifiedName", " publicID", " systemID")

Returns a reference to a newly created virtual W3C DOM DocumentType object. You can feed the object returned from this method to the document.implementation.createDocument( ) method.


Returned Value

Reference to a DocumentType object not yet associated with a Document object.


Parameters


qualifiedName

String identifier for the qualified name for the new document element.


publicID

String of the public identifier for the DOCTYPE.


systemID

String of the system identifier (typically, the URI of the DTD file) for the DOCTYPE.


createHTMLDocument(" title")

Returns a reference to a newly created virtual W3C DOM HTMLDocument (not the document node of an HTML document) object. This document is a skeleton document (<HTML><HEAD><TITLE>titleParameterText</TITLE></HEAD></HTML>), into which you may append elements of your own creation.


Returned Value

Reference to an empty HTMLDocument object.


Parameters


title

String of the document's title, which is inserted as the content of the title element.


hasFeature(" feature", " version")

Returns a Boolean true if the browser application supports (i.e., conforms to the required specifications of) a stated W3C DOM module and version. The closely related isSupported( ) method performs the same test on an individual node, allowing you to verify feature support for the current node type. Parameter values for the two methods are identical.

It is up to the browser maker to validate that the DOM implemented in the browser conforms with each module before allowing the browser to return true for the module. That doesn't necessarily mean that the implementation is bug-free or consistent with other implementations. Caveat scriptor.

In theory, you could use this method to verify module support prior to accessing a property or invoking a method. The following script fragment from the head portion of a document dynamically links a different external style sheet file for "true" CSS2 support:

 var cssFile; if (document.implementation.hasFeature("CSS", "2.0")) {     cssFile = "styles/corpStyle2.css"; } else {     cssFile = "styles/corpStyle1.css"; } document.write("<link rel='stylesheet' type='text/css' href='" + cssFile + "'>"); 

More browsers support this browser-wide method than the element-specific method, which may help more developers deploy it sooner.


Returned Value

Boolean value: true | false.


Parameters


feature

As of W3C DOM Level 2, permissible case-sensitive module name strings are: Core, XML, HTML, Views, StyleSheets, CSS, CSS2, Events, UIEvents, MouseEvents, MutationEvents, HTMLEvents, Range, TRaversal, and Views. Level 3 adds more features, such as LS (the Load and Save module), BasicEvents, TextEvents, and KeyboardEvents.


version

String representation of the major and minor version of the DOM module cited in the first parameter. For the W3C DOM Level 2, the version is 2.0, even when the DOM module supports another W3C standard that has its own numbering system. Thus, the test for HTML DOM module support is for Version 2.0, even though HTML is at 4.x.


A collection (array) of styleSheet objects imported into an explicit styleSheet object via the @import rule. In other words, a styleSheet object that employs an @import TReats that imported style sheet as a nested object, but one that is, itself, a full-fledged styleSheet object. Thus, you can access the rule objects within each imported style sheet. The following example iterates through all of the document's styleSheet objects in search of imported style sheets:

 for (var i = 0; i < document.styleSheets.length; i++) {     for (var j = 0; j < document.styleSheets[i].imports.length; j++) {         // process each imported style sheet, referenced         // here as document.styleSheets[i].imports[j]     } } 


Object Model Reference

 document.styleSheets[i].imports 


Object-Specific Properties

length


Object-Specific Methods

item( )


Returns the number of objects in the collection.


Example

 var howMany = document.styleSheets[i].imports.length; 


Value

Integer.


item( index)

Returns a single imported styleSheet object corresponding to the index value in source code order of @import rules. IE 5 for Macintosh erroneously returns null.


Returned Value

Reference to an imported styleSheet object. If there are no matches to the parameters, the returned value is null.


Parameters


index

Zero-based integer.


The input object reflects the input element. Most input element types were at least partially accessible to scripts dating all the way back to the first scriptable browsers. But Internet Explorer from version 4 onward, as well as Mozilla, Safari, and Opera from the past few years all provide script access to a wide range of properties.

In the W3C DOM specification, all input element objects share the same properties, even when the properties don't necessarily apply (the checked property of an input element of type text, for example). To reduce potential confusion, the discussions here for input types note the type or types for which each property and method truly applies (just like the corresponding entry for the input HTML element in Chapter 1).

A few properties and methods that don't appear here in the lists of object-specific items are worth highlighting. While the IE DOM (especially in the Windows versions) ascribes properties such as accessKey, disabled, and tabIndex to virtually every HTML element, the W3C DOM is typically more parsimonious in handing out these properties to elements. But input elements are the right places for these properties, and you'll find full implementations in all modern browsers. The same goes for the blur( ), click( ), and focus( ) methods, which are described among the shared items earlier in this chapter.

One input type that can cause initial headaches is the radio type. To allow a group of radio input elements to work their exclusive magic (checking one unchecks another) requires that all elements have the same identifier assigned to the name attribute (and thus name property). This means all like-named radio objects become a collection (array) of radio objects. It may be necessary, therefore, to reference an individual radio button as an item in an array. The entire array, of course, has a length property you can use to assist in looping through all radio objects within the group, if necessary, to find which one is checked, and retrieve that object's value:

 var radioGrp = document.forms[0].myRadio; for (var i = 0; i < radioGrp.length; i++) {     if (radioGrp[i].checked) {         alert("The value of the chosen button is " + radioGrp [i].value);     } } 

Many properties and methods listed below are the exclusive realm of Web Forms 2.0, whose first implementation is in Opera 9. Item descriptions clearly indicate when they apply to Web Forms 2.0. Consult the input element in Chapter 1 for more details about setting up input elements to be Web Forms 2.0 friendly.

All event types listed here are available in all scriptable browsers. Mouse and keyboard events, of course, are shared among all rendered HTML elements, as described at the beginning of this chapter. Consult Chapter 9 to see which input types recognize each event type tailored for input elements.


Object Model Reference

 [window.]document.formName.elementName [window.]document.forms[i].elements[i] [window.]document.getElementById("elementID") 


Object-Specific Properties

accept
action
alt
autocomplete
autofocus
checked
complete
dataFld
dataSrc
defaultChecked
defaultValue
dynsrc
enctype
form
forms[]
height
hspace
htmlTemplate
indeterminate
inputmode
labels[]
list
loop
lowsrc
max
maxLength
method
min
name
pattern
readOnly
replace
required
selectedOption
selectionEnd
selectionStart
size
src
start
status
step
target
type
useMap
validationMessage
validity
value
valueAsDate
valueAsNumber
width
willValidate

Object-Specific Methods

checkValidity( )
createTextRange( )
dispatchChange( )
dispatchFormChange( )
handleEvent( )
select( )
setCustomValidity( )

Object-Specific Events

Event

change

invalid (Web Forms 2.0)

select



Provides an optional advisory property consisting of a string of one or more comma-delimited MIME types of files that are being uploaded. Values have no impact on this element in current browsers.


Input Types

file


Example

 document.entryForm.myFileUpload.accept = "image/gif"; 


Value

String.


Default

None.


Web Forms 2.0 extension that allows a submission of the enclosing form to a URI different from the regular form when the button element is clicked (and its type is set to submit).


Input Types

image, submit


Example

 document.getElementById("redirSubmit").action = "redirect.php"; 


Value

URI string.


Default

None.


Provides text to be displayed (or spoken) where the image-type input element appears on the page when a browser does not download graphics (or is waiting for the image to download). See the alt property of the img object for more details.


Input Types

image


Web Forms 2.0 extension that specifies whether the browser's automatic text field completion function is engaged. Although the property is a member of text-related input elements in Opera 9, changing the value does not affect operation.


Input Types

Text-oriented input types for Web Forms 2.0.


Value

String value: on | off.


Default

on


Web Forms 2.0 extension that brings focus to the element after the page loads. Should be assigned to only one form control element per page.


Input Types

All rendered input types for Web Forms 2.0.


Value

Boolean value: true | false.


Default

false


Determines whether the button is selected or turned on by the user or script. Checkboxes operate independently of each other. Only radio or checkbox objects with the checked property set to true have their name/value pair submitted with the form. To find out whether the form element is set to be checked when the page loads, see the defaultChecked property. Scripts can change this property even if the element is disabled.


Input Types

checkbox, radio


Example

 if (document.choiceForm.myRadio[0].checked) {     //process first radio button } 


Value

Boolean: true | false.


Default

false


Reveals whether the image-type input element's src or lowsrc image file has fully loaded. See the complete property of the img object for more details.


Input Types

image


Used with IE data binding to associate a remote data source column name to a button object's value property. A datasrc attribute must also be set for the element. Setting both the dataFld and dataSrc properties to empty strings breaks the binding between element and data source. Works only with text file data sources in IE 5/Mac.


Input Types

button, checkbox, hidden, password, radio, text


Example

 document.myForm.myButton.dataFld = "linkURL"; 


Value

Case-sensitive identifier of the data source column.


Default

None.


Used with IE data binding to specify the ID of the page's object element that loads the data source object for remote data access. Content from the data source is specified via the datafld attribute. Setting both the dataFld and dataSrc properties to empty strings breaks the binding between element and data source. Works only with text file data sources in IE 5/Mac.


Input Types

button, checkbox, hidden, password, radio, text


Example

 document.myForm.myButton.dataSrc = "DBSRC3"; 


Value

Case-sensitive identifier of the data source.


Default

None.


Specifies whether the element has the checked attribute set in the tag. You can compare the current checked property against defaultChecked to see whether the state of the control has changed since the document loaded. Changing this property does not affect the current checked status.


Input Types

checkbox, radio


Example

 var cBox = document.forms[0].checkbox1 if (cBox.checked != cBox.defaultChecked) {     // process for changed state } 


Value

Boolean value: true | false.


Default

Determined by HTML tag attribute.


Returns the string assigned to the value attribute of the element in the source code (except in IE for Windows, which returns an empty string). A user must manually select a file for uploading, so pre-setting or attempting to alter this value is a waste of time.


Input Types

file, hidden, password, text


Example

 var initVal = document.entryForm.myFileUpload.defaultValue; 


Value

String.


Default

None.


Provides the URL of a video clip to be displayed through the image-type input element's image. See the dynsrc property of the img object for more details.


Input Types

image


Web Forms 2.0 extension that allows (in concert with other properties, such as action) a submission of the enclosing form to a URI and enclosure MIME type different from the regular form when the submit button or image is clicked.


Input Types

image, submit


Example

 document.getElementById("mySubmit").enctype = "text/plain"; 


Value

MIMEtype string.


Default

None.


Returns a reference to the form element that contains the current element. When processing an event from this element, the event handler function automatically has access to the input element (as the event object's target or srcElement property). By reading the form property, the script can easily access other controls within the same form.

In a Web Forms 2.0 environment, a form control (via the form attribute) may be associated with a form element that does not contain the control in the document tree. The property points to whichever form element is associated with the control.


Input Types

All types.


Example

 var theForm = evt.srcElement.form; 


Value

form element object reference.


Default

None.


Web Forms 2.0 extension that returns an array (NodeList) of references to form objects with which the current input element is associated.


Example

 var formList = document.getElementById("myButton").forms; 


Value

Array.


Default

One-item array with a reference to any enclosing form element.


Indicate the height and width in pixels of the image rendered in the input element. See the height and width properties of the img object for more details.


Input Types

image


Indicate the pixel measure of horizontal and vertical margins surrounding an image-type input object. See the hspace and vspace properties of the img object for more details.


Input Types

image


Web Forms 2.0 extension that returns a reference to the element object (a RepetitionElement object) whose ID matches that of the current form control's template attribute (which must be set for this property to be anything other than null).


Input Types

add


Example

 var repeatTemplate = document.getElementById("myButton").htmlTemplate; 


Value

Element object reference.


Default

null


Indicates whether a checkbox is visually represented as being neither checked nor unchecked, yet still active. This middle ground is rendered differently for different operating systems. In Windows, the checkbox is grayed out (with the checkmark still visible if it was there originally) but still active. On the Macintosh, the checkbox displays a hyphen inside the box. The indeterminate state usually means some change elsewhere on the page has likely affected the setting of the checkbox, requiring the user to verify the checkbox's setting for accuracy. An "indeterminate" checkbox is submitted with the form.


Input Types

checkbox


Example

 document.orderForm.2DayAir.indeterminate = true; 


Value

Boolean value: true | false.


Default

false


Web Forms 2.0 extension (adopted whole from the W3C XForms 1.0 specification at http://www.w3.org/TR/xforms/sliceE.html) that directs the browser to display the appropriate text input user interface for a written language. Consult the W3C XForms 1.0 documents for details.


Input Types

email, password, text, url


Example

 document.orderForm.searchText.inputmode = "hiragana"; 


Value

Written language script token with an optional modifier token (space-delimited). Tokens generally correspond to Unicode scripts (http://www.unicode.org/unicode/reports/tr24/).


Default

None.


Web Forms 2.0 extension that returns an array (HTMLCollection) of references to label element objects associated with the current form control element.


Input Types

All rendered types.


Example

 var textboxLabels = document.getElementById("searchBox").labels; 


Value

Array of label element object references.


Default

Empty array.


Web Forms 2.0 extension associates a set of predefined entries tailored for the input type, yet the input element also allows for text entry of a value not in the list. Predefined entries are coded as option elements inside a Web Forms 2.0 datalist element. The list attribute's value is the ID of the datalist element containing the predefined entries. In Opera's implementation, predefined entries appear as a pick list below the input element when the element has focus.


Input Types

date, datetime, datetime-local, email, month, number, range, text, time, url, week


Example

 var whichList = document.getElementById("opsystems").list; 


Value

Reference to the associated datalist element object.


Default

None.


If you specify a video clip with the dynsrc attribute, the loop property controls how many times the clip should play (loop). See the loop property of the img object for more details.


Input Types

image


Provides the URL of a lower-resolution (or alternate) image to download into the document space if the image of the src attribute will take a long time to download. See the lowsrc property of the img object for more details.


Input Types

image


Web Forms 2.0 extension that lets you specify the minimum and maximum values for an input element designed for numeric, date, time, and file upload data. If a user enters values outside of these boundaries, the browser sets the rangeUnderflow or rangeOverflow properties of the ValidityState object, which scripts may inspect for further error indications to the user.


Input Types

date, datetime, datetime-local, file, month, number, range, time, week


Example

 document.getElementById("apptTime").min = "09:00"; document.getElementById("apptTime").max = "17:00"; 


Value

For number and range types, a positive or negative integer or floating-point number; for date type, an ISO 8601 format value (e.g., 2007-03-15); for combinations of date and time, an ISO 8601 format value (e.g., 2007-03-15T08:00:00, with a trailing Z if not the local variant); for month type, an ISO format value (e.g., 2007-03); for week type, an ISO 8601 format value (e.g., 2007W3); for file type, a positive integer indicating the number of allowed files to be uploaded with the form.


Default

None.


Defines the maximum number of characters that may be typed into a text field input element. In practice, browsers beep or otherwise alert users when a typed character would exceed the maxlength value. There is no innate correlation between the maxlength and size attributes. If the maxlength allows for more characters than fit within the specified width of the element, the browser provides horizontal scrolling (albeit awkward for many users) to allow entry and editing of the field.


Input Types

password, text


Example

 document.getElementById("ZIP").maxlength=10; 


Value

Positive integer.


Default

Unlimited.


Web Forms 2.0 extension (when used with other extensions, such as the action attribute) that allows a submission for the enclosing form to a URI different and even method from the regular form when the element is clicked (and its type is set to submit).


Input Types

image, submit


Example

 document.getElementById("submitHere").method = "get"; 


Value

String of method type.


Default

get


This is the identifier associated with the form control. The value of this property is submitted as one-half of the name/value pair when the form is submitted to the server. Names are hidden from user view, since control labels are assigned via other means, depending on the control type. Form control names may also be used by script references to the objects. Despite the modern standards' preference for the id attribute, many browsers still require that a form control be assigned a name attribute to allow the control's value to be submitted.


Example

 document.orderForm.myButton.name = "Win32"; 


Value

Case-sensitive string identifier that follows the rules of identifier naming: it may contain no whitespace, cannot begin with a numeral, and should avoid punctuation except for the underscore character.


Default

None.


Web Forms 2.0 extension that lets you specify a regular expression pattern that the user's input must match to pass validation.


Input Types

email, password, text, url


Example

 document.getElementById("partNum").pattern = "[A-Z][0-9]{7}" 


Value

A regular expression (but not surrounded by the slash symbols, as used in JavaScript regular expressions).


Default

None.


Specifies whether the form element can be edited on the page by the user. A form control that has a readOnly property set to TRue may still be modified by scripts, even though the user may not alter the content.


Input Types

password, text


Example

 if (document.forms[0].myText.readOnly) {     ... } 


Value

Boolean value: TRue | false.


Default

false


Web Forms 2.0 extension that associates instructions to a submission form control with how to process the data returned from the server after the form is submitted. The choice is whether the response replaces the original document in the browser (the default) or the browser should apply returned values to the form, rather than retrieve initial form data (if a URL is assigned to the data attribute of the form element).


Input Types

image, submit


Example

 document.getElementById("submitMe").replace = "values"; 


Value

One of two string values: document | values.


Default

document


Web Forms 2.0 extension that signifies whether the input element's value is required for submission. Sets the missingValue property of the ValidityState object to TRue if the element receives no value.


Input Types

checkbox, date, datetime, datetime-local, email, file, month, number, password, radio, range, text, time, url, week


Value

Boolean value: true | false.


Default

false


Web Forms 2.0 extension that returns a reference to the option element (within a datalist element) currently selected by the user. In Opera 9, the property is implemented, but always returns null.


Input Types

date, datetime, datetime-local, email, month, number, range, text, time, url, week


Example

 var optionElem = document.getElementById("opsystems").selectedOption; 


Value

Reference to the selected option element object.


Default

None.


The selectionEnd and selectionStart properties are convenience properties that allow scripts to get and set the endpositions of a text selection within a text-oriented input element. Values are zero-based integer counters of positions between characters in the text entered into the field. When both properties have the same value, the visual result is the same as a text insertion pointer. For example, to place the cursor at the end of a text box, set the two values to the element's text length (see the textLength property). The equivalent IE functionality requires creating an IE text range in the element, adjusting the range's endpoints, and selecting the range (see the Textrange object).


Input Types

password, text


Example

 var elem = document.forms[0].myPassword; elem.selectionEnd = elem.textLength; elem.selectionStart = elem.textLength; 


Value

Positive integer.


Default

None.


Roughly speaking, the width in characters that the input box should be sized to accommodate. In practice, the browser does not always accurately predict the proper width even when all characters are the same, as they are in the password object. See details in the size attribute discussion for the input element in Chapter 1. There is no interaction between the size and maxLength properties for this object.


Input Types

password, text


Example

 document.forms[0].myPassword.size = 12; 


Value

Integer.


Default

20


Provides the relative or complete URL of the image file currently loaded or to be loaded into the image-type input element. See the src property of the img object for more details.


Input Types

image


If you specify a video clip with the dynsrc attribute, the start property controls the action that causes the clip to start running. See the start property of the img object for more details.


Input Types

image


Specifies whether the element is highlighted/checked. This property is identical to the checked property.


Input Types

checkbox, radio


Example

 if (document.forms[0].56KbpsBox.status) {     ... } 


Value

Boolean value: true | false.


Default

None.


Web Forms 2.0 extension that lets you specify the incremental values permitted in the input element. If a min and/or max attribute is set, those values set boundaries for data entered by the user; otherwise, a zero boundary is used (with 1970-01-01T00:00:00.0Z being the zero point for date-related elements).


Input Types

date, datetime, datetime-local, file, month, number, range, time, week


Example

 document.getElementById(""apptTime").step = "900"; 


Value

For number and range types, a positive or negative integer or floating-point number as a string; for date, week, and month types, an integer (as a string) representing a number of days, weeks, or months, respectively; for combinations of date and time, a number of seconds as a string.


Default

60 (datetime, datetime-local, time); 1 (others).


Web Forms 2.0 extension that allows (in concert with other attributes, such as action) the page returned from a submission of the enclosing form to appear in a window or frame different from the destination of the page returned from a regular form when a submit-type element is clicked.


Input Types

image, submit


Example

 document.getElementById("submitMe").target = "_blank"; 


Value

Frame or window name as a string.


Default

None (signifying the current window or frame).


Returns the type of form control element. The value is returned in all lowercase letters. It may be necessary to cycle through all form elements in search of specific types to do some processing on (e.g., emptying all form controls of type "text" while leaving other controls untouched). See the input element's type attribute description in Chapter 1 for more details about each type.


Input Types

All types.


Example

 if (document.forms[0].elements[3].type == "button") {     // process button input type here } 


Value

Any of the following constants (as a string): button | checkbox | file | hidden | image | password | radio | reset | select-multiple | select-one | submit | text | textarea (image type is not accessible to pre-Mozilla Netscape Navigator). Web Forms 2.0 browsers (like Opera 9) have the following additional type string values: add | date | datetime | datetime-local | email | month | move-down | move-up | number | range | remove | time | url | week.


Default

text


Provides the URL of the map element in the same document that contains client-side image map hot areas and links to be applied to the image. See the useMap property of the img object for more details.


Input Types

image


Web Forms 2.0 extension that returns a browser-generated message if the form control fails to validate according to its specifications. This property is meant more for text-oriented form controls, where an empty string means that the entry validates properly. For a button element, this property is always an empty string.


Input Types

All types, including special Web Forms 2.0 types.


Value

Empty string.


Default

Empty string.


Web Forms 2.0 extension that returns a ValidityState object. For a button element, all members of the returned object are false, except for the valid property, which is true. See the ValidityState object.


Input Types

All types, including special Web Forms 2.0 types.


Value

ValidityState object.


Default

ValidityState object.


Indicates the current value associated with the form control that is submitted with the name/value pair for the element. All values are strings, and it is through this property that scripts insert text into text fields. Browsers return the actual characters typed by the user, including the password type so you can retrieve an entered password for further processing before submission (or perhaps for storage in the cookie). For a button type, the value property controls the label of a form control: the text that appears on the button. A button input element is not submitted with the form.


Input Types

All types except image.


Example

 document.forms[0].myButton.value = "Undo"; 


Value

String.


Default

None.


Web Forms 2.0 extension that returns the value of the form control in a standardized fashion, as noted below.


Input Types

datetime, date, time, week, month.


Value

String values as follows: for datetime type, the selected value in a form like that of the toString( ) method of a JavaScript date object (e.g., Sat, 26 Aug 2006 07:06:00 GMT-0700); for date type, the selected date at 00:00 UTC; for time type, the selected time on January 1, 1970; for week type, the date value of the Monday at 00:00 UTC for the selected week; for month type, the first day of the selected month at 00:00 UTC. For all other types, null.


Default

null


Web Forms 2.0 extension that returns a number (where possible) representing the entered data. Date and time types are converted to milliseconds since January 1, 1970 at 00:00 UTC.


Input Types

All text entry types.


Value

Number value or NaN.


Default

NaN


See height.


Web Forms 2.0 extension that returns a Boolean value indicating whether the form control element meets criteria for validating under the Web Forms 2.0 mechanism. A button element is not one of the correct types, and therefore always returns false.


Input Types

All types.


Value

Boolean value: TRue | false.


Default

false


Web Forms 2.0 method that returns a Boolean value representing whether the form control element meets its validity criteriaultimately, whether the validity.valid property is true.


Input Types

All types.


Returned Value

Boolean value: true | false. Always TRue for button type elements.


Parameters

None.


Creates a TexTRange object containing the button's label text. See the Textrange object for details.


Input Types

password, text


Returned Value

Textrange object.


Parameters

None.


Web Forms 2.0 methods that fire the change and formchange events on the current element. You could, for example "convert" a click event to a change or formchange event by having the onclick event handler invoke either method.


Input Types

All types.


Returned Value

None.


Parameters

None.


handleEvent( event)

Instructs the object to accept and process the event whose specifications are passed as the parameter to the method. The object must have an event handler for the event type to process the event. Navigator 4 only.


Input Types

button | checkbox | file | password | radio | reset | select-multiple | select-one | submit | text | textarea


Returned Value

None.


Parameters


event

A Navigator 4 event object.


Selects all the text displayed in the form element. Usually requires that the element have focus prior to invoking this method.


Input Types

password, text


Returned Value

None.


Parameters

None.


setCustomValidity([ errorString])

Web Forms 2.0 method that sets the customError Boolean value of the validity property (itself a ValidityState object). If the method does not impact an element type, it throws a NOT_SUPPORTED_ERR error.


Input Types

All types.


Returned Value

None.


Parameters


errorString

If null or an empty string, the parameter resets the validity object's customError property, signifying the form control is not valid. An error string is to be remembered by the browser (during the current session) so that it displays the string upon subsequent validation failures.


The ins object reflects the ins element.


HTML Equivalent

<ins>


Object Model Reference

 [window.]document.getElementById("elementID") 


Object-Specific Properties

cite
dateTime

Object-Specific Methods

None.


Object-Specific Events

None.


These two properties are listed among the shared properties earlier in this chapter due to an IE implementation oddity. IE 5/Macintosh and W3C DOM browsers correctly implement these properties only for the del and ins objects, as specified in the W3C DOM, but in no mainstream browser do they convey any special powers. See the shared cite and dateTime properties earlier in this chapter.


The isindex object reflects the ancient HTML isindex element. IE arbitrarily converts this element into a text-type input object in its DOM, and even creates a form element around it. Avoid using this element.


HTML Equivalent

<isindex>


Object-Specific Properties

prompt


Provides the prompt message for the text entry field.


Value

String.


Default

None.


See abbr.


The label object reflects the label element.


HTML Equivalent

<label>


Object Model Reference

 [window.]document.getElementById("elementID") 


Object-Specific Properties

control
dataFld
dataFormatAs
dataSrc
form
forms
htmlFor

Object-Specific Methods

None.


Object-Specific Events

None.


Web Forms 2.0 extension that returns a reference to the input element with which the current label element is associated.


Example

 var inpElem = document.getElementById("myLabel").control; 


Value

Reference to an input element


Default

None.


Used with IE data binding to associate a remote data source column name with the displayed text of the input element label. A datasrc attribute must also be set for the element. Setting both the dataFld and dataSrc properties to empty strings breaks the binding between element and data source. Works only for text data sources in IE 5 for the Macintosh.


Example

 document.getElementById("myLabel").dataFld = "labelText"; 


Value

Case-sensitive string identifier of the data source column.


Default

None.


Used with IE data binding, this property advises the browser whether the source material arriving from the data source is to be treated as plain text or as tagged HTML. Works only for text data sources in IE 5 for the Macintosh.


Example

 document.forms[0].myLabel.dataFormatAs = "html"; 


Value

IE 4 recognizes two possible settings: text | html.


Default

text


Used with IE data binding to specify the ID of the page's object element that loads the data source object for remote data access. Setting both the dataFld and dataSrc properties to empty strings breaks the binding between element and data source. Works only for text data sources in IE 5 for the Macintosh.


Example

 document.getElementById("myLabel").dataSrc = "DBSRC3"; 


Value

Case-sensitive identifier of the data source.


Default

None.


Returns a reference to the next outermost form element object in the document tree. Multiple label element objects within the same form element reference the same form element object.


Example

 var theForm = document.getElementById("myLabel").form; 


Value

Reference to a form element object.


Default

None.


Web Forms 2.0 extension that returns an array (NodeList type) containing references to the form elements with which the input element contained by the current label element is associated.


Example

 var inpForms = document.getElementById("myLabel").forms; 


Value

Reference to an input element


Default

None.


Provides the element id of the input element to which the label is associated (the value of the for attribute). Binds the label element to a particular input element.


Example

 document.getElementById("label3").htmlFor = "chkbox3"; 


Value

String.


Default

None.


The layer object reflects the layer and ilayer elements. Found in Navigator 4 only. Other elements (such as div and span) that have style sheet position attributes set to absolute or relative are arbitrarily converted to layer objects in Navigator 4.


HTML Equivalent

 <ilayer> <layer> 


Object Model Reference

 [window.]document.layerName 


Object-Specific Properties

above
background
below
bgColor
clip
hidden
left
name
pageX
pageY
parentLayer
siblingAbove
siblingBelow
src
top
visibility
zIndex

Object-Specific Methods

captureEvents( )
handleEvent( )
load( )
moveAbove( )
moveBelow( )
moveBy( )
moveTo( )
moveToAbsolute( )
releaseEvents( )
resizeBy( )
resizeTo( )
routeEvent( )

Object-Specific Events

Handler

NN

Others

DOM

blur

4

n/a

n/a

focus

4

n/a

n/a

load

4

n/a

n/a

mouseout

4

n/a

n/a

mouseover

4

n/a

n/a

mouseup

4

n/a

n/a



Return a reference to the positionable element whose stacking z-order is above or below the current element. These properties operate in the context of all positionable elements in a document. If the current element is the highest element, the above property returns null. To restrict the examination of next higher or lower elements within a single layer context, see siblingAbove and siblingBelow. To adjust the stacking order with respect to specific objects, see the moveAbove( ) and moveBelow( ) methods.


Example

 var nextHigher = document.myILayer.above; 


Value

Object reference or null.


Default

None.


This property holds an image object that has a src property that can be set to change the image used for the layer's background. In other words, you must set the src property of the layer's background object to change the image.


Example

 document.myIlayer.background.src = "images/newlogo.gif"; 


Value

An image object property, such as src.


Default

None.


Provides the background color of the element. While you may set the value with either a hexadecimal triplet or plain-language color value, values returned from the property are for some reason the decimal equivalent of the hexadecimal RGB version. The default behavior is a transparent background created with a bgColor property value of null.


Example

 document.myIlayer.bgColor = "yellow"; 


Value

A hexadecimal triplet or plain-language color name. See Appendix A for acceptable plain-language color names. Returned values are the decimal equivalent of the hexadecimal value. A value of null sets the background to transparent.


Default

null (TRansparent).


Defines a clipping region of a positionable element. This property is treated more like an object in itself, in that you adjust its values through six properties: clip.top, clip.left, clip.bottom, clip.right, clip.width, and clip.height. Adjust the side(s) or dimension(s) of your choice. All values represent pixel values.


Example

 document.myIlayer.clip.width = 150; 


Value

Integer.


Default

None.


Specifies whether the object is visible on the page. When the object is hidden, its surrounding content does not close the gap left by the element.


Example

 document.myIlayer.hidden = false; 


Value

Boolean value: TRue | false.


Default

false


For positionable elements, defines the position (in pixels) of the left edge of an element's box (content plus left padding, border, and/or margin) relative to the left edge of the next outermost block content container. For the relative-positioned layer, the offset is based on the left edge of the inline location of where the element would normally appear in the content.


Example

 document.myIlayer.left = 45; 


Value

Integer.


Default

0


This is the identifier associated with a layer for use as the value assigned to target attributes or as script references to the frame. If no value is explicitly assigned to the id attribute, Navigator automatically assigns the name attribute value to the id attribute.


Example

 if (document.layers[2].name == "main") {     ... } 


Value

Case-sensitive identifier that follows the rules of identifier naming: it may contain no whitespace, cannot begin with a numeral, and should avoid punctuation except for the underscore character.


Default

None.


Provide the horizontal (x) and vertical (y) position of the object relative to the top and left edges of the entire document.


Example

 document.myIlayer.pageX = 400; 


Value

Integer.


Default

None.


Returns a reference to the next outermost layer in the containment hierarchy. For a single layer in a document, its parentLayer is the window object.


Example

 if (parentLayer != window) {     ... } 


Value

Object reference (a layer or window).


Default

window


Return a reference to the positionable element whose stacking z-order is above or below the current element, but only within the context of the shared parentLayer. If the current element is the highest element, the siblingAbove property returns null. To widen the examination of next higher or lower elements to a document-wide context, see above and below. To adjust the stacking order with respect to specific objects, see the moveAbove( ) and moveBelow( ) methods.


Example

 var nextHigher = document.myILayer.siblingAbove; 


Value

Object reference or null.


Default

None.


Indicates the URL of the external content file loaded into the current element. To change the content, assign a new URL to the property.

Assigning a new URL to this property does not work with inline layers (ilayer elements) in Navigator 4. Instead the current source document is removed, and other page elements can be obscured. Avoid setting this property for inline layers. The same goes for the load( ) method.


Example

 document.myIlayer.src = "swap2.html"; 


Value

Complete or relative URL as a string.


Default

None.


For positionable elements, defines the position of the top edge of an element's box (content plus top padding, border, and/or margin) relative to the top edge of the next outermost block content container. All measures are in pixels. When the element is a relative-positioned inline layer, the offset is based on the top edge of the inline location of where the element would normally appear in the content.


Example

 document.myIlayer.top = 50; 


Value

Integer.


Default

0


Indicates the state of the positioned element's visibility. Surrounding content does not close the space left by an element whose visibility property is set to hide (or the CSS version, hidden). If you set the property to the CSS syntax values (hidden | visible), they are converted internally to the JavaScript versions and returned from the property in that format.


Example

 document.myIlayer.visibility = "hide"; 


Value

One of the constant values (as a string): hide | inherit | show.


Default

inherit


For a positioned element, determines the stacking order relative to other elements within the same parent container. See Online Section IV for details on relationships of element layering amid multiple containers.


Example

 document.myIlayer.zIndex = 3; 


Value

Integer.


Default

0


captureEvents( eventTypeList)

Instructs the browser to grab events of a specific type before they reach their intended target objects. The object invoking this method must then have event handlers defined for the given event types to process the event.


Returned Value

None.


Parameters


eventTypeList

A comma-separated list of case-sensitive event types as derived from the available Event object constants, such as Event.CLICK or Event.MOUSEMOVE.


handleEvent( event)

Instructs the object to accept and process the event whose specifications are passed as the parameter to the method. The object must have an event handler for the event type to process the event.


Returned Value

None.


Parameters


event

A Navigator 4 event object.


load(" URL", newLayerWidth)

This method lets you load a new document into a layer object. It does not work properly in Navigator 4 for ilayer elements. The existing document is unloaded from the layer, but the new one does not load as you'd expect. There is no satisfactory workaround except to transform the element into a layer.


Returned Value

Boolean value: true if the document loading was successful.


Parameters


URL

String value of the complete or relative URL of the document to be loaded into the layer.


newLayerWidth

Integer value in pixels of a resized width of the element to accommodate the new content.


moveAbove( layerObject) moveBelow( layerObject)

These methods shift the z-order of the current layer to a specific location relative to another, sibling layer. This is helpful if your script is not sure of the precise zIndex value of a layer you want to use as a reference point for the current layer's stacking order. Use moveAbove( ) to position the current layer immediately above the layer object referenced as a parameter.


Returned Value

None.


Parameters


layerObject

Reference to another layer object that shares the same parent as the current layer.


moveBy( deltaX, deltaY)

A convenience method that shifts the location of the current element by specified pixel amounts along both axes. To shift along only one axis, set the other value to zero. Positive values for deltaX shift the element to the right; negative values to the left. Positive values for deltaY shift the element downward; negative values upward. This method comes in handy for path animation under the control of a setInterval( ) or setTimeout( ) method that moves the element in a linear path over time.


Returned Value

None.


Parameters


deltaX

Positive or negative pixel count of the change in horizontal direction of the element.


deltaY

Positive or negative pixel count of the change in vertical direction of the element.


moveTo( x, y) moveToAbsolute( x, y)

Convenience methods that shift the location of the current element to a specific coordinate point. The differences between the two methods show when the element to be moved is nested inside another positioned container (e.g., a layer inside a layer). The moveTo( ) method uses the coordinate system of the parent container; the moveToAbsolute( ) method uses the coordinate system of the page. For a single layer on a page, the two methods yield the same result.


Returned Value

None.


Parameters


x

Positive or negative pixel count relative to the top of the reference container, whether it is the next outermost layer (moveTo( )) or the page (moveToAbsolute( )).


y

Positive or negative pixel count relative to the left edge of the reference container, whether it is the next outermost layer (moveTo( )) or the page (moveToAbsolute( )).


releaseEvents( eventTypeList)

The opposite of layerObj.captureEvents( ), this method turns off event capture at the layer level for one or more specific events named in the parameter list. See Online Section VI.


Returned Value

None.


Parameters


eventTypeList

A comma-separated list of case-sensitive event types as derived from the available Event object constants, such as Event.CLICK or Event.MOUSEMOVE.


resizeBy( deltaX, deltaY)

A convenience method that shifts the width and height of the current element by specified pixel amounts. To adjust along only one axis, set the other value to zero. Positive values for deltaX make the element wider; negative values make the element narrower. Positive values for deltaY make the element taller; negative values make the element shorter. The top and left edges remain fixed; only the right and bottom edges are moved.


Returned Value

None.


Parameters


deltaX

Positive or negative pixel count of the change in horizontal dimension of the element.


deltaY

Positive or negative pixel count of the change in vertical dimension of the element.


resizeTo( x, y)

Convenience method that adjusts the height and width of the current element to specific pixel sizes. The top and left edges of the element remain fixed, while the bottom and right edges move in response to this method.


Returned Value

None.


Parameters


x

Width in pixels of the element.


y

Height in pixels of the element.


routeEvent( event)

Used inside an event handler function, this method directs Navigator to let the event pass to its intended target object.


Returned Value

None.


Parameters


event

A Navigator 4 event object.


The legend object reflects the legend element. A legend element must be nested inside and immediately after the fieldset element associated with a form or group of form controls.


HTML Equivalent

<legend>


Object Model Reference

 [window.]document.getElementById("elementID") 


Object-Specific Properties

align
form
forms

Object-Specific Methods

None.


Object-Specific Events

None.


Controls the alignment of the legend element with respect to the containing fieldset element. The permissible values do not always work as planned in Internet Explorer 4. Be sure to check your desired setting on all operating system platforms of your intended audience.


Example

 document.getElementById("myLegend").align = "center"; 


Value

Any one of the following constant values (as a string): bottom | center | left | right | top.


Default

left


Returns a reference to the next outermost form element object in the document tree. Multiple legend element objects within the same form element reference the same form element object.


Example

 var theForm = document.getElementById("myLegend").form; 


Value

Reference to a form element object.


Default

None.


Web Forms 2.0 extension that returns an array (NodeList type) containing references to the form elements with which the input element contained by the current legend element is associated.


Example

 var inpForms = document.getElementById("myLegend").forms; 


Value

Reference to an input element


Default

None.


The li object reflects the li element nested inside an ol or ul element.


HTML Equivalent

<li>


Object Model Reference

 [window.]document.getElementById("elementID") 


Object-Specific Properties

type
value

Object-Specific Methods

None.


Object-Specific Events

None.


Indicates the manner in which the leading bullets, numbers, or letters of items in the list are displayed. Bullet styles are displayed when the li element is nested inside a ul element; numbers and letters are displayed for an ol element. If your script changes the type for a single li object, be aware that the change affects all subsequent li elements in the same list.


Example

 document.getElementById("instruxListItem3").type = "a"; document.getElementById("point4").type = "square"; 


Value

For an ol style list, possible values are: A | a | I | i | 1. Sequencing is performed automatically as shown in the following table.

Type

Example

A

A, B, C, ...

a

a, b, c, ...

I

I, II, III, ...

i

i, ii, iii, ...

1

1, 2, 3, ...


For a ul-style list, possible values are: circle | disc | square.


Default

1 and disc (although values are empty unless the corresponding attribute is explicitly assigned).


Indicates the number of the item within an ordered list. This property applies to an li element only when it is nested inside an ol element, and only when the corresponding attribute is explicitly assigned in the HTML code. The default value for unadjusted numbering is always 0 in IE, Safari, and Opera and -1 in Mozilla. If you set the value property of one item in the list, the following items continue the sequence from the new value. Modifying the property value does not adjust the rendered numbering.


Example

 if (document.getElementById("step5").value > 0) {     ... } 


Value

Integer.


Default

0 or -1.


The link object reflects the link element. Note that many of the properties listed here are not available for scripting in the object unless their corresponding attributes are set initially in the HTML tag. Moreover, because the element's attributes act as directives while the document loads, assigning new values to the corresponding properties generally has no effect (even though the properties are read/write). This includes: href, rel, rev, and type. As a reminder, the disabled property (described among the shared properties earlier in this chapter) lets all supporting browsers turn on and off a linked style sheet.


HTML Equivalent

<link>


Object Model Reference

 [window.]document.getElementById("elementID") 


Object-Specific Properties

charset
href
hreflang
media
rel
rev
sheet
styleSheet
target
type

Object-Specific Methods

None.


Object-Specific Events

Event

IE

Opera 9

Others

DOM

error

·

·

load

·

·



Indicates the character encoding of the content at the other end of the link.


Example

 var charCoding = document.getElementById("myLink").charset; 


Value

Case-insensitive alias from the character set registry (ftp://ftp.isi.edu/in-notes/iana/assignments/character-sets).


Default

None.


Provides the URL specified by the element's href attribute. In IE/Windows, you can assign a new URL to this property to load in an alternate style sheet after the fact.


Example

 document.getElementById("styleLink").href = "altStyles.css"; 


Value

String of complete or relative URL.


Default

None.


Specifies the language code of the content at the destination of a link. Requires that the HRef attribute or property also be set.


Example

 document.getElementById("myLink").hreflang = "DE"; 


Value

Case-insensitive language code.


Default

None.


Specifies the intended output device for the content of the destination document pointed to by the HRef attribute. The media property looks forward to the day when browsers are able to tailor content to specific kinds of devices such as pocket computers, text-to-speech digitizers, or fuzzy television sets.


Example

 if (document.getElementById("link3").media == "print") {     // process for print output } 


Value

Any one of the following constant values as a string: all | print | screen.


Default

all


Defines the relationship between the current element and the external item pointed to by the link. Also known as a forward link, not to be confused in any way with the destination document whose address is defined by the HRef attribute. This property is not fully exploited in mainstream browsers, but you can treat the attribute as a kind of parameter to be checked and/or modified under script control.


Example

 if (document.getElementById("link3").rel == "alternate stylesheet") {     // process for alternate style sheet } 


Value

Case-insensitive, space-delimited list of HTML 4 standard link types (as a single string) applicable to the element. Sanctioned link types are:

alternate
appendix
bookmark
chapter
contents
copyright
glossary
help
index
next
prev
section
start
stylesheet
subsection

Default

None.


Defines the relationship between the current element and the destination of the link. Also known as a reverse link. This property is not fully exploited in mainstream browsers, but you can treat the attribute as a kind of parameter to be checked and/or modified under script control.


Value

Case-insensitive, space-delimited list of HTML 4 standard link types (as a single string) applicable to the element. See the rel property for sanctioned link types.


Default

None.


Returns a reference to the styleSheet object (CSSStyleSheet object in W3C DOM terminology) linked into the current document when a style sheet is specified as the target of the link element. IE for Windows provides a similar property: styleSheet.


Example

 var extSS = document.getElementById("link3").sheet; 


Value

styleSheet object reference.


Default

None.


This nonstandard convenience property returns a reference to the styleSheet object linked into the current document when a style sheet is specified as the target of the link element. Mozilla and Safari provide a similar property: sheet.


Example

 var extSS = document.getElementById("link3").styleSheet; 


Value

styleSheet object reference.


Default

None.


Indicates the window or frame name to be the recipient of linked content. Default value (equivalent of _self) is the desired setting for linked style sheets.


Example

 document.getElementById("link4").target = "frame2"; 


Value

String value of the window or frame name, or any of the following constants (as a string): _parent | _self | _top | _blank.


Default

None.


Indicates an advisory MIME type declaration about the data being loaded from an external source. For example, an external style sheet would be text/css. This information is usually set in the element tag's type attribute.


Example

 if (document.getElementById("myStyle").type == "text/css") {     ... } 


Value

MIME type string.


Default

None.


A collection of all a and area elements that have assigned HRef attributes that make them behave as links (instead of only anchors). Collection members are sorted in source code order. Navigator and Internet Explorer let you use array notation to access a single link in the collection (document.links[0] or document.links["section3"], for example). If you wish to use the link's name as an index value (always as a string identifier), be sure to use the value of the name attribute, rather than the id attribute. To use the id attribute in a reference to an anchor, access the object via a document.all.elementID (in IE only) or document.getElementById("elementID") reference.


Object Model Reference

 document.links 


Object-Specific Properties

length

Object-Specific Methods

item( )
namedItem( )
tags( )
urns( )

Object-Specific Events

None.


Returns the number of elements in the collection.


Example

 var howMany = document.links.length; 


Value

Integer.


item( index) item( index[, subindex])

Returns a single object or collection of objects corresponding to the element matching the index value (or, optionally in IE/Windows, the index and subindex values).


Returned Value

One object or collection (array) of objects. If there are no matches to the parameters, the returned value is null.


Parameters


index

When the parameter is a zero-based integer (as required for Mozilla), the returned value is a single element corresponding to the said numbered item in source code order (nested within the current element). When the parameter is a string (allowed by IE/Windows), the returned value is a collection of elements with id or name properties that match that string.


subindex

If you specify a string value for the first parameter (in IE/Windows), you may use the second parameter to specify a zero-based integer to retrieve a specific element from the collection with id or name properties that match the first parameter's string value.


namedItem( IDOrName)

Returns a single object (in W3C DOM browsers) or collection of objects corresponding to the element matching the parameter string value.


Returned Value

One object (in W3C DOM browsers) or collection (array) of objects. If there are no matches to the parameters, the returned value is null.


Parameters


IDOrName

The string that contains the same value as the desired element's id or name attribute.


tags( tagName)

Returns a collection of objects (among all objects within the current collection) with tags that match the tagName parameter. Lets you distinguish among collections of a and area elements.


Returned Value

A collection (array) of objects. If there are no matches to the parameters, the returned value is an array of zero length.


Parameters


tagName

A string that contains the element tag, as in document.links.tags("a").


urns( URN)

Returns a collection of nested element objects that have behaviors attached to them and URNs that match the URN parameter.


Returned Value

A collection (array) of objects. If there are no matches to the parameters, the returned value is an array of zero length.


Parameters


URN

A string with a local or external behavior file URN.


The LinkStyle object is a W3C DOM abstract object that gets blended into the link element object. Through this blending, the Mozilla and Safari link element object gains the sheet property, which provides a reference to the styleSheet object linked into the current document through a link element.


Object Model Reference

 document.getElementById("linkElementID") 


Object-Specific Properties

sheet


Object-Specific Methods

None.


Object-Specific Events

None.


Returns a reference to the styleSheet object (CSSStyleSheet object in W3C DOM terminology) linked into the current document when a style sheet is specified as the target of the link element. IE for Windows provides a similar property for a link element object: styleSheet.


Example

 var extSS = document.getElementById("link3").sheet; 


Value

styleSheet object reference.


Default

None.


The listing object reflects the listing element.


HTML Equivalent

<listing>


Object Model Reference

 [window.]document.getElementById("elementID") 


Object-Specific Properties

None.


Object-Specific Methods

None.


Object-Specific Events

None.


There is one location object in each window or frame. The object stores all information about the URL of the document currently loaded into that window or frame. By assigning a new URL to the href property of the location object, you instruct the browser to load a new page into the window or frame. This is the primary way of scripting the loading of a new page:

 location.href = "newPage.html"; 

A script in one frame can reference the location object in another frame to load a new document into that other frame:

 parent.otherFrameName.location.href = "newPage.html"; 

Security restrictions prevent a script in one frame from accessing location object information in another frame if the document in the second frame does not come from the same domain (and the same server, unless the document.domain properties of the two documents are set to match) as the document with the nosy script. This prevents a rogue script from monitoring navigation in another frame to external web sites. In Navigator 4 and Mozilla, you can overcome the security restriction with the help of signed scripts, but the user still has to give explicit permission for a script to access location object information outside the script's domain.

As a window-related object, the location object is not part of the formal W3C DOM Level 1 or 2 specifications (which leave windows for future versions). But the location object and its properties are well-entrenched in scripting vernacular, and should continue to be supported for a long time coming.


Object Model Reference

 [windowRef.]location 


Object-Specific Properties

hash
host
hostname
href
pathname
port
protocol
search

Object-Specific Methods

assign( )
reload( )
replace( )

Object-Specific Events

None.


Indicates that portion of a URL following the # symbol, referring to an anchor location in a document. This property contains its data only if the user has explicitly navigated to an anchor, and is not just scrolling to it. Do not include the # symbol when setting the property.


Example

 location.hash = "section3"; 


Value

String.


Default

None.


Provides the combination of the hostname and port (if any) of the server that serves up the current document. If the port is explicitly part of the URL, the hostname and port are separated by a colon, just as they are in the URL.


Example

 if (location.host == "www.megacorp.com:80") {     ... } 


Value

String of hostname, optionally followed by a colon and port number.


Default

Depends on server.


Provides the combination of the hostname of the server (i.e., a two-dot address consisting of server name and domain) that serves up the current document. The hostname property does not include the port number.


Example

 if (location.hostname == "www.megacorp.com") {     ... } 


Value

String of hostname (server and domain).


Default

Depends on server.


Provides the complete URL of the document loaded in the window or frame. Assigning a URL to this property is how you script navigation to load a new document into the window or frame (although Internet Explorer also offers the equivalent window.navigate( ) method).


Example

 location.href = "http://www.megacorp.com"; 


Value

String of complete or relative URL.


Default

None.


Provides the pathname component of the URL. This consists of all URL information following the last character of the domain name, including the initial forward slash symbol.


Example

 location.pathname = "/images/logoHiRes.gif"; 


Value

String.


Default

None.


Provides the port component of the URL, if one exists. This consists of all URL information following the colon after the last character of the domain name. The colon is not part of the port property value.


Example

 location.port = "80"; 


Value

String (a numeric value as string).


Default

None.


Provides the protocol component of the URL. This consists of all URL information up to and including the first colon of a URL. Typical values are: "http:", "file:", "ftp:", and "mailto:".


Example

 if (location.protocol == "file:") {     // statements for treating document as local file } 


Value

String.


Default

None.


Provides the URL-encoded portion of a URL that begins with the ? symbol. A document that is served up as the result of the search also may have the search portion available as part of the window.location property. You can modify this property by script. Doing so sends the URL and search criteria to the server. You must know the format of data (usually name/value pairs) expected by the server to perform this properly. You can also pass string data between separate pages by appending a search string to the next page's URL. While the search string appendage does not affect retrieval of the page, the string arrives with the new page in the new page's location object. A script in the new page can read and dissect the location.search property to place the passed values in variables that scripts in the page may use for their processing.


Example

 location.search="?p=Tony+Blair&d=y&g=0&s=a&w=s&m=25"; 


Value

String starting with the ? symbol.


Default

None.


assign(" URL")

This method was intended to be hidden from view of scripters, but remains available for now. It performs the same action as assigning a URL to the location.href property. The assign( ) method is listed here for completeness and should not be used.


Returned Value

None.


Parameters


URL

A string version of a complete or relative URL of a document to be loaded into a window or frame.


reload([ unconditional])

Performs a hard reload of the document associated with the location object. This kind of reload resets form elements to their default values (for a soft reload, use history.go(0)). By default, the reload( ) method performs a conditional-get action, which retrieves the file from the browser cache if the file is still in the cache (and the cache is turned on). To force a reload from the server, force an unconditional-get by adding the true Boolean parameter.


Returned Value

None.


Parameters


unconditional

An optional Boolean value. If TRue, the browser performs an unconditional-get to force a reload of the document from the server, rather than the browser cache.


replace(" URL")

Loads a new document into the reference window and replaces the browser's history listing entry of the current document with the entry of the new document. Thus, some interim page that you don't want appearing in history (to prevent the Back button from ever returning to the page) can be removed from the history and replaced with the entry of the newly loaded document.


Returned Value

None.


Parameters


URL

A string version of a complete or relative URL of a document to be loaded into a window or frame.


See directories.


The map object reflects the map element.


HTML Equivalent

<map>


Object Model Reference

 [window.]document.getElementById("elementID") 


Object-Specific Properties

areas[]
name

Object-Specific Methods

None.


Object-Specific Events

None.


Indicates a collection of all area element objects nested inside the map element.


Example

 for (var i = 0; i < document.getElementById("myMap").areas.length; i++) {     oneMap = document.getElementById("myMap").areas[i];     ... } 


Value

Array of area element objects.


Default

Array of length zero.


This is the identifier associated with the client-side image map specification. A map element contains all the area elements that define the hotspots of an image and their link destinations. The name assigned to the map element is the one cited by the usemap attribute of the img element. This binds the map definitions to the image.


Example

 document.getElementById("myMap").name = "altMap"; 


Value

Case-sensitive string identifier that follows the rules of identifier naming: it may contain no whitespace, cannot begin with a numeral, and should avoid punctuation except for the underscore character.


Default

None.


The marquee object reflects the marquee element. Mozilla's implementation is in the form of an XUL extension (built-in). A number of properties and methods used internally by the add-on are exposed to scripts, but there is little or no need to reference them. If you are interested in the inner workings, you can learn a lot by viewing the XML and JavaScript Mozilla source code for the module (http://lxr.mozilla.org/seamonkey/source/layout/style/xbl-marquee/xbl-marquee.xml).


HTML Equivalent

<marquee>


Object Model Reference

 [window.]document.getElementById("elementID") 


Object-Specific Properties

behavior
bgColor
dataFld
dataFormatAs
dataSrc
direction
height
hspace
loop
scrollAmount
scrollDelay
trueSpeed
vspace
width

Object-Specific Methods

start( )
stop( )

Object-Specific Events

Event

IE

Others

DOM

bounce

·

finish

·

start

·



Specifies the motion of the content within the rectangular space set aside for the marquee element. You have a choice of three motion types.


Example

 document.getElementById("newsBanner").behavior = "slide"; 


Value

Case-insensitive marquee element motion types:


alternate

Content alternates between marching left and right.


scroll

Content scrolls (according to the direction attribute or property) into view and out of view before starting again.


slide

Content scrolls (according to the direction attribute or property) into view, stops at the end of its run, blanks, and then starts again.


Default

scroll


Background color of the element. This color setting is not reflected in the style sheet backgroundColor property. Even if the bgcolor attribute or bgColor property is set with a plain-language color name, the returned value is always a hexadecimal triplet.


Example

 document.getElementById("myBanner").bgColor = "yellow"; 


Value

A hexadecimal triplet or plain-language color name. See Appendix A for acceptable plain-language color names.


Default

Inherits body background color.


Used with IE data binding to associate a remote data source column name with the content of the marquee element. A datasrc attribute must also be set for the element. Setting both the dataFld and dataSrc properties to empty strings breaks the binding between element and data source. Works only with text file data sources in IE 5/Mac.


Example

 document.getElementById("myBanner").dataFld = "hotNews"; 


Value

Case-sensitive string identifier of the data source column.


Default

None.


Used with IE data binding, this property advises the browser whether the source material arriving from the data source is to be treated as plain text or as tagged HTML.


Example

 document.getElementById("myBanner").dataFormatAs = "text"; 


Value

IE recognizes two possible settings: text | html.


Default

text


Used with IE data binding to specify the ID of the page's object element that loads the data source object for remote data access. Setting both the dataFld and dataSrc properties to empty strings breaks the binding between element and data source. Works only with text file data sources in IE 5/Mac.


Example

 document.getElementById("myBanner").dataSrc = "DBSRC3"; 


Value

Case-sensitive string identifier of the data source.


Default

None.


Specifies the direction of the scroll within the element space.


Example

 document.getElementById("myBanner").direction = "down"; 


Value

Four possible case-insensitive directions: down | left | right | up.


Default

left


Provide the height and width in pixels of the element. Changes to these values are immediately reflected in reflowed content on the page.


Example

 document.getElementById("myBanner").height = 250; 


Value

Integer.


Default

None.


Provide the pixel measure of horizontal and vertical margins surrounding the element. The hspace property affects the left and right edges of the element equally; the vspace affects the top and bottom edges of the element equally. These margins are not the same as margins set by style sheets, but they have the same visual effect.


Example

 document.getElementById("myBanner").hspace = 5; document.getElementById("myBanner").vspace = 8; 


Value

Integer of pixel count.


Default

0


Sets the number of times the element scrolls its content. After the final scroll, the content remains in a fixed position. Constant animation can sometimes be distracting to page visitors, so if you have the marquee turn itself off after a few scrolls, you may be doing your visitors a favor.


Example

 document.getElementById("myBanner").loop = 3; 


Value

Any positive integer if you want the scrolling to stop after that number of times. Otherwise, set the value to -1.


Default

-1


Specifies the amount of space between positions of each drawing of the content. The greater the space, the faster the text appears to scroll. See also scrollDelay.


Example

 document.getElementById("myBanner").scrollAmount = 4; 


Value

Positive integer.


Default

6


Specifies the amount of time in milliseconds between each drawing of the content. The greater the delay, the slower the text appears to scroll. See also scrollAmount.


Example

 document.getElementById("myBanner").scrollDelay = 100; 


Value

Positive integer.


Default

85 (Windows 95); 90 (Macintosh).


Specifies whether the browser should honor scrolldelay attribute settings below 60 milliseconds. The default setting (false) prevents accidental settings that scroll too fast for most readers.


Example

 document.getElementById("myBanner").trueSpeed = "true"; 


Value

Boolean value: true | false.


Default

false


See hspace.


See height.


Starts the marquee element scrolling if it has been stopped. If the method is invoked on a stopped element, the onstart event handler also fires in response.


Returned Value

None.


Parameters

None.


Stops the scrolling of the marquee element. The content remains on the screen in the precise position it was in when the method was invoked. Restart via the start( ) method.


Returned Value

None.


Parameters

None.


The MediaList object is an abstract representation in the W3C DOM of a collection of string names for media specified for a particular styleSheet object. The media property of a styleSheet object returns a value that is a MediaList object (IE 6 and 7 incorrectly return a string value). Media types (such as print, screen, aural, and so on) are specified for the style sheet either via the media attribute of a link element or an @media rule in a style element. Media support beyond print and screen types (and the default all type) is rather limited, so the details of this object are not yet important.


Object-Specific Properties

length
mediaText

Object-Specific Methods

appendMedium( )
deleteMedium( )
item( )

Object-Specific Events

None.


Returns the number of items in the collection.


Example

 var howMany = document.styleSheets[0].media.length; 


Value

Integer.


Returns the entire string of comma-delimited media names.


Example

 var allMedia = document.styleSheets[0].media.mediaText; 


Value

String.


appendMedium(" mediumType") deleteMedium(" mediumType")

Adds or removes a medium type from the list. In early (pre-1.0) Mozilla, the methods are incorrectly named append( ) and delete( ).


Returned Value

None.


Parameters


mediumType

String of recognized media type (e.g., print, screen).


item( index)

Returns one media name string from the collection corresponding to the item matching the index value in source code order.


Returned Value

String.


Parameters

index

A zero-based integer corresponding to the specified item in source code order.


The menu object reflects the menu element.


HTML Equivalent

<menu>


Object Model Reference

 [window.]document.getElementById("elementID") 


Object-Specific Properties

compact
type

Object-Specific Methods

None.


Object-Specific Events

None.


Provided for this element for the sake of compatibility with the W3C DOM standard. However, mainstream browsers do not act upon this property or its corresponding attribute.


Value

Boolean value: TRue | false.


Default

false


Implemented in IE 6 and 7 due to internal element relationships with the ol and ul element objects. Ignore for the menu element object.


See directories.


The meta object reflects the meta element.


HTML Equivalent

<meta>


Object Model Reference

 [window.]document.getElementById("elementID") 


Object-Specific Properties

charset
content
httpEquiv
name
scheme
url

Object-Specific Methods

None.


Object-Specific Events

None.


Indicates the character encoding of the content in the file associated with the HRef attribute. This property does not change the setting of the charset attribute of a name/value pair contained by the content attribute or property. For now the charset property has little or no effect on a document.


Example

 if (document.all.myMeta.charset == "csISO5427Cyrillic") {     // process for Cyrillic charset } 


Value

Case-insensitive alias from the character set registry (ftp://ftp.isi.edu/in-notes/iana/assignments/character-sets).


Default

Determined by browser.


This is the equivalent of the value of a name/value pair. The property's corresponding content attribute is usually accompanied by either a name or http-equiv attribute, either of which acts as the name portion of the name/value pair. Specific values of the content attribute vary with the value of the name or http-equiv attribute. Sometimes the content attribute value contains multiple values. In such cases, the values are delimited by a semicolon. Some of these multiple values may be name/value pairs in their own right, such as the content for a refresh meta element. The first value is a number representing the number of seconds of delay before loading another document; the second value is a name/value pair indicating a URL of the document to load after the delay expires.

Despite the following example, changing the content property on a loaded document may not produce the desired effect if the browser relies on the incoming value as the document loads.


Example

 document.getElementById("refreshMeta").content =   "5,http://www.giantco.com/basicindex.html"; 


Value

String.


Default

None.


This is the equivalent of the name of a name/value pair. The property's corresponding http-equiv attribute is usually accompanied by a content attribute, which acts as the "value" portion of the name/value pair. The author may elect to use the name attribute instead of the http-equiv attribute, but only one may be set. Adjust only the property corresponding to the attribute used in the meta element's tag. Then be sure to set the content property with a value that makes sense with the httpEquiv or name property.


Example

 document.getElementById("refreshMeta").httpEquiv = "expires"; 


Value

String.


Default

None.


This is an identifier for the name/value pair that constitutes the meta element. The value is typically a plain-language term that denotes the purpose of the meta element, such as "author" or "keywords". Either the name or httpEquiv properties can have a value, but not both, in the same meta element.


Example

 document.getElementById("detailMeta").name = "keywords"; 


Value

String.


Default

None.


Reflects the scheme attribute, but as yet has no particular functionality in current browsers. See the scheme attribute of the meta element in Chapter 1 for information about the intended purpose of this property.


Value

String.


Default

None.


Although implemented in IE browsers, this property no longer appears to be officially supported.


The mimeType object belongs to the navigator object. The object represents a MIME type specification. Its properties let scripts find out if the browser is equipped to handle a specific MIME type of external content before it is loaded from the server. All these properties are mirrored in the internal document displayed when you choose Navigator's About Plug-ins menu option. Internet Explorer 5 for the Macintosh implements this scheme, but Explorer for Windows uses an entirely different system for determining support for external media via the object element.


Object Model Reference

 navigator.mimeTypes[i] 


Object-Specific Properties

description
enabledPlugin
suffixes
type

Object-Specific Methods

None.


Object-Specific Events

None.


Returns the brief description of the plugin. This information is embedded in the plugin by its developer. Be aware that the precise wording of this description may vary for the same plugin written for different operating systems.


Example

 var descr = navigator.mimeTypes["video/mpeg"].description; 


Value

String.


Default

None.


Returns a plugin object reference corresponding to the plugin currently set to play any incoming data formatted according to the current MIME type. You can then dig deeper into properties of the returned plugin object to retrieve, say, its name.


Example

 var plugName = navigator.mimeTypes["video/mpeg"].enabledPlugin.name; 


Value

plugin object reference.


Default

None.


Returns a comma-delimited string list of file suffixes associated with the mimeType object, as supported by the plugin enabled for that MIME type. For example, the suffixes that the QuickTime plugin acknowledges for the type video/avi are:

 avi, vfw 

If you loop through all mimeType objects registered in the browser to find a match for a specific suffix, you can then find out whether the matching mimeType object has a plugin installed for it (via the enabledPlugin property).


Example

 var suff = navigator.mimeTypes["audio/mpeg"].suffixes; 


Value

String.


Default

None.


Returns a string version of the MIME type associated with the mimeType object. You could, for example, loop through all the mimeType objects in search of the one that matches a specific MIME type (application/x-midi) and examine that mimeType object further to see whether it is currently supported and enabled.


Example

 var MType = navigator.mimeTypes[3].type; 


Value

String.


Default

None.


The W3C DOM MouseEvent object is an abstract object that contains the properties and methods shared by every instance of a W3C DOM mouse-related event. This object inherits characteristics from the W3C DOM Event and UIEvent objects. The properties (information such as click coordinates) and methods of this object are blended into the directly scripted event object. See the discussion of the event object earlier in this chapter for specific property and method support for this object and how these items are inherited by more specific event types.


The W3C DOM MutationEvent object is an abstract object that contains the properties and methods shared by every instance of a W3C DOM event that concerns itself with the modification of the document tree. This object inherits characteristics from the W3C DOM Event. The properties (information such as references to the node affected by the change) and methods of this object are blended into the directly scripted event object. See the discussion of the event object earlier in this chapter for specific property and method support for this object and how these items are inherited by more specific event types.


See attributes.


The navigator object in many ways represents the browser application. As such, the browser is outside the scope of the document object model. Even so, the navigator object plays an important role in scripting, because it allows scripts to see what browser and browser version is running the script. In addition to several key properties that both Navigator and Internet Explorer have in common, each browser also extends the property listing of this object in ways that would generally benefit all browsers. IE duplicates this object under the clientInformation object name, but for cross-browser compatibility, you can use the navigator object reference in all browsers.


Object Model Reference

 navigator [window.]navigator 


Object-Specific Properties

appCodeName
appMinorVersion
appName
appVersion
browserLanguage
cookieEnabled
cpuClass
language
mimeTypes[]
onLine
oscpu
platform
plugins[]
product
productSub
securityPolicy
systemLanguage
userAgent
userLanguage
userProfile
vendor
vendorSub

Object-Specific Methods

javaEnabled( )
preference( )
taintEnabled( )

Object-Specific Events

None.


Reveals the code name of the browser. Almost all scriptable browsers and versions return Mozilla, which was the code name for an early version of Navigator (a combination of the early freeware name of the Mosaic browser and Godzilla). The Mozilla character is Netscape's corporate mascot, but all browsers that license the original Mosaic technology (including IE) return Mozilla.


Example

 var codeName = navigator.appCodeName; 


Value

Mozilla


Default

Mozilla


With succeeding generations of Internet Explorer, this property returns a dizzying range of values, most of which are not useful for typical version detection. IE 5.x for Windows returns an appVersion value of 4.0, with the appMinorVersion reporting the first digit to the right of the decimal. In IE 6 for Windows, the appMinorVersion returns a string signifying a build or patch code number, such as ;Q313675;. Use with extreme caution.


Example

 var subVer = navigator.appMinorVersion; 


Value

String.


Default

Depends on browser version.


Reveals the model name of the browser.


Example

 var isIE = navigator.appName == "Microsoft Internet Explorer"; 


Value

String values. Netscape Navigator, Mozilla, and Safari: Netscape; IE: Microsoft Internet Explorer; Opera 9: Opera. Some other browsers return these values to appear to be compatible with one of the mainstream browsers.


Default

Depends on browser.


Reveals a version number of the browser engine, along with minimal operating system platform information (a subset of the information returned by userAgent). Sample returned values are as follows.

Internet Explorer:

 4.0 (compatible; MSIE 6.0; Windows 98; Q312461) 4.0 (compatible; MSIE 7.0; Windows NT 5.1) 

Mozilla:

 5.0 (Macintosh; en-US) 

Safari:

 5.0 (Macintosh; U; PPC Mac OS X; en-us) AppleWebKit/418.8 (KHTML, like Gecko) Safari/419.3 

Opera:

 9.01 (Windows NT 5.1; U; en) 

Note that the version number at the start of the value (up to the first whitespace) is not necessarily indicative of the actual browser application version, but rather of the fundamental engine. Thus, IE application Versions 4 through 7 (and perhaps later) all report engine Version 4.0; Mozilla and Safari are based on what they term engine generation 5.0 (although they use entirely different engines). Browser application version information is found elsewhere either in the appVersion, userAgent, or other navigator object properties. Do not use the first word of the appVersion value for any kind of browser version detection that influences which DOM or JavaScript language features are supported by the browser. In browsers leading up to Version 4, this property correctly reflected the application version, but that is no longer the case.

While it may appear that the precise Internet Explorer version is embedded in this property's value (as MSIE X.XX), there are occasional mismatches in some versions. To inspect this portion of the version string, the navigator.userAgent property is more reliable.


Example

 var isVer4Min = parseInt(navigator.appVersion) >= 4; 


Value

String.


Default

Depends on browser.


Provides the default written language of the browser. Other browsers use the navigator.language property.


Example

 var browLangCode = navigator.browserLanguage; 


Value

Case-insensitive language code as a string, such as en.


Default

Browser default.


Returns whether the browser allows reading and writing of cookie data.


Example

 if (cookieEnabled) {     setCookieData(data); } 


Value

Boolean value: TRue | false.


Default

Depends on browser preference setting.


Returns a string reference of the CPU of the client computer. Common Intel microprocessors (including Pentium-class CPUs and Macintoshes running Windows emulators) return x86, while PowerPC Macintoshes return PPC. This value tells you only about the basic hardware class, not the operating system or specific CPU speed or model number.


Example

 if (navigator.cpuClass == "PPC") {     // statements specific to PowerPC clients } 


Value

String.


Default

Depends on client hardware.


Indicates the written language for which the browser version was created. The language is specified in the ISO 639 language code scheme (such as en-us). Internet Explorer provides this information via the navigator.browserLanguage property.


Example

 var mainLang = navigator.language; 


Value

Case-insensitive language code as a string.


Default

Browser default.


Returns an array of mimeType objects supported by installed plugins in the browser. IE for Windows provides this property for syntactical compatibility, but it always returns an array of zero length. See the mimeType object.


Example

 var videoPlugin = navigator.mimeTypes["video/mpeg"].enabledPlugin; 


Value

Array of mimeType objects.


Default

Browser default.


Specifies whether the browser is set for online or offline browsing. Pages may wish to invoke live server actions when they load in online mode, but avoid these calls when in offline mode. Use this Boolean property to build such conditional statements.


Example

 if (navigator.onLine) {     document.write("<applet ...>");     ... } 


Value

Boolean value: true | false.


Default

true


Returns a string containing operating system or central processing unit information about the client machine. Values vary widely across systems. Windows clients are divided roughly into two categories: non-NT and NT. The former includes Windows 95, 98, and ME (oscpu values of Win95, Win98, and Win 9x 4.90, respectively). The NT category includes Windows NT 4 (WinNT4.0) and Windows XP (Windows NT x.x). Macintosh systems all report the CPU type and the absence or presence of Mac OS X (PPC or PPC Mac OS X). Unix systems report both the operating system and CPU type. The oscpu value is also a part of the userAgent value. Formatting for this information is not the same in Internet Explorer's corresponding cpuClass or userAgent properties.


Example

 if (navigator.oscpu.indexOf("Win") != -1) {     document.write("You are running a Windows computer."); } 


Value

String.


Default

System dependent.


Returns the name of the operating system or hardware platform of the browser. For Windows 95/NT, the value is Win32; for a Macintosh running a PowerPC CPU, the value is MacPPC. At least for the major platforms I've been able to test, mainstream browsers agree on the returned values. Using this property to determine the baseline facilities of the client in a conditional expression can help the page optimize its output for the device.


Example

 if (navigator.platform == "Win32") {    document.write("<link rel='stylesheet' type='text/css' href='css/stylePC.css'>"); } 


Value

String.


Default

System dependent.


Returns a collection of plugin objects recognized by the browser to facilitate script determination of the browser's support for a particular external media type. IE 4 and later for Windows implement this property, but only as a dummy placeholder that always returns an array of length zero. See the mimeType and plugin objects.


Example

 var plugInCount = navigator.plugins.length; 


Value

Array of plugin object references.


Default

None.


Return a string identifying the software engine behind the browser. In Mozilla and Safari, the product property returns Gecko, while the productSub property returns a development build number (in string form).


Example

 var prod = navigator.product; 


Value

String.


Default

Browser dependent.


Returns a string in Navigator 4 revealing the browser's encryption level (that is, the domestic or export encryption policy to which the browser adheres). With the loosening of U.S. encryption export laws, Mozilla implements one encryption type across all versions. In Mozilla, this property returns an empty string.


Value

String.


Default

None.


Specifies the code for the default written language used by the operating system. If you have multi-lingual content available, you can use this property to insert content in specific languages.


Example

 if (navigator.systemLanguage == "nl") {// document.write( ) some Dutch content } 


Value

Case-insensitive language code.


Default

Usually the browser default (en for English-language Internet Explorer available in the United States).


Provides information about the browser software, including version, operating system platform, and brand. This is the most complete set of information about the browser, whereas appVersion and appName properties provide subset (and not always correct) data. Typical data for the userAgent property looks like the following examples from a selection of browsers:

 Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1) Mozilla/5.0 (Macintosh; U; PPC Mac OS X Mach-O; en-US; rv:1.8.0.6) Gecko/20060728 Firefox/1.5.0.6 Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en-us) AppleWebKit/418.8 (KHTML, like Gecko) Safari/419.3 Opera/9.01 (Windows NT 5.1; U; en) 

Do not rely on the length or position of any part of this data, as it may vary with the browser, version, and proxy server used at the client end. Instead, use the indexOf( ) method to check for the presence of a desired string. To extract only the actual application version number for IE, use the following function:

 function readIEVersion( ) {     var ua = navigator.userAgent;     var IEOffset = ua.indexOf("MSIE ");     return parseFloat(ua.substring(IEOffset + 5, ua.indexOf(";", IEOffset))); } 


Example

 if (navigator.userAgent.indexOf("MSIE") != -1) {     var isIE = true; } 


Value

String.


Default

Browser dependent.


The default written language of the browser, based on the operating system user profile setting (if one exists). The property defaults to the browserLanguage property.


Example

 var userLangCode = navigator.userLanguage; 


Value

Case-insensitive language code as a string.


Default

Browser default.


The userProfile property is, itself, an object that lets scripts request permission to access personal information stored in the visitor's user profile (for Win32 versions of Internet Explorer 4 through 6). See the userProfile object.


Example

 navigator.userProfile.addReadRequest("vcard.displayname"); navigator.userProfile.doReadRequest("3", "MegaCorp Customer Service"); var custName = navigator.userProfile.getAttribute("vcard.displayname"); navigator.userProfile.clearRequest( ); if (custName) {     ... } 


Value

userProfile object reference; null in IE 7.


Default

Browser default.


Return a string identifying the company that is using the browser engine. For example, Netscape 7 returns simply Netscape, while Safari returns Apple Computer, Inc. Mozilla's own product, Firefox, returns an empty string. The vendorSub property (not implemented in Safari) returns the version release in detail (in string form).


Example

 if (parseFloat(navigator.vendorSub, 10) >= 6.2) {     // OK, meets minimum Netscape requirement } 


Value

String.


Default

Browser dependent.


Returns whether Java is turned on in the browser. This method obviously won't help you in a nonscriptable browser (or scriptable browser that doesn't support the property), but if scripting is enabled, it does tell you whether the user has Java turned off in the browser preferences.


Returned Value

Boolean value: true | false.


Parameters

None.


preference( name[, value])

By way of signed scripts in Navigator 4 and Mozilla, you can access a wide variety of user preferences settings. These include even the most detailed items, such as whether the user has elected to download images or whether style sheets are enabled. Most of these settings are intended for scripts used by network administrators to install and control the user settings of enterprise-wide deployment of Navigator. Consult the Netscape developer web site for further information about these preferences settings (http://developer.netscape.com/docs/manuals/communicator/preferences/).


Returned Value

Preference value in a variety of data types.


Parameters


name

The preference name as a string, such as general.always_load_images.


value

An optional value to set the named preference.


Returns whether data tainting is turned on in the browser. This security mechanism was never fully implemented in Navigator, but the method that checks for it is still included in newer versions of Navigator and Mozilla for backward compatibility. Internet Explorer and Opera also include it for compatibility, even though it always returns false.


Returned Value

Boolean value: true | false.


Parameters

None.


The nobr object reflects the nobr element.


HTML Equivalent

<nobr>


Object Model Reference

 [window.]document.getElementById("elementID") 


Object-Specific Properties

None.


Object-Specific Methods

None.


Object-Specific Events

None.


The Node object is an abstract representation in the W3C DOM of the fundamental content building block in a document. All pieces of content that you can address in the W3C DOM model are nodes: unnamed contiguous strings of text between tags, tagged elements, name/value attribute pairs, special-purpose elements such as comments, DOCTYPE declarations, and even the document, itself, to name several.

A Node object has a large set of properties and methods, most of which concern a node's relationships to surrounding nodes. Properties listed below in all uppercase letters are either constants or bit masks. The objects in a document that scripts read and control are defined as descendants of the basic Node object; this means that the most common content-bearing objects that DHTML scripts work withHTML elements, text nodes, and element attributesall share this set of properties and methods to start (and are described at the beginning of this chapter among the shared properties and methods). Then, as needed for their powers as HTML elements, they accrue additional properties and/or methods that give them their special powers.

While the nodeness of the W3C DOM codifies the inheritance relationships among different pieces of a document's content, the model presents a conceptual framework and granularity that at times seems tedious compared to the shortcut HTML-ness of both the first-generation DOM and the Microsoft DOM. But the ultimate goal is to provide a single model that works for both XML and HTML documents (in either their pure HTML or XML-ized versions).


Object Model Reference

 Node 


Object-Specific Properties

ATTRIBUTE_NODE
CDATA_SECTION_NODE
DOCUMENT_FRAGMENT_NODE
COMMENT_NODE
DOCUMENT_NODE
DOCUMENT_POSITION_CONTAINED_BY
DOCUMENT_POSITION_CONTAINS
DOCUMENT_POSITION_DISCONNECTED
DOCUMENT_POSITION_FOLLOWING
DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC
DOCUMENT_POSITION_PRECEDING
DOCUMENT_TYPE_NODE
ELEMENT_NODE
ENTITY_NODE
ENTITY_REFERENCE_NODE
NOTATION_NODE
PROCESSING_INSTRUCTION_NODE
TEXT_NODE
attributes
baseURI
childNodes
firstChild
lastChild
localName
namespaceURI
nextSibling
nodeName
nodeType
nodeValue
ownerDocument
parentNode
prefix
previousSibling
textContent

Object-Specific Methods

appendChild( )
cloneNode( )
compareDocumentPosition( )
getFeature( )
getUserData( )
hasAttributes( )
hasChildNodes( )
insertBefore( )
isDefaultNamespace( )
isEqualNode( )
isSameNode( )
isSupported( )
lookupNamespaceURI( )
lookupPrefix( )
normalize( )
removeChild( )
replaceChild( )
setUserData( )

The NodeFilter object provides a mechanism for the NodeIterator and treeWalker objects to determine which nodes or classes of nodes are to be accepted or rejected for inclusion into one of the special node lists. The lone accept( ) method is invoked silently by the NodeInterator and treeWalker objects whenever the objects are asked to point to the next node in sequence. The NodeFilter object is also the holder of two sets of constants that are used in a variety of creation method calls and user-defined filter functions. See the treeWalker object for an example, and the document.createTreeWalker( ) method for application of the constants.


Object Model Reference

 NodeFilter 


Object-Specific Properties

FILTER_ACCEPT
FILTER_REJECT
FILTER_SKIP
SHOW_ALL
SHOW_ATTRIBUTE
SHOW_CDATA_SECTION
SHOW_COMMENT
SHOW_DOCUMENT
SHOW_DOCUMENT_FRAGMENT
SHOW_DOCUMENT_TYPE
SHOW_ELEMENT
SHOW_ENTITY
SHOW_NOTATION
SHOW_PROCESSING_INSTRUCTION
SHOW_TEXT

Object-Specific Methods

accept( )

Object-Specific Events

None.


accept( nodeReference)

Returns an integer signifying whether a node is to be included in the NodeIterator or TReeWalker object's list. This method is invoked automatically by the objects whenever one of their pointer-moving methods is invoked.


Returned Value

Integer value, each of which has a corresponding constant value associated with the NodeFilter object: 1 (NodeFilter.FILTER_ACCEPT); 2 (NodeFilter.FILTER_REJECT); 3 (NodeFilter.FILTER_SKIP).


Parameters


nodeReference

Reference to the document tree node under test. Passed automatically to the method when invoked by the NodeInterator and treeWalker objects.


The NodeIterator object is a "live" list of nodes that meet the criteria defined by the document.createNodeIterator( ) method. The list is a simple list of node references in source code order, but the list items do not bear any parent or descendant relationships to each other. The createNodeIterator( ) method describes the node where the list begins and which nodes (or classes of nodes) are exempt from the list by way of filtering (see the treeWalker object for an example of this kind of filtering).

The NodeIterator object maintains a kind of pointer inside the list (so that your scripts don't have to). Methods of this object let scripts access the next or previous node in the list, while moving the pointer one position in either direction. If scripts modify the document tree after the NodeIterator is created, changes to the document tree are automatically reflected in the sequence of nodes in the NodeIterator.


Object Model Reference

 NodeIteratorReference 


Object-Specific Properties

expandEntityReference
filter
root
whatToShow

Object-Specific Methods

detach( )
nextNode( )
previousNode( )

Object-Specific Events

None.


See these properties of the treeWalker object.


Disconnects the current NodeIterator object from the document tree. Items in the list are no longer accessible once the method is invoked.


Returned Value

None.


Parameters

None.


Moves the internal NodeIterator pointer one position forward (nextNode( )) or backward (previousNode( )), while returning a reference to the node through which the pointer passed en route.


Returned Value

Reference to a node in the document tree.


Parameters

None.


The NodeList object is an abstract representation in the W3C DOM of a collection of nodes of any type. Any W3C DOM property or method that returns a collection of nodes returns an object of type NodeList. For example, the Node object's childNodes property and the Element object's getElementsByTagName( ) method both return NodeList objects. JavaScript exposes a NodeList collections as an array that has the familiar length property. Scripts can reference individual items in the array through integer array indexes (inside square brackets) or via the NodeList object's item( ) method.

Some node types have their own collections (e.g., NamedNodeMap for a collection of attribute nodes and the HTMLCollection for a collection of HTML element nodes). These other collection objects have extra properties and methods that are meaningful only to the types of nodes inside the collections. For instance, because text nodes (one of the simplest type of Node object) do not have a property that can contain an identifier, the NodeList object does not include a method to reference an item by its ID. But an HTMLCollection object (consisting entirely of the more complex HTMLElement types of nodes) includes another method (namedItem( )) that lets scripts reference an item by its ID as well as integer index. The distinctions among collection object types are readily apparent when you compare the properties and methods of the collection objects you actually script (see the descriptions in this chapter of the attributes and images objects, for example). The W3C DOM terminology, on the other hand, is not a factor in scripts.


Object-Specific Properties

length

Object-Specific Methods

item( )

The noframes object reflects the noframes element, and the noscript object reflects the noscript element.


HTML Equivalent

 <noframes> <noscript> 


Object Model Reference

 [window.]document.getElementById("elementID") 


Object-Specific Properties

None.


Object-Specific Methods

None.


Object-Specific Events

None.


The Notation object (one of the node types) is an abstract representation in the W3C DOM of a portion of a DOCTYPE declaration. In particular, a Notation object contains properties for reading the public and system IDs cited by the DOCTYPE.


The object object reflects the object element. This is an updated way of embedding other media and external data into a document (through a plugin or, in IE for Windows, an ActiveX control). The depth and quality of implementation of this object (vis-à-vis the W3C specifications) is uneven across browser brands and versions. The most consistent implementation is in IE for Windows for loading ActiveX controls.


HTML Equivalent

<object>


Object Model Reference

 [window.]document.getElementById("elementID") 


Object-Specific Properties

align
alt
altHtml
archive
BaseHref
border
classid
code
codeBase
codeType
contentDocument
data
dataFld
dataSrc
declare
form
height
hspace
name
object
standby
type
useMap
vspace
width

Object-Specific Methods

None.


Object-Specific Events

Handler

IE

Mozilla

Safari

Opera

DOM

abort

·

·

error

·

·

·

load

·

·



Defines how the element is aligned relative to surrounding text content. Most values set the vertical relationship between the element and surrounding text. For example, to align the bottom of the element with the baseline of the surrounding text, the align property value would be baseline. An element can be "floated" along the left or right margin to let surrounding text wrap around the element.


Example

 document.getElementById("myObject").align = "absmiddle"; 


Value

Any of the following alignment constant values (as a string): absbottom | absmiddle | baseline | bottom | right | left | none | texttop | top.


Default

bottom


Indicates the text to be displayed (or spoken) where the object element appears on the page when a browser doesn't download graphics (or is waiting for the image to download). Presumably, Microsoft implemented this nonstandard property for occasions when the object element is used for the display of images, rather than the more common img element.


Example

 document.getElementById("logoDisplay").alt = "MegaCorp Logo"; 


Value

String value.


Default

None.


Provides HTML content to be displayed if the object or applet fails to load. This can be a message, static image, or any other HTML that best fits the scenario. There are inconsistencies in Internet Explorer with regard to this property name's case. The Win32 version requires altHtml; the Mac version requires altHTML.


Example

 document.getElementById("myObject").altHtml = "<img src='/books/2/570/1/html/2/objectAlt.gif'>"; 


Value

Any quoted string of characters, including HTML tags.


Default

None.


Reflects the archive attribute of the object element, but current mainstream browsers assign no functionality to either the attribute or property.


Value

String value.


Default

None.


Returns the URL of the document containing the object element. Most commonly, the value is the same as the location.href of the current window. Note the unusual letter case.


Example

 var where = document.getElementById("myObject").BaseHref; 


Value

URL string.


Default

Current document's URL.


Controls the thickness of the border in pixels. For cross-browser compatibility use string values.


Example

 document.getElementById("myObject").border = "5"; 


Value

Number as string.


Default

0


Provides the URL of the object's implementation. In Internet Explorer, the URL can point to the client computer's CLSID directory (with a clsid: URL) that stores all the IDs for registered ActiveX controls, such as DirectX or Media Player. IE 4 for Macintosh names this property classID, but the name was repaired to all lowercase in IE 4.5. The W3C DOM omits this property, even though HTML 4 includes the corresponding attribute.


Example

 if (document.getElementById("soundObject").classid ==     "clsid:83A38BF0-B33A-A4FF-C619A82E891D"){     // process for the desired sound object } 


Value

String (including the clsid: protocol for local ActiveX controls).


Default

None.


Provides the name of the Java applet class file set to the code attribute of the object element (when using an object element in lieu of an applet elementif supported by your browsers).


Example

 if (document.getElementById("clock").code == "Y2Kcounter.class") {     // process for the found class file } 


Value

Case-sensitive applet class filename as a string.


Default

None.


This is the path to the directory holding the class file designated in either the code or classid attribute. The codebase attribute does not name the class file, just the path.


Example

 if (document.getElementById("clock").codeBase == "classes") {     // process for the found class file directory } 


Value

Case-sensitive pathname, usually relative to the directory storing the current HTML document.


Default

None.


Provides an advisory about the content type of the object referred to by the classid attribute. A browser might use this information to assist in preparing support for a resource requiring a multimedia player or plugin. If the codetype property is set to an empty string, the browser looks next for the type attribute setting (although it is normally associated with content linked by the data attribute URL). If both attributes have no (or empty) values set, the browser gets the content type information from the resource as it downloads.


Example

 document.getElementById("gameTime").codeType = "application/x-crossword"; 


Value

Case-insensitive MIME type. A catalog of registered MIME types is available from ftp://ftp.isi.edu/in-notes/iana/assignments/media-types/.


Default

None.


Refers to a document node created by the object element, if any.


Value

Document node reference or null.


Default

null


URL of a file containing data for the object element (as distinguished from the object itself). Relative URLs are calculated relative to the codebase attribute if one is assigned; otherwise, the URL is relative to the document's URL.


Example

 var objDataURL = document.getElementById("soundEffect").data; 


Value

A complete or relative URL as a string.


Default

None.


Used with IE data binding to associate a remote data source column name to an object element attribute determined by properties set in the object. A datasrc attribute must also be set for the element. Setting both the dataFld and dataSrc properties to empty strings breaks the binding between element and data source.


Example

 document.getElementById("myObject").dataFld = "streamURL"; 


Value

Case-sensitive identifier of the data source column.


Default

None.


Used with IE data binding to specify the ID of the page's object element that loads the data source object for remote data access (an object element other than the current one). Setting both the dataFld and dataSrc properties to empty strings breaks the binding between element and data source.


Example

 document.getElementById("myObject").dataSrc = "DBSRC3"; 


Value

Case-sensitive identifier of the data source.


Default

None.


Reflects the declare attribute. Has no effect on the content in current mainstream browsers.


Value

Boolean value: TRue | false.


Default

false


Returns a reference to the form element that contains the current element (if any). This property is appropriate only if the object is acting as a form control.


Value

Object reference or null.


Default

None.


Provide the height and width of the element, in pixels. Changes to these values are immediately reflected in reflowed content on the page.


Example

 document.getElementById("myObject").height = 250; 


Value

Integer.


Default

None.


Provide the pixel measure of horizontal and vertical margins surrounding an object element. The hspace property affects the left and right edges of the element equally; the vspace affects the top and bottom edges of the element equally. These margins are not the same as margins set by style sheets, but they have the same visual effect.


Example

 document.getElementById("myObject").hspace = 5; document.getElementById("myObject").vspace = 8; 


Value

Integer of pixel count as string.


Default

0


This is the identifier associated with the object element. If the object should be one that goes inside a form, the name property is submitted as one-half of the name/value pair when the form is submitted to the server.


Example

 document.getElementById("myObject").name = "company"; 


Value

Case-sensitive string identifier that follows the rules of identifier naming: it may contain no whitespace, cannot begin with a numeral, and should avoid punctuation except for the underscore character.


Default

None.


Provides a reference to a wrapper around an object to allow access to document object model properties of the object element when the names may be confused with internal property naming of the object. For example, if the code loaded into an object element had a property named hspace, the script reference document.getElementById("reader").object.hspace would retrieve that internal property, rather than the hspace property of the HTML element. The object property wrapper tells the JavaScript interpreter to access the property of the external object loaded into the element, and not the property of the HTML element itself.


Example

 var objCode = document.getElementById("reader").object.code; 


Value

Object reference.


Default

None.


This will eventually assume the duty of the alt attribute for displaying a message during loading. Currently has no effect on the element.


Value

String.


Default

None.


Provides an advisory about the MIME type of the external data to be loaded into the object. The browser looks to the type property value if the codeType property is null.


Example

 if (document.getElementById("myObject").type == "image/jpeg") {     ... } 


Value

Case-insensitive MIME type. A catalog of registered MIME types is available from ftp://ftp.isi.edu/in-notes/iana/assignments/media-types/.


Default

None.


Provides the URL of the map element in the same document that contains client-side image map hot areas and links. The value includes the hash mark assigned with the map name in the usemap attribute of the object element.


Example

 document.getElementById("logoViewer").useMap = "#altMap"; 


Value

A string starting with a hash mark and the name of the map element.


Default

None.


See hspace.


See height.


The ol object reflects the ol element.


HTML Equivalent

<ol>


Object Model Reference

 [window.]document.getElementById("elementID") 


Object-Specific Properties

compact
start
type

Object-Specific Methods

None.


Object-Specific Events

None.


When set to TRue, the compact property should instruct the browser to render items in the list in a more compact format. This property has no effect in mainstream browsers.


Example

 document.getElementById("myOL").compact = true; 


Value

Boolean value: true | false.


Default

false


Indicates the starting number for the sequence of items in the ol element. This is convenient when a sequence of items must be disturbed by running body text. While the value is a number, the corresponding Arabic numeral, Roman numeral, or alphabet letter renders the value. When no value is set as an attribute, different browsers assign different default values (see below)


Example

 document.getElementById("sublist2").start = 6; 


Value

Integer.


Default

1 (IE, Opera); -1 (Mozilla); 0 (Safari).


Indicates the manner in which the leading numbers or letters of items in the list are displayed.


Example

 document.getElementById("instruxList").type = "a"; 


Value

Possible values are: A | a | I | i | 1. Sequencing is performed automatically as shown in the following table.

Type

Example

A

A, B, C, ...

a

a, b, c, ...

I

I, II, III, ...

i

i, ii, iii, ...

1

1, 2, 3, ...



Default

None specified, although behavior is that of 1.


The optgroup object reflects the optgroup element, which must be nested inside a select element and surround option elements. See the optgroup element in Chapter 1 for browser support details of this element. The disabled property (described among the shared properties earlier in this chapter) is available for this object, and it influences the disabled status of nested option elements.


HTML Equivalent

<optgroup>


Object Model Reference

 [window.]document.getElementById("elementID") 


Object-Specific Properties

label


Object-Specific Methods

None.


Object-Specific Events

None.


Reflects the label attribute of the optgroup element.


Value

String.


Default

None.


The option object reflects the option element, which must be nested inside a select element. References to option objects most often use its parent select object, with the option object treated as one member of an array of options belonging to that select object. With modern browsers, you can also reference an option object directly via its ID. The disabled property (described among the shared properties earlier in this chapter) is available for IE 4 and later and W3C DOM browsers.

You can modify the set of options in a select object in browsers starting with Netscape 3 and Explorer 4 with backward-compatible code that continues to work in the newest browsers. If the modification entails replacing existing options with a different list of the same length, you can simply assign new values to text, value, and selected properties of each option in the select object's options array. But if the list has a different number of options, you are better served by removing all existing option objects and inserting new ones. A constructor function for a new Option object lets you create objects one at a time, and then assign them to positions within the options array. Syntax for the constructor is as follows:

 var newOpt = new Option("text", "value", isDefaultSelectedFlag, isSelectedFlag); 

The following function demonstrates the typical steps involved in rewriting a select object's list of options:

 function setSelect(selectElemObj) {     // remove existing options     selectElemObj.options.length = 0;     // create and assign options, one by one     selectElemObj.options[0] = new Option("Hercule Poirot", "poirot", false, false);     selectElemObj.options[1] = new Option("Miss Marple", "marple", false, false);     ... } 

In a production environment, the values for the constructor parameters would most likely be delivered to the page as an array of objects, allowing the stuffing of new options to be carried out inside a for loop. For additional approaches to this task, see the options.add( ) method (for IE, Mozilla, and Opera) and the select.add( ) method (for IE 5 or later and W3C DOM browsers).


HTML Equivalent

<option>


Object Model Reference

 [window.]document.formName.selectName.options[i] [window.]document.forms[i].elements[i].options[i] [window.]document.getElementById("elementID") 


Object-Specific Properties

defaultSelected
form
index
label
selected
text
value

Object-Specific Methods

None.


Object-Specific Events

None.


Determines whether an element has the selected attribute set in the tag. You can compare the current selected property against defaultSelected to see whether the state of the select control has changed since the document loaded. Changing this property does not affect the current selected status.


Example

 var listItem = document.forms[0].selector.options[2]; if (listItem.selected != listItem.defaultSelected) {     // process for changed state } 


Value

Boolean value: TRue | false.


Default

Determined by HTML tag attribute.


Returns a reference to the form object that contains the select element and its options.


Example

 var theForm = document.getElementById("myOption3").form; 


Value

form object reference.


Default

None.


Returns the zero-based index integer value of the current option object within the collection of options of the select element. The select object's selectedIndex property returns the index value of the option that is currently selected.


Example

 var whichItem = document.getElementById("myOption3").index; 


Value

Integer.


Default

None.


Reflects the label attribute of the option element. This property is intended for use with hierarchical menus, but it is not operational in browsers except for IE 5/Mac, where it returns the same value as the text property.


Value

String.


Default

None.


Determines whether the list option has been selected by the user, meaning that its value is submitted with the form. Scripts can modify the value to select an item algorithmically. To find out which option is selected, it is more efficient to use the select object's selectedIndex property, rather than looping through all options in search of those whose selected properties are true. The exception to this is when the select element is set to allow multiple selections, in which case you need to cycle through them all to find the chosen items.


Example

 document.forms[0].selectList.options[3].selected = true; 


Value

Boolean value: TRue | false.


Default

false


Provides the text associated with the option element (this property pre-dates the ability to read or write the text node content of an option element). This text is located between the start and end tags; it is what appears in the select element on screen. A hidden value associated with the list item can be stored, retrieved, and changed via the value property.


Example

 var list = document.forms[0].selectList; var listItemText = list.options[list.selectedIndex].text; 


Value

String.


Default

None.


Provides the value associated with the option element. If the option element has a value attribute or value property set, this is the value returned for the value property; otherwise, the property returns an empty string.


Example

 var itemValue = document.forms[0].selectList.options[2]value; 


Value

String.


Default

None.


An array of option elements nested within a select object. The W3C DOM Level 2 classifies this object as an HTMLOptionsCollection.


Object Model Reference

 [window.]document.formName.selectName.options [window.]document.forms[i].elements[i].options [window.]document.getElementById("selectElementID").options 


Object-Specific Properties

length
selectedIndex

Object-Specific Methods

add( )
item( )
namedItem( )
remove( )
tags( )
urns( )

Returns the number of elements in the collection. You can assign a value of zero to this property to empty the options from the select element.


Example

 var howMany = document.forms[0].mySelect.options.length; 


Value

Integer.


Returns a zero-based integer indicating which option within the collection is currently selected. This is a nonstandard alernate to the selectedIndex property of the containing select element object.


Example

 var whichOne = document.forms[0].mySelect.options.selectedIndex; 


Value

Zero-based integer.


add( elementRef[, index])

Adds an already-created element (from the createElement( ) method) to the current collection. The element must be of the option type. By default, the new element is added as the last item of the collection unless you specify an index value as a second parameter (in which case all existing items from that index position get pushed down by one). The following example sequence appends a new item to a select object:

 var newElem = document.createElement("option"); newElem.text = "Freddie"; newElem.value = "Freddie Mercury"; document.forms[1].rockers.options.add(newElem); 

Notice that a generic object is created first. Then its properties are stuffed with values, and the new element is added to the select element.

For an example of a cross-browser and backward-compatible approach to this task, see the option object discussion. Also see the select.add( ) method for a W3C DOM approach that works with all W3C DOM browsers.


Returned Value

None.


Parameters


elementRef

A fully formed element object reference, usually generated by the createElement( ) method.


index

An optional integer indicating where in the collection the new element should be placed.


item( index[, subindex])


item( index)

Returns a single object or collection of objects corresponding to the element matching the index value (or, optionally, the index and subindex values).


Returned Value

One object or collection (array) of objects. If there are no matches to the parameters, the returned value is null.


Parameters


index

When the parameter is a zero-based integer, the returned value is a single element corresponding to the specified item in source code order (nested within the current element); when the parameter is a string (IE only), the returned value is a collection of elements with id properties that match that string.


subindex

In IE only, if you specify a string value for the first parameter, you can use the second parameter to specify a zero-based index that retrieves the specified element from the collection with id properties that match the first parameter's string value.


namedItem(" ID")

Returns a single option object corresponding to the element matching the parameter string value.


Returned Value

One option object. If there are no matches to the parameters, the returned value is null.


Parameters


ID

The string that contains the same value as the desired element's id attribute.


remove( index)

Deletes an element from the current collection. Simply specify the zero-based index value of the option element you wish to remove from the collection belonging to a select element. The following example deletes the first item from a select object:

 document.forms[1].rockers.options.remove(0); 

The process for removing an option element is entirely different in other browsers. To delete an item, assign null to the item in the collection. For example, the Mozilla version of the preceding IE example is as follows:

 document.forms[1].rockers.options[0] = null; 

Regardless of the browser-specific process of removing an option from the select object, the length of the options array collapses to fill the space.


Returned Value

None.


Parameters


index

A zero-based integer indicating which item in the collection should be deleted.


tags(" tagName")

Returns a collection of objects (among all objects nested within the current collection) with tags that match the tagName parameter. Implemented in all IE collections (see the all.tags( ) method), but redundant for collections of the same element type.


urns( URN)

See the all.urns( ) method.


The output object reflects the Web Forms 2.0 output element. See the output element in Chapter 1 for implementation details and usage. Because the output object is another type of Web Forms 2.0 form control, it shares its properties and methods with the input object. Both methods are superfluous for this object because its data is never validated nor submitted with the form. See the input object for details on the properties and methods listed below.


HTML Equivalent

<output>


Object Model Reference

 [window.]document.getElementById("elementID") 


Object-Specific Properties

defaultValue
form
forms
name
value
validationMessage
validity
willValidate

Object-Specific Methods

checkValidity( )
setCustomValidity( )

The p object reflects the p element.


HTML Equivalent

<p>


Object Model Reference

 [window.]document.getElementById("elementID") 


Object-Specific Properties

align

Object-Specific Methods

None.


Object-Specific Events

None.


Determines how the paragraph text is justified within the p element's box.


Example

 document.getElementById("myP").align = "center"; 


Value

Any of the three horizontal alignment string constants: center | left | right.


Default

left


The page object is a special type of style rule created via an @page CSS rule. In the W3C DOM, this object (known as the CSSPageRule object) inherits properties of the CSSRule object. But as of IE 6 for Windows, the page object does not adhere to this inheritance structure. This object lays the foundation for a more fully implemented notion of page boxes expected in future browser versions.


HTML Equivalent

 <style type="text/css"> @page {specifications} </style. 


Object Model Reference

 [window.]document.styleSheets[i].pages[j] 


Object-Specific Properties

pseudoClass
selectorText
style

Object-Specific Methods

None.


Object-Specific Events

None.


Returns the name of the pseudo-class associated with the @page rule (if any).


Example

 var pClass = document.styleSheets[2].pages[0].pseudoClass; 


Value

String pseudo-class names (including leading colon): :first | :left | :right.


Default

None.


Provides the selector of the @page rule (if any).


Example

 document.styleSheets[2].pages[0].selectorText = ":right"; 


Value

String.


Default

None.


Returns the style object (of type CSSStyleDeclaration in the W3C DOM) reflecting the style attributes and properties of the @page rule.


Value

style object reference.


Default

None.


Provides an array of page objects (@page rules) nested within a styleSheet object.


Object Model Reference

 [window.]document.styleSheets[i].pages 


Object-Specific Properties

length


Object-Specific Methods

item( )


Object-Specific Events

None.


Returns the number of objects in the collection.


Example

 var howMany = document.styleSheets[0].pages.length; 


Value

Integer.


item( index)

Returns a single object corresponding to the element matching the index value.


Returned Value

Reference to a page object. If there are no matches to the parameters, the returned value is null.


Parameters


index

A zero-based integer corresponding to the specified item in source code order.


The param object reflects the param element, which passes variable values to ActiveX objects (IE/Windows only), Java applets, and some plugins. Such programs are written to read parameter name/value pairs during initialization so the values are ready to go when the program starts (e.g., the URL of a sound file). IE for Windows commonly assigns a full suite of parameters to some ActiveX controls, even though only a handful might be explicitly defined in the source code. Although properties are read/write, assigning new values after the page has loaded does not convey the new values to the external program.


HTML Equivalent

<param>


Object Model Reference

 [window.]document.getElementById("elementID") 


Object-Specific Properties

name
type
value
valueType

Object-Specific Methods

None.


Object-Specific Events

None.


This is the name of the external program's parameter to which a value in the param element applies.


Example

 var pName = document.getElementById("audioParam2").name; 


Value

String.


Default

None.


Provides the MIME type for a param element with a valuetype attribute set to "ref".


Example

 if (document.getElementById("myParam").valueType == "ref") {     var pType = document.getElementById("myParam").type; } 


Value

Case-insensitive MIME type as string. A catalog of registered MIME types is available from ftp://ftp.isi.edu/in-notes/iana/assignments/media-types/.


Default

None.


Indicates the string value assigned to a named parameter for the external program.


Example

 var pVal = document.getElementById("volumeParam").value; 


Value

String.


Default

None.


Indicates the string classification of the parameter set by the element.


Example

 var pValType = document.getElementById("volumeParam").valueType; 


Value

String constant: data | object | ref.


Default

data


See input.


See directories.


The plaintext object reflects the plaintext element. Note that the Win32 version of Internet Explorer 4 incorrectly evaluates the innerHTML, innerText, outerHTML, and outerText property values to include all document content following the start tag for the element. This element is deprecated in favor of the pre element.


HTML Equivalent

<plaintext>


Object Model Reference

 [window.]document.getElementById("elementID") 


Object-Specific Properties

None.


Object-Specific Methods

None.


Object-Specific Events

None.


A plugin object represents a single plugin that is registered with the browser at launch time. Access to a single plugin is normally via the navigator.plugins array. It is also common to use the navigator.mimeTypes array and associated properties to uncover whether the browser has the desired plugin installed before loading external content. Most of the properties provide scripted access to information normally found in the About Plug-ins window available from Navigator's Help menu and IE/Macintosh File Helper preferences. IE for Windows uses a different technique (involving the object element loading ActiveX controls) to determine support for playing external media.


Object Model Reference

 navigator.plugins[i] 


Object-Specific Properties

description
filename
length
name

Object-Specific Methods

None.


Provides a brief plain-language description of the plugin supplied by the plugin manufacturer.


Example

 var descr = navigator.plugins[2].description; 


Value

String.


Default

None.


Returns the filename of the plugin binary. Some early browser versions returned the complete pathname, but modern browsers return only the filename.


Example

 var file = navigator.plugins[2].filename; 


Value

String.


Default

None.


Returns the number of MIME types supported by the plugin. Don't confuse this property with the length property of the entire navigator.plugins array, which measures how many plugin objects are known to the browser.


Example

 var howManyMIMEs = navigator.plugins[2].length; 


Value

Integer.


Default

None.


Returns the name of the plugin assigned to it by its manufacturer. You cannot, however, be guaranteed that a plugin designed for multiple operating systems has the same name across all versions.


Example

 var pName = navigator.plugins[2].name; 


Value

Integer.


Default

None.


All mainstream browsers have a plugins array, but they are quite different collections of objects. For Netscape Navigator, Mozilla, Safar, and Opera, the plugins array is a property of the navigator object. Each item in the navigator.plugins array represents a plugin that is installed in the browser (actually just registered with the browser when the browser last loaded). See the plugin object.

On the Windows side, Internet Explorer's plugins collection belongs to the document object and essentially mirrors the embeds collection: a collection of all embed elements in the document. An embed element may well, indeed, launch a plugin, but not necessarily. Nor does Internet Explorer for Windows provide JavaScript access to the installed plugins in the same way that browsers such as Navigator and Mozilla do (IE for Macintosh provides no such access).


Object Model Reference


IE

 document.plugins 


NN, Mozilla, Safari, Opera

 navigator.plugins 


Object-Specific Properties

length

Object-Specific Methods

item( )
namedItem( )
refresh( )

Returns the number of elements in the collection.


Example

 var IEhowMany = document.plugins.length; var NNhowMany = navigator.plugins.length; 


Value

Integer.


item( index[, subindex]) item( index)

Returns a single object or collection of objects corresponding to the item matching the index value (or, optionally, the index and subindex values).


Returned Value

One object or collection (array) of objects. If there are no matches to the parameters, the returned value is null.


Parameters


index

When the parameter is a zero-based integer, the returned value is a single element corresponding to the specified item in source code order (nested within the current element). When the parameter is a string (IE only), the returned value is a collection of elements with name properties that match that string.


subindex

In IE only, if you specify a string value for the first parameter, you can use the second parameter to specify a zero-based index that retrieves the specified element from the collection with name properties that match the first parameter's string value.


namedItem(" name")

Returns a single plugin (NN) or embed (IE) object corresponding to the element matching the parameter string value.


Returned Value

One plugin (NN) or embed (IE) object. If there are no matches to the parameters, the returned value is null.


Parameters


name

The string that contains the same value as the desired object's name attribute.


Instructs the browser to reregister plugins installed in the plugins directory. This allows a browser to summon a newly installed plugin without forcing the user to quit and relaunch the browser.


Returned Value

None.


Parameters

None.


A popup object is a featureless rectangular space that has none of the typical browser window chrome (borders, scrollbars, title bar, etc.) nor any reference path back to the main document. Scripts must create the popup object to a specific size and location, and populate the window with content by assigning an HTML string to the popup's document.body.innerHTML property. Your scripts must also help this region stand out from the document by assigning background colors and borders to either the popup's document.body.style property or the styles of elements inside the popup.

While this popup object holds what is essentially a document object, it is not related to the window object in any way, and therefore may not load external documents. It does, however, have the helpful characteristic of transcending frame and even browser window borders, giving the appearance of an operating-system level HTML content holder. Thus, you could use it for a drop-down menu or an annotation that needs to flow across frame borders or extend beyond the browser window edge.

A popup is a transient visual element. A click anywhere outside of the popup causes the popup to disappear. But you can assign the full range of mouse events to the elements in the popup's document, for effects such as rollovers and menu item clicks. The HTML content may also contain images.

To create a popup object, use the window.createPopup( ) method. Here is a simple example of the typical creation, population, and display sequence:

 var popup = window.createPopup( ); var bod = popup.document.body; bod.style.border = "3px solid #ff8800"; bod.style.padding = "2px"; bod.style.backgroundColor = "lightyellow"; bod.innerHTML =   "<p style='font-family:Arial, sans-serif; font-size:10px'>Some popup text.</p>"; popup.show(100, 100, 100, 26, document.body); 


Object Model Reference

 popupObjectRef 


Object-Specific Properties

document
isOpen

Object-Specific Methods

hide( )
show( )

Object-Specific Events

None.


Returns a reference to the document object inside the popup object. Most (but not all) regular document object properties apply to the popup's document object. It is the primary gateway to assigning HTML content to the popup. This property is read-only, but the document object's properties are read/write to allow you to assign values to its content.


Example

 popupRef.document.body.innerHTML = "<p>Howdy, pardner!</p>"; 


Value

document object reference.


Default

The current document object.


Returns a Boolean value revealing whether the popup object is visible. Even after the popup object is hidden, its content is still accessible to scripts.


Example

 if (popupRef.isOpen) {     popupRef.hide( ); } 


Value

Boolean value: TRue | false.


Default

false


Hides the popup object. Generally invoked from scripts triggered by user actions on the popup's content.


Returned Value

None.


Parameters

None.


show( left, top, width, height[, positioningElemRef])

Shows the popup object, usually after its content has been assigned. All dimensions and position are set via parameters. The position may optionally be established relative to an element in the main document. Position and positioning element parameters may come from event object properties (event.clientX, event.clientY, and event.srcElement).


Returned Value

None.


Parameters


left

Horizontal pixel coordinate relative to the left edge of the screen or, if specified by the optional parameter, an HTML element.


top

Vertical pixel coordinate relative to the top edge of the screen or, if specified by the optional parameter, an HTML element.


width

Outer pixel width of the popup space.


height

Outer pixel height of the popup space.


positioningElemRef

An optional reference to any element accessible to the script invoking the method. Establishes a coordinate context for the left and top parameters.


The pre object reflects the pre element for preformatted text.


HTML Equivalent

<pre>


Object Model Reference

 [window.]document.getElementById("elementID") 


Object-Specific Properties

width


Object-Specific Methods

None.


Object-Specific Events

None.


Provides the character column count for the monospaced content of the element.


Example

 document.getElementById("codeExample2").width = 40; 


Value

Integer.


Default

-1 (Mozilla); 0 (Safari, Opera); none (IE).


The ProcessingInstruction object (one of the node types) is an abstract representation in the W3C DOM of an element that contains instructions for an application, but whose content is not treated as part of the document's content tree. Such elements in XML documents are tagged with the format <?ProcessTarget InstructionText?>. In the W3C DOM, the two main components are exposed as the target and data string properties, respectively.


The q object reflects the q element for inline quotations. Although IE for Windows includes (probably erroneously) the cite property for all elements (and causes that property to be listed among the shared properties earlier in this chapter), this object employs the true meaning of the cite property only for IE for Macintosh and W3C DOM browsers.


HTML Equivalent

<q>


Object Model Reference

 [window.]document.getElementById("elementID") 


Object-Specific Properties

None.


Object-Specific Methods

None.


Object-Specific Events

None.


See input.


The W3C DOM Range objectsimilar in concept to the IE Textrange objectrepresents a sequence of zero or more rendered text characters in a document. When a text range consists of zero characters, it represents an insertion point between two characters (or before the first or after the last character of the document). The Range object automatically keeps track of the node and character offset references for the start and endpoints of the range, so its methods can copy existing content, delete the range's contents, or insert new contents (in node form) into the existing range while maintaining the integrity of the document tree at every step. Nodeness is important to the Range object, but most of those concerns are handled for you.

A Range object is created via the document.createTextRange( ) method or by turning a user selection into a range via window.getSelection( ).getRangeAt(0). Once a text range is created, use its methods to adjust its start and endpoint to encompass a desired segment of the text. Then choose from a set of additional methods to act on the range. See Online Section V for details and examples of using the Range object and how its syntax varies from that of the IE Textrange object.


Object Model Reference

 document.createRange( ) 


Object-Specific Properties

collapsed
commonAncestorContainer
endContainer
endOffset
startContainer
startOffset

Object-Specific Methods

cloneContents( )
cloneRange( )
collapse( )
compareBoundaryPoints( )
compareNode( )
comparePoint( )
createContextualFragment( )
deleteContents( )
detach( )
exTRactContents( )
insertNode( )
intersectsNode( )
isPointInRange( )
selectNode( )
selectNodeContents( )
setEnd( )
setEndAfter( )
setEndBefore( )
setStart( )
setStartAfter( )
setStartBefore( )
surroundContents( )
toString( )

Object-Specific Events

None.


Returns Boolean TRue if the range's start and endpoints are at the same location, encompassing zero characters. A collapsed range can be located anywhere within the document.


Example

 if (rng.collapsed) {     // act on collapsed text range } 


Value

Boolean value: TRue | false.


Default

None.


Returns a reference to a document tree node that is the next outermost container that encompasses the current range's start and endpoints. If the start and endpoints are, themselves, in the same node (for example, the same text node), the commonAncestorContainer property returns a reference to that node's parent node. IE Textrange equivalent is parentElement( ).


Example

 var containingElem = rng.commonAncestorContainer; 


Value

Reference to a node object (commonly an element node type).


Default

None.


Returns a reference to a document tree node that contains the current range's endpoint.


Example

 var containingElemRight = rng.endContainer; 


Value

Reference to a node object.


Default

None.


Returns an integer count of characters or nodes for the endpoint's location within the node reported by the endContainer property. If the endContainer is a text node, the endOffset property counts the number of characters to the right of the first character of that text node. If the endContainer is an element node, the endOffset property counts the number of nodes between the start of the containing node's content and the endpoint.

As an example, consider the following document segment that shows a text range in boldface characters, with the start and endpoints signified by pipe characters:

 <p>One paragraph with |a <span>nested</span>| element inside.</p> 

Note that the start point is within a text node, while the endpoint sits just outside the span element end tag. The Range object's properties report values as shown in the following table.

Property

Value

Description

commonAncestorContainer

[object HTMLParagraphElement]

The p element embraces both the start and endpoints.

startContainer

[object Text]

Start point is within a text node.

startOffset

19

Start point is at the 20th (zero-based index of 19) character from the start of its container, the text node.

endContainer

[object HTMLParagraphElement]

Endpoint is designated as the end of the span element, which makes the next outer p element the endpoint's container.

endOffset

2

Endpoint is at the 3rd (zero-based index of 2) node in the context of its endContainer p element (first node is a text node; second node is the span element; endpoint is at the start of the third node of the p element).



Example

 var rngEndOff = rng.endOffset; 


Value

Integer.


Default

None.


Returns a reference to a document tree node that contains the current range's start point.


Example

 var containingElemLeft = rng.startContainer; 


Value

Reference to a node object.


Default

None.


Returns an integer count of characters or nodes for the start point's location within the node reported by the startContainer property. If the startContainer is a text node, the startOffset property counts the number of characters to the right of the first character of that text node. If the startContainer is an element node, the startOffset property counts the number of nodes between the start of the containing node's content and the start point. See endOffset for more details.


Example

 var rngStartOff = rng.startOffset; 


Value

Integer.


Default

None.


Returns a DocumentFragment node containing a copy of the contents from the current range. Any dangling nodes are resolved as part of the cloning process.


Returned Value

Reference to a node of a document fragment type.


Parameters

None.


Returns a Range object that is a carbon copy of the current range, including references to associated containers. This method lets you preserve a copy of a Range object's specifications while creating a new Range object. Similar to the IE Textrange object's duplicate( ) method.


Returned Value

Reference to a Range object.


Parameters

None.


collapse( toStartFlag)

Shrinks the current range to an insertion point (start and endpoints are in the same node at the same offset). The Boolean parameter controls whether the range collapses to the start point (TRue) or endpoint (false) of the current range. A script working its way through a document (e.g., using the String.indexOf( ) method to search for the next instance of a string) usually collapses to the endpoint before shifting the endpoint to the end of the body to perform the next String.indexOf( ) search.


Returned Value

None.


Parameters


toStartFlag

Boolean value that controls whether collapse occurs at the start point (true) or endpoint (false) of the current range.


compareBoundaryPoints( compareType, sourceRangeRef)

Returns an integer code indicating the relative positioning of one boundary point of the current range's against a boundary point of a different text range. In the simplest case, the two endpoints (one from each range) share the same ancestor container. In such a case, the first parameter determines which endpoints from the two ranges get compared. Use the constants supplied with every Range object, as shown in the following table.

Comparison type

Description

rng.START_TO_START

Comparing the start position of the current range against the start position of the source range

rng.START_TO_END

Comparing the start position of the current range against the endposition of the source range

rng.END_TO_END

Comparing the endposition of the current range against the endposition of the source range

rng.END_TO_START

Comparing the endpoisition of the current range against the start position of the source range


If the first boundary in the comparison occurs earlier in the document than the second boundary, the returned value is -1; if the first boundary comes after the second boundary, the returned value is 1; if the two boundaries are in the identical position, the returned value is 0. Similar to the IE TexTRange object's compareEndPoints( ) method.

But the situation can be more complex if the boundary points being compared have different ancestor container nodes. The offset values with respect to container nodes influence the comparison results. Due to the variety of results that can occur with numerous relationships between the compared endpoints, your scripts will need to perform an intricate analysis of boundaries to assure comparisons report the desired sequence. On the other hand, simply looking for unanimity of boundary points is a much simpler prospect. You may prefer to limit your comparisons to looking only for return values of zero (or any other value) for a more binary determination of boundary comparisons.


Returned Value

Integer values -1, 0, or 1.


Parameters


compareType

Integer values from 0 to 3 corresponding to comparison types. Integer values are not aligned with the W3C DOM standard in Mozilla before version 1.4, but the plain-language constants (such as rng.START_TO_START, shown in the table above) produce the correct comparisons.


sourceRangeRef

Reference to a second, previously defined Range object, perhaps preserved through the cloneRange( ) method.


compareNode( nodeReference)

A Mozilla-only method that returns an integer code indicating the relative position of some other node with respect to the current range. Four plain-language constants are members of every Mozilla Range object, and can be used for comparisons of values returned by the compareNode( ) method. Note that the returned values are from the point of view of the node passed as a parameter, rather than from that of the current range.

Returned values and constants are as follows.

Constant

Value

Description

rng.NODE_BEFORE

0

Entire node comes before the range.

rng.NODE_AFTER

1

Entire node comes after the range.

rng.NODE_BEFORE_AND_AFTER

2

Node starts before the current range and ends after it.

rng.NODE_INSIDE

3

Node is contained in its entirety within the scope of the range.


By way of example:

 if (rng.compareNode(document.getElementById("myElem")) == rng.NODE_INSIDE) {     // process for myElem node being contained by the range } 


Returned Value

Integer values 0, 1, 2, or 3.


Parameters


nodeReference

Reference to any node in the document tree.


compareNode( nodeReference, offset)

A Mozilla-only method that returns an integer code indicating the relative position of some other node and offset within that node with respect to the current range. Note that the returned values are from the point of view of the node (more specifically, the point signified by the offset within the node) passed as parameters, rather than from that of the current range.

Returned values are as follows.

Value

Description

-1

Point comes before the start of the range.

0

Point is located within the range.

1

Point comes after the end of the range.


By way of example:

 if (rng.comparePoint(document.getElementById("myElem"), 2) == 0) {     // process for offset of 2 within myElem node being contained by the range } 


Returned Value

Integer values -1, 0, 1.


Parameters


nodeReference

Reference to any node in the document tree.


offset

Integer offset, counting either nested nodes within an element or characters within a text node.


createContextualFragment( contentString)

The createContextualFragment( ) method was initially designed as an alternative to the innerHTML convenience property (because the W3C DOM provides little in the way of support for content strings consisting of tags). This method accepts any stringincluding tagged contentas a parameter, and returns a DocumentFragment type of node, ready for appending or inserting into the document tree. Subsequent adoption of the innerHTML property by the Mozilla browser makes this method redundant, except that it is more consistent with the overall nodeness of the W3C DOM.


Returned Value

Reference to a document fragment type of node outside of the document tree. This node can then be applied to the document tree.


Parameters


contentString

Document content in string form, including tags and attributes.


Removes the contents of the current text range from the document tree. If the range is an element node (e.g., with boundaries established via the selectNode( ) method), invoking deleteContents( ) on the range removes the node from the document tree and collapses the range. The Range object remains in memory, but without any content. If you want to capture the content prior to its deletion, do so with other Range object methods (such as cloneRange( ) and, when it works correctly, cloneContents( )).


Returned Value

None.


Parameters

None.


Destroys the current Range object to the extent that invoking most methods on the object or accessing its properties throw a RangeException of type INVALID_STATE_ERR.


Returned Value

None.


Parameters

None.


Returns a DocumentFragment node containing the contents of the current range, after removing the contents from the document tree. If you experience problems with this method, try setting the range boundaries first set via the selectNodeContents( ) method.


Returned Value

Reference to a node of a document fragment type.


Parameters

None.


insertNode( nodeReference)

Inserts a node at the start of the current text range. Most useful when the range is already collapsed as a text insertion pointer. The node being inserted can be created fresh (via document.createElement( )) or fetched from elsewhere in the document tree, in which case it is removed from its old position and inserted into the current range. If you insert a text node adjacent to a spot that also happens to be an existing text node, you can wind up with two adjacent text nodes. Invoke the normalize( ) method on the parent to consolidate the text nodes.


Returned Value

Nothing


Parameters


nodeReference

Reference to any text, element, or document fragment node to be inserted into the range.


intersectsNode( nodeReference)

Returns Boolean true if any part of the current range overlaps with the text or element node that is passed as a parameter. If your script detects an intersection, it can use the compareNode( ) method to obtain more detail about the intersection.


Returned Value

Boolean value: TRue | false.


Parameters


nodeReference

Reference to any text or element in the document tree.


isPointInRange( nodeReference, offset)

Returns Boolean true if the location denoted by the parameter values (a node in the document tree and an offset location within that node) is within the current range.


Returned Value

Boolean value: true | false.


Parameters


nodeReference

Reference to any text or element in the document tree.


offset

Integer offset, counting either nested nodes within an element or characters within a text node.


selectNode( nodeReference) selectNodeContents( nodeReference)

Sets the range's boundary points to encompass a node or just the node's contents. Despite the methods' names, no body text in the rendered document is highlighted.

Your choice of method impacts the way the range's startContainer and endContainer properties are filled. In the following sequence, you see what happens to the range and its properties when an element node and a text node are parameters to these methods. The initial HTML segment is:

 <p>One paragraph with a <span >nested</span> element inside.</p> 

Selecting the span element (with the rng.selectNode(document.getElementById("myspan")) method) sets the range to:

 <p>One paragraph with a |<span >nested</span>| element inside.</p> 

The Range object's properties report values as follows.

Property

Value

Description

startContainer

[object HTMLParagraphElement]

Start point is right before the span element.

startOffset

1

Start point is at the 2nd (zero-based index of 1) node inside the p element.

endContainer

[object HTMLParagraphElement]

Endpoint is immediately after the span element.

endOffset

2

Endpoint is at the 3rd (zero-based index of 2) node in the context of its endContainer p element.


Using the rng.selectNodeContents(document.getElementById("myspan")) method to select the span element's contents sets the range to:

 <p>One paragraph with a <span >|nested|</span> element inside.</p> 

The Range object's properties report values as follows.

Property

Value

Description

startContainer

[object HTMLSpanElement]

Start point is just inside the span element.

startOffset

0

Start point is at the 1st (zero-based index of 0) node inside the span element.

endContainer

[object HTMLSpanElement]

Endpoint is immediately after the span element's content.

endOffset

1

Endpoint is at a position where the 2nd (zero-based index of 1) node, if present, would be in the context of its endContainer span element.


Using the rng.selectNode(document.getElementById("myspan").firstChild) method to select the text node inside the span element sets the range to:

 <p>One paragraph with a <span >|nested|</span> element inside.</p> 

Even though the node passed as a parameter is different (and a different node type), the new range selection looks the same as the previous one. In fact, due to the way the node tree is structured, the Range object's properties report identical values as follows.

Property

Value

Description

startContainer

[object HTMLSpanElement]

Start point is just inside the span element.

startOffset

0

Start point is at the 1st (zero-based index of 0) node inside the span element.

endContainer

[object HTMLSpanElement]

Endpoint is immediately after the span element's content.

endOffset

1

Endpoint is at a position where the 2nd (zero-based index of 1) node, if present, would be in the context of its endContainer span element.


Using the rng.selectNodeContents(document.getElementById("myspan")) method to select the contents of the text node inside the span element sets the range to:

 <p>One paragraph with a <span >||nested</span> element inside.</p> 

In other words, the range collapses to an insertion point at the start of the text node (this may be a bug), and the text node becomes the container, as shown in the following property enumeration.

Property

Value

Description

startContainer

[object Text]

Start point is at the beginning of the text node.

startOffset

0

Start point is at the 1st (zero-based index of 0) position of the text node.

endContainer

[object Text]

Endpoint is collapsed.

endOffset

0

Endpoint is collapsed.


Element nodes tend to be the most practical parameter values to pass to either method.


Returned Value

None.


Parameters


nodeReference

Reference to any text or element in the document tree.


setEnd( nodeReference, offset) setStart( nodeReference, offset)

Establish the document tree locations for the individual boundary points of an existing Range object. Similar to the IE Textrange object's setEndPoint( ) method. The mapping of a location relies upon a node reference and an offset value relative to that node's starting point and type. Offset values count child nodes when the nodeReference is an element node; they count characters when the nodeReference is a text node. To set a boundary at a node edge, the associated methods (setEndAfter( ) and three others) are more convenient.


Returned Value

None.


Parameters


nodeReference

Reference to any element or text node in the document tree.


offset

Integer offset, counting either nested nodes within an element or characters within a text node.


setEndAfter( nodeReference) setEndBefore( nodeReference) setStartAfter( nodeReference) setStartBefore( nodeReference)

Establish the document tree locations for the individual boundary points of an existing Range object with respect to a node's edges. These methods assume that you are interested in setting a range's boundaries to places immediately before or after an existing node, and not concerned with other kinds of offsets. Range boundaries do not have to be symmetrical, allowing you to specify the start boundary relative to one node and the end boundary relative to a completely different node later in the document.


Returned Value

None.


Parameters


nodeReference

Reference to any element or text node in the document tree.


surroundContents( parentNodeReference)

Encapsulates the current range with a new container, usually a new element node created via the document.createElement( ) method. Endpoints of the current range should have the same parent container prior to applying this method.


Returned Value

None.


Parameters


parentNodeReference

Reference to a node that becomes the new containing parent for the range.


Returns a string of the body content contained by the range. No tags or attributes accompany the returned value.


Returned Value

String.


Parameters

None.


Some operations on W3C DOM Range objects can trigger errors, or, in the vernacular of JavaScript 1.5, throw exceptions if something goes wrong. The W3C DOM defines an object that conveys a code number corresponding to a well-defined, if somewhat limited, list of exceptions specifically related to Range objects. For example, if you attempt to set range boundaries to encompass non-content-related nodes (such as an Attr node), the selectNode( ) method with such a node as a parameter throws an exception whose code number is 2. This number corresponds to the exception that signals an attempt to perform an illegal or logically impossible action on a text range.


Object Model Reference

 errorObjectReference 


Object-Specific Properties

code


Object-Specific Methods

None.


Object-Specific Events

None.


Provides the integer corresponding to one of the defined Range object error types, as shown in the following table.

Code

Constant

Most Likely Cause

1

BAD_BOUNDARYPOINTS_ERR

The surroundContents( ) method was applied to a range with a nonapplicable endpoint

2

INVALID_NODE_TYPE_ERR

The method tried to work in a nonapplicable type of node



Value

Integer


Default

Determined by error.


Any HTML element that is set up in a Web Forms 2.0 environment is an instance of the RepetitionElement, sometimes as a repeated block, other times as a template (depending on attribute settings). This object has a number of properties and methods (listed below) that become members of any HTML element in a supporting browser (such as Opera 9). See the descriptions of these properties and methods among the shared items at the beginning of this chapter.


Object-Specific Properties

repeatMax
repeatMin
repeatStart
repetitionBlocks
repetitionIndex
repetitionTemplate
repetitionType

Object-Specific Methods

addRepetitionBlock( )
addRepetitionBlockByIndex( )
moveRepetitionBlock( )
removeRepetitionBlock( )

Object-Specific Events

None.


See input.


Provides a collection of all TR element objects contained in a single table, tbody, tfoot, or thead element object. The rows collection of a table element includes all rows of the table, regardless of row groups. Collection members are sorted in source code order. Internet Explorer lets you use array notation or parentheses to access a single row in the collection (e.g., document.getElementById("myTable").rows[0], document.all.myTable.rows (0)).


Object Model Reference

 document.getElementById("tableOrSectionID").rows 


Object-Specific Properties

length

Object-Specific Methods

item( )
namedItem( )
tags( )
urns( )

Object-Specific Events

None.


Returns the number of elements in the collection.


Example

 var howMany = document.getElementById("myTable").rows.length; 


Value

Integer.


item( index[, subindex]) item( index)

Returns a single TR object or collection of tr objects corresponding to the element matching the index value (or, optionally in IE, the index and subindex values).


Returned Value

One tr object or collection (array) of TR objects. If there are no matches to the parameters, the returned value is null.


Parameters


index

When the parameter is a zero-based integer, the returned value is a single element corresponding to the specified item in source code order (nested within the current element); when the parameter is a string (IE only), the returned value is a collection of elements with id properties that match that string.


subindex

In IE only, if you specify a string value for the first parameter, you can use the second parameter to specify a zero-based index that retrieves the specified element from the collection with id properties that match the first parameter's string value.


namedItem(" ID")

Returns a single tr object or collection of tr objects corresponding to the element matching the parameter string value.


Returned Value

One tr object or collection (array) of tr objects. If there are no matches to the parameters, the returned value is null.


Parameters


ID

The string that contains the same value as the desired element's id attribute.


tags( tagName)

Returns a collection of objects (among all objects within the current collection) with tags that match the tagName parameter. Redundant here, because all elements have the same tr tag.


Returned Value

A collection (array) of objects. If there are no matches to the parameters, the returned value is an array of zero length.


Parameters


tagName

This involves a string of the all-uppercase version of the element tag, for example, document.getElementById("myTable").rows.tags("tr").


urns( URN)

See the all.urns( ) method.


Of these three ruby text-related elements, only ruby and rt are officially supported as objects in the IE DOM. But an rb element (even though it has no structural or rendering powers as of IE 7) is also regarded as an element object. Mozilla and Opera treat these as valid HTML element objects of unknown type. See the ruby element in Chapter 1 for details on the usage of these elements. As scriptable objects, they have no properties or methods beyond a generic HTML element object.


Object Model Reference

 document.getElementById("elementID") 


Object-Specific Properties

None.


Object-Specific Methods

None.


Object-Specific Events

None.


See CSSRule.


See CSSRules.


The runtimeStyle object (a property of all HTML element objects in IE 5 and later for Windows) acts like a super-powerful style object: setting any of its properties overrides that property's settings that may exist in explicitly coded style definitions. Thus, it overpowers global, imported, linked, and inline style definitions. This object shares nearly the same long list of properties and methods with the style object.


Object Model Reference

 [window.]document.getElementById("elementID").runtimeStyle 


Object-Specific Properties

See the style object.


Object-Specific Methods

See the style object.


Object-Specific Events

None.


See b.


See abbr.


The screen object refers to the video display on which the browser is being viewed. Many video control panel settings influence the property values, but only a handful of properties are shared among browser brands.


Object Model Reference


NN

screen


IE

[window.]screen


Object-Specific Properties

availHeight
availLeft
availTop
availWidth
bufferDepth
colorDepth
deviceXDPI
deviceYDPI
fontSmoothingEnabled
height
logicalXDPI
logicalYDPI
pixelDepth
updateInterval
width

Object-Specific Methods

None.


Object-Specific Events

None.


Provide the height and width of the content region of the user's video monitor in pixels. This measure does not include the 24-pixel task bar (Windows) or 20-pixel system menubar (Macintosh). IE/Macintosh miscalculates the height of the menu bar as 24 pixels. To use these values in creating a pseudo-maximized window, you also have to adjust the top-left position of the window.


Example

 var newWind = window.open("","","height=" + screen.availHeight + ",width=" + screen.availWidth); 


Value

Integer of available pixels in vertical and horizontal dimensions.


Default

Depends on the user's monitor size.


Provide the pixel coordinates of the left and top edges of the screen that is available for content. With the standard Windows Taskbar arrangement, both values are zero. But drag the Taskbar to the left or top of the screen, and the corresponding value increases to accommodate the bar's space. Navigator 4 for the Macintosh doesn't start its screen counting until just below the fixed menu bar, but for Mozilla and Safari in Mac OS X, the availTop property returns 22 for the menu bar height.


Example

 window.moveTo(screen.availLeft, screen.availTop); 


Value

Integer.


Default

0 (Windows); 20 (Macintosh)


Specifies the setting of the offscreen bitmap buffer. Path animation smoothness may improve on some clients if you match the bufferDepth to the colorDepth values. Setting the bufferDepth to -1 forces IE to buffer at the screen's pixel depth (as set in the control panel), and colorDepth is automatically set to that value, as well (plus if a user changes the bits per pixel, the buffer is adjusted accordingly). A setting to any of the other permitted values (1, 4, 8, 15, 16, 24, or 32) buffers at that pixel depth and sets the colorDepth to that value. The client's display must be set to the higher bits-per-pixel values to take advantage of the higher settings in scripts.


Example

 screen.bufferDepth = 4; 


Value

Any of the following allowed integers: -1 | 0 | 4 | 8 | 15 | 16 | 24 | 32.


Default

0


Returns the number of bits per pixel used to display color in the video monitor or image buffer. Although this property is read-only, its value can be influenced by settings of the bufferDepth property (IE only). You can determine the color depth of the current video screen and select colors accordingly.


Example

 if (screen.colorDepth > 8) {     document.getElementById("pretty").color = "cornflowerblue"; } else {     document.getElementById("pretty").color = "blue"; } 


Value

Integer.


Default

Current video control panel setting.


All four properties concern themselves with the dots-per-inch resolution of display screens along the horizontal (x) and vertical (y) axes. A device density property returns the actual pixel density of the current display screen, as detected by the operating system. The logical density is the "normal" pixel density that most users and page authors work with (typically 96 dots per inch horizontally and vertically). These two sets of properties let scripts examine whether the user has a higher-than-usual pixel density display, which could make fixed-size items, such as images and pixel-sized fonts, appear uncomfortably small on the screen. In such cases, scripts can determine a scaling factor between the device and logical densities, and apply that factor to the style.zoom property of critical elements (or the entire document.body, for that matter). Users of high-density display systems may already have their IE application preferences set to automatic scaling, so these calculations aren't necessary.


Example

 var normDPI = 96; if ((screen.deviceXDPI == screen.logicalXDPI) && (screen.deviceXDPI > normDPI)) {     document.body.style.zoom = normDPI / screen.logicalXDPI; } 


Value

Integer.


Default

96


Returns Boolean true if the user has enabled Smooth Edges for fonts in the Windows Display control panel. The setting may influence the font-related style sheet you link into a document.


Example

 var styleFile = "css/corpStyle.css"; if (screen.fontSmoothingEnabled) {     styleFile = "css/corpStyleFancy.css"; } document.write("<link type='text/css' rel='stylesheet' href='"  +     styleFile + "'>"); 


Value

Boolean value: true | false.


Default

false


Return the number of pixels available vertically and horizontally in the client video monitor. This is the raw dimension. For the amount of screen space not covered by system bars, see availHeight and availWidth.


Example

 if (screen.height > 480 && screen.width > 640) {     ... } 


Value

Integer of pixel counts.


Default

Depends on video monitor.


See deviceXDPI.


Returns the number of bits per pixel used to display color in the video monitor. This value is similar to the colorDepth property, but it is not influenced by a potential custom color palette, as colorDepth is.


Example

 if (screen.pixelDepth > 8) {     document.getElementById("pretty").color = "cornflowerblue"; } else {     document.getElementById("pretty").color = "blue"; } 


Value

Integer.


Default

Current video control panel setting.


Provides the time interval (in milliseconds) between screen updates. A value of zero lets the browser select an average that usually works best. The longer the interval, the more animation steps may be buffered and then ignored as the update fires to display the current state.


Example

 screen.updateInterval = 0; 


Value

Positive integer or zero.


Default

0


See height.


The script object reflects the script element. Internet Explorer 4 for Windows chokes on accessing or setting the innerHTML or innerText properties, but the equivalent text property is safe. IE 5 for the Macintosh implements the readyState property (shared among all elements in IE for Windows) for this object. IE has known problems loading external .js files vis the setAttribute( ) method on the src attribute; assigning a new URL to the src property is more reliable.


HTML Equivalent

<script>


Object Model Reference

 [window.]document.getElementById("elementID") 


Object-Specific Properties

charset
defer
event
htmlFor
src
text
type

Object-Specific Methods

None.


Object-Specific Events

Event

IE

Others

DOM

error

·

load

·



Indicates the character encoding of the script content.


Example

 if (document.getElementById("myScript").charset == "csISO5427Cyrillic") {     // process for Cyrillic charset } 


Value

Case-insensitive alias from the character set registry (ftp://ftp.isi.edu/in-notes/iana/assignments/character-sets).


Default

Determined by browser.


Specifies whether the browser should proceed with rendering regular HTML content without looking for the script to generate content as the page loads. This value needs to be set in the script element's tag at runtime. When this property is set to true by the addition of the DEFER attribute to the tag, the browser does not have to hold up rendering further HTML content to parse the content of the script element in search of document.write( ) statements. Changing this property's value after the document loads does not affect the performance of the script or browser. Although all mainstream browsers implement the property, only IE does anything with it.


Example

 if (document.getElementById("myScript").defer = = "true") {     ... } 


Value

Boolean value: true | false.


Default

false


Internet Explorer's event model allows binding of object events to script elements with the help of the event and for attributes (see Online Section VI). The event property returns the setting for the event attribute. Not functional in other browsers, even though the property is implemented in some.


Example

 if (document.getElementById("gizmoScript").event == "onresize") {     ... } 


Value

Case-sensitive event name string.


Default

None.


Returns the value (element ID) assigned to the for attribute of a script element. This attribute points to the ID of the element to which the script is bound when a specific event (set by the event attribute) fires for the element. Not functional in browsers other than IE.


Example

 if (document.getElementById("helpScript").htmlFor == "helpButton") {     ... } 


Value

String.


Default

None.


Provides the URL of the .js script file imported into the current script element. If you assign a new .js file to an existing script element in IE, the previous .js file's scripts do not disappear. But any duplications of variable or functions names are overwritten by the definitions from the new file.


Example

 if (document.getElementsByTagName("script")[1].src == "scripts/textlib.js") {     ... } 


Value

Complete or relative URL as a string.


Default

None.


Indicates the text content of the element. Assigning script statements to this object has different results in various browsers. In late versions of IE for Windows, the new value is added to the existing script, even though the property no longer reports the previous script text; in Mozilla, the assigned values are ignored; in IE 5 for Macintosh, the property is treated as read-only; Safari returns only an empty string.


Example

 var scriptText = document.getElementById("script3").text; 


Value

String.


Default

None.


Provides an advisory about the content type of the script statements. The content type should tell the browser which scripting engine to use to interpret the script statements, such as text/javascript. The type attribute may eventually replace the language attribute as the one defining the scripting language in which the element's statements are written.


Example

 var scriptMIMEtype = document.getElementById("script3").type; 


Value

String.


Default

None.


A collection of all scripts defined or imported in a document, including those defined in the head or body portion. Collection members are sorted in source code order.


Object Model Reference

 document.scripts 


Object-Specific Properties

length

Object-Specific Methods

item( )
namedItem( )
tags( )
urns( )

Object-Specific Events

None.


Returns the number of elements in the collection.


Example

 var howMany = document.scripts.length; 


Value

Integer.


item( index[, subindex])

Returns a single object or collection of objects corresponding to the element matching the index value (or, optionally, the index and subindex values).


Returned Value

One object or collection (array) of objects. If there are no matches to the parameters, the returned value is null.


Parameters


index

When the parameter is a zero-based integer, the returned value is a single element corresponding to the said numbered item in source code order (nested within the current element). When the parameter is a string, the returned value is a collection of elements with id properties that match that string.


subindex

If you specify a string value for the first parameter, you may use the second parameter to specify a zero-based integer to retrieve a specific element from the collection with id properties that match the first parameter's string value.


namedItem(" ID")

Returns a single script object or collection of script objects corresponding to the element matching the parameter string value.


Returned Value

One script object or collection (array) of script objects. If there are no matches to the parameters, the returned value is null.


Parameters


ID

The string that contains the same value as the desired element's id attribute.


tags( tagName)

Returns a collection of objects (among all objects within the current collection) with tags that match the tagName parameter. Redundant here, because all elements have the same script tag.


Returned Value

A collection (array) of objects. If there are no matches to the parameters, the returned value is an array of zero length.


Parameters


tagName

A string of the all-uppercase version of the element tag, as in document.scripts.tags("script").


urns( URN)

See the all.urns( ) method.


See directories.


The select object reflects the select element. This element is a form control that contains option elements. The shared disabled property is no available for pre-Mozilla Netscape Navigator.


HTML Equivalent

<select>


Object Model Reference

 [window.]document.formName.selectName [window.]document.forms[i].elements[i] [window.]document.getElementById("elementID") 


Object-Specific Properties

autofocus
data
dataFld
dataSrc
form
forms
labels
length
multiple
name
options[]
selectedIndex
selectedOptions
size
type
validationMessage
validity
value
willValidate

Object-Specific Methods

add( )
checkValidity( )
dispatchChange( )
dispatchFormChange( )
item( )
namedItem( )
remove( )
setCustomValidity( )

Object-Specific Events

Event

IE

NN

Opera 9

Others

DOM

afterupdate

·

beforeupdate

·

change

·

·

·

·

·

formchange

·

forminput

·

invalid

·



Web Forms 2.0 extension that brings focus to the element after the page loads. Should be assigned to only one form control element per page.


Example

 document.getElementById("myselect").autofocus = true; 


Value

Boolean: TRue | false.


Default

false


Web Forms 2.0 extension that allows a form to retrieve initial values for controls from an external XML file. The specification provides some details of the structure and namespaces to be used for the file. Visit http://www.whatwg.org/ for further information.


Value

URL string.


Default

Empty string.


Used with IE data binding to associate a remote data source column name with the selectedIndex property of the select object. A datasrc attribute must also be set for the element. Setting both the dataFld and dataSrc properties to empty strings breaks the binding between element and data source. Works only with text file data sources in IE 5/Mac.


Example

 document.forms[0].mySelect.dataFld = "choice"; 


Value

Case-sensitive identifier of the data source column.


Default

None.


Used with IE data binding to specify the ID of the page's object element that loads the data source object for remote data access. Setting both the dataFld and dataSrc properties to empty strings breaks the binding between element and data source. Works only with text file data sources in IE 5/Mac.


Example

 document.forms[0].mySelect.dataSrc = "DBSRC3"; 


Value

Case-sensitive identifier of the data source.


Default

None.


Returns a reference to the form element that contains the current element. When processing an event from this element, the event handler function automatically has access to the select element (as the event object's target or srcElement property). By reading the form property, the script can easily access other controls within the same form.


Example

 var theForm = evt.srcElement.form; 


Value

form element object reference.


Default

None.


Web Forms 2.0 extension that returns an array (NodeList) of references to form objects with which the current select element is associated.


Example

 var formList = document.getElementById("mySelect").forms; 


Value

Array.


Default

One-item array with a reference to any enclosing form element.


Web Forms 2.0 extension that returns an array (HTMLCollection) of references to label element objects associated with the current select element.


Example

 var allLabels = document.getElementById("mySelect").labels; 


Value

Array of label element object references.


Default

Empty array.


The number of option objects nested inside the select object. The value returned is the same as the select object options.length property, and can be safely used as a for loop maximum counter value to iterate through the nested option objects. The W3C DOM specifies that this property is read-only, but because the property has been read/write for some time in mainstream browsers, you can continue to adjust this value. By and large, the only modification made to this property, if at all, should be setting its value to zero to empty all options from the select object. Better still, if you are authoring for IE 5 and later or W3C DOM browsers, use the select.remove( ) and select.add( ) methods to modify the contingent of option elements nested inside the select element.


Example

 document.forms[0].mySelect.length = 0; 


Value

Integer.


Default

None.


Specifies whether the browser should render the select element as a list box and allow users to make multiple selections from the list of options. By default, the size property is set to the number of nested option elements, but the value may be overridden with the size property setting. To change a scrolling pick list to a popup menu, set the multiple property to false and the size property to 1. Users can select contiguous items by Shift-clicking on the first and last items of the group. To make discontiguous selections, Windows users must Ctrl-click on each item; Mac users must Command-click on each item. The multiple property has no effect when size is set to 1 to display a popup menu.


Example

 if (document.entryForm.list3.multiple) {     ... } 


Value

Boolean value: true | false.


Default

false


This is the identifier associated with the form control. The value of this property is submitted as one-half of the name/value pair when the form is submitted to the server. Names are hidden from user view, since control labels are assigned via other means, depending on the control type. Form control names may also be used by script references to the objects. Despite the modern standards' preference for the id attribute, many browsers still require that a control be assigned a name attribute to allow the control's value to be submitted.


Example

 document.orderForm.payment.name = "credcard"; 


Value

Case-sensitive string identifier that follows the rules of identifier naming: it may contain no whitespace, cannot begin with a numeral, and should avoid punctuation except for the underscore character.


Default

None.


Returns an array of all option objects contained by the current element (in the W3C DOM Level 2, this array is an HTMLOptionsCollection object). Items in this array are indexed (zero-based) in source code order. For details on using this collection in a backward-compatible way for adding and removing option elements from a select element, see the options object. Loop through this collection in select elements set for multiple selections.


Example

 var selVals = new Array( ); for (var i = 0; i < document.forms[0].mySelect.length; i++) {     if (document.forms[0].mySelect.options[i].selected) {         selVals[selVals.length] = document.forms[0].mySelect.options[i].value;     } } 


Value

Array of option objects.


Default

None.


This is the zero-based integer of the option selected by the user. If the select element is set to allow multiple selections, the selectedIndex property returns the index of the first selected item (see the selected property). You can use this property to gain access to the value or text of the selected item, as shown in the example.

In recent browsers, if no option is selected, the selectedIndex property returns 0 (the first option). Setting the value to -1 deselects all items and empties the display (except in Safari).


Example

 var list = document.forms[0].selectList; var listText = list.options[list.selectedIndex].text; 


Value

Integer.


Default

0


Controls the number of rows displayed in a scrolling pick list, reflecting the size attribute of the select element. When set to true, the multiple property overrides a size value set to fewer than the number of options. To change a scrolling pick list to a popup menu, set the multiple property to false and the size property to 1.


Example

 document.forms[0].choices.size = 6; 


Value

Integer.


Default

None.


Returns the type of form control element. A select object has two possible values, depending on whether the element is set to be a multiple-choice list. The value is returned in all lowercase letters. It may be necessary to cycle through all form elements in search of specific types to do some processing on (e.g., emptying all form controls of type "text" while leaving other controls untouched).

Note that Navigator 4 incorrectly reports a select object's type as select-multiple if the element's size attribute is set to any value larger than 1, even if the multiple attribute is not set.


Example

 if (document.forms[0].elements[3].type == "select-multiple") {     ... } 


Value

Any of the following constants (as a string): button | checkbox | file | hidden | image | password | radio | reset | select-multiple | select-one | submit | text | textarea.


Default

Depends on value of multiple.


Web Forms 2.0 extension that returns a browser-generated message if the form control fails to validate according to its specifications. This property is meant more for text-oriented form controls, where an empty string means that the entry validates properly.


Value

Empty string.


Default

Empty string.


Web Forms 2.0 extension that returns a ValidityState object. See the ValidityState object.


Value

ValidityState object.


Default

ValidityState object.


This is the current value associated with the form control that is submitted with the name/value pair for the element. All values are strings, but they may represent other kinds of data, including Boolean and numeric values. Early browsers (pre-Mozilla Netscape and pre-IE 4), scripts had to retrieve the selected option's value by using the select object's selectedIndex property as an index into the options array, then inspect each option object's selected property to find the TRue one(s).


Example

 if (document.forms[0].medium.value == "CD-ROM") {     ... } 


Value

String.


Default

None.


add( newOptionElement[, positionIndex])


add( newOptionElement, optionElementReference)

Adds a new option element to the current select element. Unfortunately, IE and W3C DOMs don't agree on the parameter values for this method. While all browsers require a reference to a newly created option element (the value returned from a document.createElement("option") method is appropriate for that), the second parameter varies with browser. In IE, the second parameter is optional and supplies a numeric index to the existing option element; the new option is inserted in front of that element. With no second parameter, the new option is appended to the existing option elements. In W3C DOM browsers, the second parameter is required. The parameter is either a reference to an existing option element (the new option is inserted before that referenced option) or null (the new option is appended to the existing options).


Returned Value

None.


Parameters


newOptionElement

Reference to an option element created by script, usually with the document.createElement( ) method.


positionIndex

Optional IE integer parameter signifying the existing nested option element in front of which the new option is to be inserted. Omitting this parameter or assigning a value of -1 causes the new option to be appended to the end of the options list.


optionElementReference

Reference to an option element in front of which the new option is to be inserted. You may also use null to append the new option to the end of the option list.


Web Forms 2.0 method that returns a Boolean value representing whether the form control element meets its validity criteriaultimately, whether the validity.valid property is TRue.


Returned Value

Boolean value: true | false.


Parameters

None.


Web Forms 2.0 methods that fire the change and formchange events on the current element. You could, for example "convert" a mouseup event to a change or formchange event by having the onmouseup event handler invoke either method.


Returned Value

None.


Parameters

None.


item( index[, subindex])


item( index)

Returns a single nested option object or collection of nested option objects corresponding to the element matching the index value (or, optionally, the index and subindex values).


Returned Value

One object or collection (array) of objects. If there are no matches to the parameters, the returned value is null.


Parameters


index

When the parameter is a zero-based integer, the returned value is a single element corresponding to the said numbered item in source code order (nested within the current element). When the parameter is a string, the returned value is a collection of elements with id properties that match that string.


subindex

If you specify a string value for the first parameter, you may use the second parameter to specify a zero-based integer to retrieve a specific element from the collection with id properties that match the first parameter's string value.


namedItem(" ID")

Returns a single nested option object or collection of nested option objects corresponding to the element matching the parameter string value.


Returned Value

One option object or collection (array) of option objects. If there are no matches to the parameters, the returned value is null.


Parameters


ID

The string that contains the same value as the desired element's id attribute.


remove( positionIndex)

Deletes an option element from the current select element at the zero-based index position signified by the parameter value. In lieu of setting the select object's length property to zero, you can remove all existing options with a simple loop construction:

 while (selectElemRef.length > 0) {     selectElemRef.remove(0); } 

At this point, you can populate the list with new options via the various approaches described in the add( ) method discussion and the options object discussion.


Returned Value

None.


Parameters


positionIndex

Zero-based integer signifying the item from the nested options collection to be deleted.


setCustomValidity([ errorString])

Web Forms 2.0 method that sets the customError Boolean value of the validity property (itself a ValidityState object). This method has no effect on button elements and throws a NOT_SUPPORTED_ERR error.


Returned Value

None.


Parameters


errorString

If null or an empty string, the parameter resets the validity object's customError property, signifying the form control is not valid. An error string is to be remembered by the browser (during the current session) so that it displays the string upon subsequent validation failures.


The selection object represents zero or more characters that have been explicitly selected in a document by the user or selected under script control. The objects are very different entities across browsers (observe compatibility ratings for properties and methods, below), and there are two incompatible approaches to providing script access to the selection.

In IE for Windows, you create a selection object via the document.selection property, which returns a selection object. To perform substantive actions on the content of the selection object, you then generate a Textrange object from the selection object (via the selection object's createRange( ) method). Use Textrange properties and methods to interact with the content. To convert a Textrange object to a visibly selected stretch of text on the page, use the Textrange object's select( ) method. This close linkage with the TexTRange object means that the IE selection object is limited to Win32 versions. The IE selection object can include selected text inside an input (of type text) and textarea element.

In IE for the Macintosh, you don't have a selection object per se. Instead, it implements the Navigator 4 document.getSelection( ) method, which returns only the string contents of the selected text. Speaking of that Navigator 4 method, Mozilla does support it, but the method is deprecated and displays a warning (less harmful than an error) in the JavaScript Console if you use the method.

In Mozilla, create a selection object with the window.getSelection( ) method. Many properties and methods of the Mozilla selection object have analogs with the W3C DOM Range object specification. In fact, it is through the Range object that scripts can highlight even discontiguous text spans on the page: create and size a Range object; then add that Range to the highlighted text via the selection object's addRange( ) method. Mozilla selections (as with the Range object) operate only on body content, and not on text inside editable text boxes.

Safari's support for the selection object is quite limited, returning little more than the selected text. Opera 8 or later tracks the IE object to the extent that you can create an IE TexTRange object from the selection; Opera 9 also implements the Mozilla selection object.

It's not uncommon among browsers that a user clicking on a button or link deselects the current text selection. Therefore, all scripted action involving selections in these browsers must be triggered by onselect or onmouseup events, or functions invoked by a timer (see the window.setTimeout( ) method description in Chapter 5).


Object Model Reference


IE (Win), Opera

document.selection


Mozilla, Safari, Opera 9

window.getSelection( )


Object-Specific Properties

anchorNode
anchorOffset
focusNode
focusOffset
isCollapsed
rangeCount
type
typeDetail

Object-Specific Methods

addRange( )
clear( )
collapse( )
collapseToEnd( )
collapseToStart( )
containsNode( )
createRange( )
createRangeCollection( )
deleteFromDocument( )
empty( )
extend( )
getrangeAt( )
removeAllRanges( )
removeRange( )
selectAllChildren( )
selectionLanguageChange( )
toString( )

Object-Specific Events

None.


Return a reference to the node where the user started (anchor) and ended (focus) the selection. Most typically, these are text node types. If the selection is set or extended via the addRange( ) method, these properties point to the node boundaries of the most recently added range.


Example

 var anchor = selectionRef.anchorNode; if (anchor.nodeType == 3 && anchor.parentNode.tagName == "td") {     // process selection start inside a table cell } 


Value

Reference to a document tree node, or null if no selection.


Default

null


Return an integer count of characters or nodes from the beginning of the anchor or focus nodes of the selection (see anchorNode and focusNode properties). If the node is a text node, the offset unit is the character; if the node is an element node, the offset unit is the node. This behavior is similar to the offset properties of a Range object. Most typically, these values count characters within text node types. If the selection is set or extended via the addRange( ) method, these properties point to the node boundary offsets of the most recently added range.


Example

 var selStartOffset = selectionRef.anchorOffset; 


Value

Integer.


Default

0


Returns Boolean TRue if the anchor and focus boundaries of a selection are identical.


Example

 if (selectionRef.isCollapsed) {     // selection is an insertion point } 


Value

Boolean value: true | false.


Default

true


Returns an integer count of Range objects (which may be discontiguous in Mozilla) within the span of the selection. A manual selection by the user always contains one Range, but the addRange( ) method can tack on multiple, discontiguous ranges to the selection. To inspect each highlighted section's properties, use the getrangeAt( ) method.


Example

 var howMany = selectionRef.rangeCount; 


Value

Integer.


Default

0


Specifies whether the current selection object has one or more characters selected or is merely an insertion point.


Example

 if (document.selection.type == "Text") {     ... } 


Value

In IE, one of three constant values (as a string): None | Text | Control. The last one is possible only when HTML editing is engaged and control selections are possible. In Safari, one of three constant values (as a string): None | Caret | Range.


Default

None


This property is supplied as a placeholder for other applications that may use the IE browser component. Such an application can provide additional selection type information as needed.


addRange( RangeReference)

Turns a Range into a highlighted selection on the page. You can add as many discontiguous ranges to the selection as your application requires. Each addition increments the selection object's rangeCount property. Ranges may also overlap in a selection.

 var selRef = window.getSelection( ); var rng = document.createRange( ); rng.selectNodeContents(document.getElementById("myP")); selRef.addRange(rng); 


Returned Value

None.


Parameters


RangeReference

Reference to a Range object with boundaries that have been established by Range object methods.


Deletes the content of the current selection in a document. For example, the event handler in the following tag deletes any selected text of the p element two seconds after the user starts making the selection:

 <p onselectstart="setTimeout('document.selection.clear( )',2000);"> 


Returned Value

None.


Parameters

None.


collapse( nodeReference, offset)

Collapses the current selection to a location specified by the two parameters. Any previously highlighted selection returns to normal display.


Returned Value

None.


Parameters


nodeReference

Reference to a text or element node in the document tree in which the collapsed selection should move.


offset

Integer count of characters or nodes within the nodeReference node where the collapsed selection should move. The count is relative to the start of the node. Units are character for text nodes, nodes for elements.


Collapses the current selection to a location at the start (collapseToStart( )) or end (collapseToEnd( )) of the selection object. Any previously highlighted selection returns to normal display. If the selection consists of multiple ranges, the start or end boundary used for these collapse methods are at the outermost edges of the combined selection. After the collapse, the selection contains only one range.


Returned Value

None.


Parameters

None.


containsNode( nodeReference, entirelyFlag)

Returns Boolean TRue if the current selection object contains a node passed as a parameter. The second parameter is supposed to let you loosen or tighten the definition of contains, but the behavior of the method seems backward to the intended purpose of the flag. You can assure accuracy if you pass null as the second parameter, which forces the method to define containment as containing the node in its entirety.


Returned Value

Boolean value: TRue | false.


Parameters


nodeReference

Reference to any addressable text or element node in the document tree.


entirelyFlag

Boolean value or null. Observed behavior is that a value of true means the selection can contain only a part of the node for the method to return true.


Creates a TexTRange object from the current selection object. After a statement like the following:

 var myRange = document.selection.createRange( ); 

scripts can act on the content of the selected text.


Returned Value

TexTRange object.


Parameters

None.


Creates a TexTRange collection object. This must be in anticipation of IE supporting multiple, discontiguous selections in the future.


Returned Value

Textrange collection object.


Parameters

None.


Removes the current selection from the document tree. The node hierarchy adjusts itself by obeying the same rules as Range.deleteContents( ).


Returned Value

None.


Parameters

None.


Deselects the current selection and sets the selection object's type property to None. There is no change to the content that had been selected.


Returned Value

None.


Parameters

None.


extend( nodeReference, offset)

Moves the end (focus) boundary of the selection to the designated document tree node and offset within that node. The start (anchor) point does not move with this method.


Returned Value

None.


Parameters


nodeReference

Reference to a text or element node in the document tree in which the selection's focus (endpoint) should move.


offset

Integer count of characters or nodes within the nodeReference node where the collapsed selection should move. The count is relative to the start of the node. Units are character for text nodes, nodes for elements.


getRangeAt( rangeIndex)

Returns a reference to the range within a selection object whose zero-based numeric index matches the passed parameter. For contiguous selections, the parameter should be zero. But for discontiguous selections, the getrangeAt( ) method lets you retrieve each range that had been added to the selection for individual manipulation as a Range object. Use the selection.rangeCount property to derive the number of Range objects contained by the selection object. Invoking the method does not disturb the sequence of ranges within the selection.


Returned Value

Range object reference.


Parameters


rangeIndex

Zero-based integer index value.


Removes all Range objects from the current selection (not from the document tree). The selection collapses, and the rangeCount property value changes to zero.


Returned Value

None.


Parameters

None.


removeRange( rangeReference)

Removes a single Range object from the current selection (not from the document tree). If you have a multiple-range selection, you can iterate through all Range objects, inspect each for some criterion, and delete the one(s) you want with the following sequence:

 var oneRange; var sel = window.getSelection( ); for (var i = 0; i < sel.rangeCount; i++) {     oneRange = sel.getRangeAt(i);     if (oneRange.someProperty == someDiscerningValue) {         sel.removeRange(oneRange);     } } 


Returned Value

None.


Parameters


rangeReference

Reference to one of the Range objects previously added to the current selection.


selectAllChildren( elementNodeReference)

Forces the selection object to encompass the element node passed as a parameter and all of its child nodes. This method is also a shortcut to using a script to select an element node. Using this method on an element node causes the anchor and focus nodes to be that element node. Should you pass a reference to a text node, the resulting selection is collapsed in front of the first character of the text node. Invoking this method on an existing selection replaces all ranges with the new range encompassing the element.


Returned Value

None.


Parameters


elementNodeReference

Reference to an element node in the document tree that becomes the selection.


selectionLanguageChange( RTLFlag)

Controls the cursor Bidi (bi-directional) level.


Returned Value

None.


Parameters


RTLFlag

Boolean value: true for right-to-left; false for left-to-right.


Returns a string containing only body content from the selection. Tags and attributes are ignored.


Returned Value

String value.


Parameters

None.


See b.


The span object reflects the span element. This element is used primarily as an arbitrary container for assigning styles to inline content elements. You might say that it is the quintessential generic inline element object. In Navigator 4, a span element that is given a position style is treated very much like a layer object for scripting purposes.


HTML Equivalent

<span>


Object Model Reference

 [window.]document.getElementById("elementID") 


Object-Specific Properties

None.


Object-Specific Methods

None.


Object-Specific Events

None.


See directories.


See b.


See abbr.


The style element object reflects the style HTML element. This object is separate from the style object that is accessed as a property of virtually every element in a document. The style element object is generated in a document via the <style> tag, which can have a unique ID value assigned to it; the style (property) object contains all the style properties and their current values as set for a particular element.


HTML Equivalent

<style>


Object Model Reference

 [window.]document.getElementById("elementID") 


Object-Specific Properties

disabled
media
sheet
styleSheet
type

Object-Specific Methods

None.


Object-Specific Events

Event

IE

Others

DOM

error

·

load

·



Specifies whether rules in the style sheet should be applied to their selected elements. During page authoring, you can create a button that toggles style sheets on and off to see how the page looks in all types of browsers.


Example

 document.getElementById("mainStyle").disabled = true; 


Value

Boolean value: true | false.


Default

false


Indicates the intended output device for the rules of the style element. The media property looks forward to the day when browsers are able to tailor content to specific kinds of devices such as pocket computers, text-to-speech digitizers, or fuzzy television sets.


Example

 document.getElementById("myStyle").media = "print"; 


Value

Any one of the following constant values as a comma-delimited string: all | print | screen.


Default

all


Returns a styleSheet object (W3C DOM type CSSStyleSheet) representing the style sheet defined by the style element. This is an alternate (and nonstandard) way to reference a styleSheet object. The document.styleSheets collection is a better approach.


Example

 var oneSheet = document.getElementById("myStyle").sheet; 


Value

Reference to a styleSheet object (W3C DOM type CSSStyleSheet).


Default

None.


Returns a styleSheet object representing the style sheet defined by the style element. This is property is present, but doesn't seem to be officially supported. The document.styleSheets collection is a better approach.


Example

 var oneSheet = document.getElementById("myStyle").styleSheet; 


Value

Reference to a styleSheet object.


Default

None.


This is the style sheet MIME type specified by the type attribute of the style element.


Example

 if (document.getElementById("myStyle").type == "text/css") {     // unlikely to be anything else } 


Value

MIME type string.


Default

text/css


In its most generic sense, a style object is the access point for scripts to read and write individual CSS properties for a given element. This style object exposes (or has the potential to expose) every style sheet property supported by the browser (the kinds of CSS properties described in Chapter 4).

In practice, however, a style object that you access through an HTML element object's style property (one of the shared properties described early in this chapter) is limited in scope: It reflects only the CSS settings explicitly defined in the element's tag via the style attribute or settings assigned to the element's style property via script (all the properties are there, but their values are empty, false, or zero). But other style sheets associated with the browser (internal style sheets) and the document (explicit style sheet rules defined in the <style> element and rules imported through either a link element or an @import rule) also affect the rendered characteristics of the element. A union of all CSS properties affecting an elementthe effective style definitionmay be read, but only through browser-dependent syntax. IE (also supported by Opera) uses the currentStyle property of an element, whereas W3C DOM browsers use the document.defaultView.getComputedStyle( ) method. Both syntaxes return an object that lets scripts inspect the value of each effective CSS property value.

While the three IE style-related objects (style, currentStyle, and runtimeStyle) return a style object with properties that expose CSS style properties, the situation is a little more complex on the W3C DOM side. On the one hand, Mozilla, Safari, and Opera implement a version of the W3C DOM CSSStyleDeclaration object that exposes all the CSS properties as scriptable properties. This is the version accessed through an element object's style property (just like IE, thus making an element object's style property work cross-browser). But when you read the effective style sheet (via document.defaultView.getComputedStyle( )), the object that comes back does not expose the CSS properties directly as scriptable properties in Mozilla before 1.4 or Safari. Instead, you must use the CSSStyleDeclaration methods (listed below) to inspect a specific attribute value by name. It's a longer way to reach a particular effective style property value, but very much in keeping with other attribute-reading syntax deployed throughout the W3C DOM. Fortunately, beginning with Mozilla 1.4 and Opera 8, the CSSStyleDeclaration object returned from getComputedStyle( ) exposes all CSS properties as scriptable properties. The property values are read-only (as they are in IE's currentStyle and runtimeStyle objects), but you can use a read-only value in your scripting for if-then decisions and as the basis for arithmetic for numerically oriented values. Once you set a CSS property value via the element object's style property, however, you can read it from the style property cross-browser, and thus avoid the browser compatibility hassle.

This section lists the available style object properties plus the W3C DOM formal methods for accessing those attributes where needed. The W3C DOM lists a large percentage of the style object properties under an object umbrella called CSS2Properties. The specification offers the CSS2Properties object as an optional convenience for browsers (as current Mozilla and Opera apparently use internally to expose computed style properties).

The scriptable properties of the style object listed below correspond to the CSS properties. For more information on a particular property, see the corresponding listing in Chapter 4.


Object Model Reference


All

[window.]document.getElementById("elementID").style


IE

[window.]document.styleSheets[i].rules[j].style

[window.]document.styleSheets[i].rules[j].currentStyle

[window.]document.styleSheets[i].rules[j].runtimeStyle


W3C DOM

[window.]document.styleSheets[i].cssRules[j].style


Object-Specific Properties

accelerator
azimuth
background
backgroundAttachment
backgroundColor
backgroundImage
backgroundPosition
backgroundPositionX
backgroundPositionY
backgroundRepeat
behavior
blockDirection
border
borderBottom
borderBottomColor
borderBottomStyle
borderBottomWidth
borderCollapse
borderColor
borderLeft
borderLeftColor
borderLeftStyle
borderLeftWidth
borderRight
borderRightColor
borderRightStyle
borderRightWidth
borderSpacing
borderStyle
borderTop
borderTopColor
borderTopStyle
borderTopWidth
borderWidth
bottom
captionSide
clear
clip
clipBottom
clipLeft
clipRight
clipTop
color
content
counterIncrement
counterReset
cssFloat
cssText
cue
cueAfter
cueBefore
cursor
direction
display
elevation
emptyCells
filter
font
fontFamily
fontSize
fontSizeAdjust
fontStretch
fontStyle
fontVariant
fontWeight
height
imeMode
layoutFlow
layoutGrid
layoutGridChar
layoutGridLine
layoutGridMode
layoutGridType
left
length
letterSpacing
lineBreak
lineHeight
listStyle
listStyleImage
listStylePosition
listStyleType
margin
marginBottom
marginLeft
marginRight
marginTop
markerOffset
marks
maxHeight
maxWidth
minHeight
minWidth
MozBorderRadius
MozBorderRadiusBottomleft
MozBorderRadiusBottomright
MozBorderRadiusTopleft
MozBorderRadiusTopright
MozOpacity
opacity
orphans
outline
outlineColor
outlineOffset
outlineStyle
outlineWidth
overflow
overflowX
overflowY
padding
paddingBottom
paddingLeft
paddingRight
paddingTop
page
pageBreakAfter
pageBreakBefore
pageBreakInside
parentRule
pause
pauseAfter
pauseBefore
pitch
pitchRange
pixelBottom
pixelHeight
pixelLeft
pixelRight
pixelTop
pixelWidth
playDuring
posBottom
posHeight
position
posLeft
posRight
posTop
posWidth
quotes
richness
right
rubyAlign
rubyOverhang
rubyPosition
scrollbar3dLightColor
scrollbarArrowColor
scrollbarBaseColor
scrollbarDarkShadowColor
scrollbarFaceColor
scrollbarHighlightColor
scrollbarShadowColor
scrollbarTrackColor
size
speak
speakHeader
speakNumeral
speakPunctuation
speechRate
stress
styleFloat
tableLayout
textAlign
textAlignLast
textAutospace
texTDecoration
texTDecorationBlink
texTDecorationLineThrough
texTDecorationNone
texTDecorationOverline
textdecorationUnderline
textIndent
textJustify
textKashidaSpace
textOverflow
textShadow
texttransform
textUnderlinePosition
top
unicodeBidi
verticalAlign
visibility
voiceFamily
volume
whiteSpace
widows
width
wordBreak
wordSpacing
wordWrap
writingMode
zIndex
zoom

Object-Specific Methods

getPropertyCSSValue( )
getPropertyPriority( )
getPropertyValue( )
item( )
removeProperty( )
setProperty( )

Object-Specific Events

None.


For IE 5 and later running under Windows 2000 or newer version of Windows, users can set a preference to highlight an accelerator key for commands (or web page accessKey letters) when the user presses the Alt key. The accelerator key property controls whether the element is treated as a highlightable accelerator key string. Available as a property of the IE currentStyle (read-only) and runtimeStyle (read/write) objects only.


Example

 document.getElementById("controlH").style.accelerator = true; 


Value

Boolean value: true | false.


Default

false


This large group of properties comes from CSS attributes intended for browsers that use speech synthesis techniques to vocalize document content. You don't have to be vision-impaired to benefit from this possibility, but Mozilla does not include this feature by default. You can read about these CSS attributes in Chapter 4.

Opera 9 implements its own version of several of these properties (opPhonemes, opVoicePitch, opVoicePitchRange, opVoiceRate, opVoiceStress, opVoiceVolume). The browser maker offers a separate voice plug-in.


Value

All values for these properties are strings.


Default

None.


Provides the element's style sheet background attribute. This is a shorthand attribute, so the scripted property consists of a string of space-delimited values for the backgroundAttachment, backgroundColor, backgroundImage, backgroundPosition, and backgroundRepeat property values. One or more values may be in the background value, and the individual values may be in any order. Available in IE as a property of the style and runtimeStyle objects only.


Example

 document.getElementById("myDiv").style.background = "url(logo.gif) repeat-y"; 


Value

String of space-delimited values corresponding to one or more individual background style properties.


Default

None.


Sets how the image is "attached" to the element. The image can either remain fixed within the viewable area of the element (the viewport) or it may scroll with the element as the document is scrolled. During scrolling, the fixed attachment looks like a stationary backdrop to rolling credits of a movie.


Example

 document.getElementById("myDiv").style.backgroundAttachment = "fixed"; 


Value

String of either allowable value: fixed | scroll.


Default

scroll


Provides the background color of the element. If you also set a backgroundImage, the image overlays the color. Transparent pixels of the image allow the color to show through.


Example

 document.getElementById("highlighted").style.backgroundColor = "yellow"; 


Value

Any valid color specification (see description at beginning of the chapter) or TRansparent.


Default

transparent


URL of the background image of the element. If you also set a backgroundColor, the image overlays the color. Transparent pixels of the image allow the color to show through.


Example

 document.getElementById("navbar").style.backgroundImage = "url(images/navVisited.jpg)"; 


Value

Any complete or relative URL to an image file in CSS URL format: url(filePath).


Default

None.


Indicates the top and left location of a background image relative to the element's content region (plus padding). Positions may be specified as length values (with numbers and units or percentages) or according to a combination of constants top, right, bottom, left, and center. The property has no effect on a background images set to repeat along both axes. Available as a property of the IE style and runtimeStyle objects only.


Example

 document.getElementById("div3").style.backgroundPosition = "20% 50%"; 


Value

A string containing one value (to be applied to both horizontal and vertical axes) or a space-delimited pair of values. Values may be explicit length values (with units, as in 30px 5px), percentages (e.g., 50% 50%) or position constants that have explicit meanings for their combinations.

Constant value pair

Percentage equivalents

Constant value pair

Percentage equivalents

top left

0% 0%

center center

50% 50%

left top

0% 0%

right

100% 50%

top

50% 0%

right center

100% 50%

top center

50% 0%

center right

100% 50%

center top

50% 0%

bottom left

0% 100%

right top

100% 0%

left bottom

0% 100%

top right

100% 0%

bottom

50% 100%

left

0% 50%

bottom center

50% 100%

left center

0% 50%

center bottom

50% 100%

center left

0% 50%

bottom right

100% 100%

center

50% 50%

right bottom

100% 100%


Percentage values are interpolated logically. For example, a value of 0% means that the image abuts the left or top edge of the element block; a value of 50% centers the image vertically or horizontally; a value of 100% places the image flush right or bottom..


Default

0% 0%


Indicate the top and left locations of the background image relative to the element's content region (plus padding). Useful if you wish to adjust the background image along only one axis while not disturbing the other.


Example

 document.getElementById("div3").style.backgroundPositionX = "20px"; document.getElementById("table2").style.backgroundPositionY = "10px;" 


Value

You should be able to specify percentage values, which are the percentage of the block-level element's box width and height (respectively) at which point the image (or repeated images) begins. You are safest with pixel values. None of the allowed constants except top and left are recognized.


Default

0


Specifies whether a background image (specified with the backgroundImage property) should repeat and, if so, along which axes. You can use repeating background images to create horizontal and vertical bands with some settings.


Example

 document.getElementById("div3").style.backgroundRepeat = "repeat-y"; 


Value

With a string setting of no-repeat, one instance of the image appears in the location within the element established by the backgroundPosition property (default is top-left corner). Normal repeats are performed along both axes, but you can have the image repeat down a single column (repeat-y) or across a single row (repeat-x). To reestablish the default, assign the value repeat.


Default

repeat


Controls whether an IE Windows external behavior is assigned to the element.


Example

 document.getElementById("div3").style.behavior = "url(#default#userData)"; 


Value

CSS-formatted URL value, with the actual URL pointing to an external .htc file, ID of an object element that loads a behavior ActiveX control into the page, or one of the built-in default behaviors (in the format url(#default#behaviorName)).


Default

None.


Returns the writing script direction of the current element. Available as a property of the IE currentStyle object only.


Example

 if (document.getElementById("myDIV").style.blockDirection = "rtl") {     // process right-to-left text } 


Value

String constant values: ltr | rtl.


Default

ltr


Provides a shorthand property for getting or setting the borderColor, borderStyle, and/or borderWidth properties of all four borders around an element in one statement. You must specify a border style (see borderStyle) for changes of this property to affect the display of the element's border (a missing style is interpreted as no style, ergo no border). Numerous other properties allow you to set the width, style, and color of individual edges or groups of edges if you don't want all four edges to be the same. Only those component settings explicitly made in the element's tag attributes are reflected in the property, but you may assign components not part of the original tag. Available in IE as a property of the style and runtimeStyle objects only.


Example

 document.getElementById("announce").style.border = "inset red 4px"; 


Value

Space-delimited string. For the borderStyle and borderWidth component values, see the respective properties in this chapter. For details on the borderColor value, see the section about CSS colors at the beginning of Chapter 4.


Default

None.


These are shorthand properties for getting or setting the borderColor, borderStyle, and/or borderWidth properties for a single edge of an element in one statement. You must specify a border style (see borderStyle) for changes of these properties to affect the display of the element's border (a missing style is interpreted as no style, ergo no border along the specified edge). If you want all four edges to be the same, see the border attribute. Only those component settings explicitly made in the element's tag attributes are reflected in the property, but you may assign components not part of the original tag. Available in IE as properties of the style and runtimeStyle objects only.


Example

 document.getElementById("announce").style.borderBottom = "inset red 4px"; document.getElementById("announce").style.borderLeft = "solid #20ff00 2px"; document.getElementById("announce").style.borderRight = "double 3px"; document.getElementById("announce").style.borderTop = "outset red 8px"; 


Value

Space-delimited string. For the borderSideStyle and borderSideWidth component values, see the respective properties in this chapter. For details on the borderSideColor value formats, see the section about colors at the beginning of Chapter 4.


Default

None.


Provide the color of a single border edge of an element. It is easy to abuse these properties by mixing colors that don't belong together. See also the borderColor attribute for setting the color for groups of edges in one statement.


Example

 document.getElementById("announce").style.borderBottomColor = "red"; document.getElementById("announce").style.borderLeftColor = "#20ff00"; document.getElementById("announce").style.borderRightColor = "rgb(100, 75, 0)"; document.getElementById("announce").style.borderTopColor = "rgb(90%, 0%, 25%)"; 


Value

For details on CSS color values, see the section about colors at the beginning of Chapter 4.


Default

None.


Provide the line style of a single border edge of an element. The edge-specific attributes let you override a style that has been applied to all four edges with the border or borderStyle properties. See also the borderStyle property for setting the style for groups of edges in one statement.


Example

 document.getElementById("announce").style.borderBottomStyle = "groove"; document.getElementById("announce").style.borderLeftStyle = "double"; document.getElementById("announce").style.borderRightStyle = "solid"; document.getElementById("announce").style.borderTopStyle = "inset"; 


Value

Style values are case-insensitive constants that are associated with specific ways of rendering border lines. The CSS style constants are: dashed, dotted, double, groove, hidden, inset, none, outset, ridge, and solid. Not all browsers recognize all the values in the CSS recommendation. See the border-style attribute listing in Chapter 4 for complete details on the available border styles.


Default

None.


Provide the width of a single border edge of an element. See also the borderWidth property for setting the width for groups of edges in one statement.


Example

 document.getElementById("announce").style.borderBottomWidth= "thin"; document.getElementById("announce").style.borderLeftWidth = "thick"; document.getElementById("announce").style.borderRightWidth = "2px"; document.getElementById("announce").style.borderTopWidth = "0.5em"; 


Value

Three case-insensitive constantsthin | medium | thickallow the browser to define how many pixels are used to show the border. For more precision, you can also assign a length value (see the discussion of CSS length values at the beginning of Chapter 4).


Default

medium


Controls which table border model the table element should observe.


Example

 document.getElementById("myTable").style.borderCollapse = "separate"; 


Value

Two case-insensitive string constants: collapse | separate.


Default

separate


A shortcut attribute that lets you set multiple border edges to the same or different colors. You may supply one to four space-delimited color values. The number of values determines which sides receive the assigned colors.


Example

 document.getElementById("announce").style.borderColor = "red"; document.getElementById("announce").style.borderColor = "red green"; document.getElementById("announce").style.borderColor = "black rgb(100, 75, 0) #c0c0c0"; document.getElementById("announce").style.borderColor = "yellow green blue red"; 


Value

This property accepts one, two, three, or four color values as a string (including transparent as a color), depending on how many and which borders you want to set with specific colors. See the border-color attribute listing in Chapter 4 for complete details on how the number of values affects this property.


Default

The object's color property (if it is set).


Controls the spacing between table cells when the table is in (the default) separate borders mode, similar to a table object's cellSpacing property. IE 5 for the Macintosh doesn't respond to changes of this property's value. Available in IE as a property of the style object only.


Example

 document.getElementById("myTable").style.borderSpacing= "12px"; 


Value

CSS length value as a string (see the discussion of CSS length values at the beginning of Chapter 4).


Default

None.


This is a shortcut property that lets you set multiple border edges to the same or different style. You may supply one to four space-delimited style values. The number of values determines which sides receive the assigned colors.


Example

 document.getElementById("announce").style.borderStyle = "solid"; document.getElementById("announce").style.borderStyle = "solid double"; document.getElementById("announce").style.borderStyle = "double groove groove double"; 


Value

Style values are case-insensitive constants that are associated with specific ways of rendering border lines. The CSS style constants are: dashed, dotted, double, groove, hidden, inset, none, outset, ridge, and solid. Not all browsers recognize all the values in the CSS recommendation. See the border-style attribute listing in Chapter 4 for complete details on the available border styles.

This property accepts one, two, three, or four style values as a string, depending on how many and which borders you want to set with specific styles. See the border-style attribute listing in Chapter 4 for complete details on how the number of values affects this property.


Default

none


This is a shortcut property that lets you set multiple border edges to the same or different width. You may supply one to four space-delimited width length values. The number of values determines which sides receive the assigned widths.


Example

 document.getElementById("founderQuote").style.borderWidth = "3px 5px"; 


Value

Three case-insensitive constantsthin | medium | thickallow the browser to define exactly how many pixels are used to show the border. For more precision, you can also assign a length value (see the discussion of length values at the beginning of Chapter 4).

This property accepts one, two, three, or four values, depending on how many and which borders you want to set with specific widths. See the border-width attribute listing in Chapter 4 for complete details on how the number of values affects this property.


Default

medium


For an absolute-positioned element, defines the position of the bottom edge of an element's box (content plus bottom padding, border, and/or margin) relative to the bottom edge of the next outermost block content container. IE for Windows and Netscape 6 do something unexpected when the positioned element uses the root positioning context. Instead of using the bottom of the document as the comparative edge, these browsers use the bottom of the browser window space (the viewport in CSS terminology). This means that the precise bottom position of the element varies with the user's browser window size. IE 5 for the Macintosh uses the document's bottom as the comparative edge. This discrepancy makes it more practical to use the bottom property for a positioned element nested inside another positioned element. When the element is relative-positioned, the offset is based on the bottom edge of the inline location where the element would normally appear in the content.

For numeric calculations on this value in IE, retrieve the pixelBottom or posBottom style properties, which return genuine numeric values.


Example

 document.getElementById("blockD2").style.bottom = "35px"; 


Value

String consisting of a numeric value and length unit measure, a percentage, or auto.


Default

auto


Controls the location of a caption element (nested inside a table element) relative to the table's box.


Example

 document.getElementById("myTable").style.captionSide = "bottom"; 


Value

Case-insensitive string of any of the following constants: bottom | left | right | top. Some browsers may be limited to only the bottom and top values.


Default

top


Defines whether the element allows itself to be displayed in the same horizontal band as a floating element. Typically, another element in the vicinity has its float style attribute set to left or right. To prevent the current element from being in the same band as the floating block, set the clear property to the same side (left or right). If you aren't sure where the potential overlap might occur, set the clear property to both. An element that has its clear property set to a value other than none is rendered at the beginning of the next available line below the floating element.


Example

 document.getElementById("myDiv").style.clear = "both"; 


Value

Case-insensitive string of any of the following constants: both | left | none | right.


Default

none


Defines a clipping region of a positionable element. The clipping region is the area of the element layer in which content is visible. Clipping may not work properly in Internet Explorer 4 for the Macintosh. Available in IE as a property of the style and runtimeStyle objects only.


Example

 document.getElementById("art2").style.clip = "rect(5px 100px 40px 0)"; 


Value

Case-insensitive string of either the auto constant or the CSS clip attribute setting that specifies the shape (rect only for now) and the position of the four clip edges relative to the original element's top-left corner. When specifying lengths for each side of the clipping rectangle, observe the clockwise order of values: top, right, bottom, left. See the discussion about CSS length values at the beginning of Chapter 4. A value of auto sets the clipping region to the block that contains the content. In Internet Explorer, the width may extend to the width of the next outermost container (such as the body element).


Default

None.


Return a clipping edge of a positionable element. Available in IE as a property of the currentStyle object only.


Example

 var cl = document.getElementById("art2").style.clipLeft; 


Value

Case-insensitive length string or auto constant. See the discussion about CSS length values at the beginning of Chapter 4.


Default

None.


Sets the foreground (text) color style sheet attribute of the element. For some graphically oriented elements, such as form controls, the color attribute may also be applied to element edges or other features. Such extracurricular behavior is browser specific and may not be the same across browsers.


Example

 document.getElementById("specialDiv").style.color = "green"; 


Value

Case-insensitive CSS color specification (see the discussion at beginning of Chapter 4).


Default

black


Defines extra content that is to be displayed before or after and element (in concert with the :before and :after pseudo-classes. Although the property is available for IE 5 Macintosh and Netscape 6, the values are empty strings and the rendered content (which appears in Netscape 6 only) does not change if you assign it a new value.


Value

See the discussion of the content CSS attribute in Chapter 4.


Default

None.


These properties are placeholders for future implementations of automatic counter mechanisms specified in the CSS specification.


Value

See the discussion of the counterIncrement and counterReset CSS attributes in Chapter 4.


Default

None.


Controls the CSS float attribute for an element, allowing adjacent text content to wrap around block elements, such as images. Changing the value in IE 5 for Macintosh has no effect. The "css" prefix for this property name deflects potential conflicts with the float reserved JavaScript keyword.


Example

 document.getElementById("myDiv").style.cssFloat = "right"; 


Value

String of an allowable constant value: left | right | none.


Default

none


Returns a string of the entire CSS style sheet rule applied to the element. If the rule included shorthand style attribute settings (such as border), browsers return modified versions according to their ideas of what the value means. If you set the style attribute of an element to style="border: groove red 3px", IE for Windows reports the cssText property for that element as:

 BORDER-RIGHT: red 3px groove; BORDER-TOP: red 3px groove; BORDER-LEFT: red 3px groove; BORDER-BOTTOM: red 3px groove 

IE for Macintosh reports:

 {BORDER-TOP: 3px groove red; BORDER-RIGHT: 3px groove red; BORDER-BOTTOM: 3px groove red; BORDER-LEFT: 3px groove red} 

And Mozilla reports:

 border: 3px groove red; 

Note how each browser manipulates the sequence of individual values. Even so, you can assign a shorthand value to the property and in any order you like. Available in IE as a property of the style and runtimeStyle objects only.


Example

 document.getElementById("block3").style.cssText = "margin: 2px; font-size: 14pt"; 


Value

String value of semicolon-delimited style attributes.


Default

None.


See azimuth.


Specifies the shape of the cursor when the screen pointer is atop the element. The precise look of cursors depends on the operating system. Before deploying a modified cursor, be sure you understand the standard ways that the various types of cursors are used within the browser and operating system. Users expect a cursor design to mean the same thing across all applications. Figure 4-3 in Chapter 4 offers a gallery of cursors for each of the cursor constant settings provided by Internet Explorer.

Setting this property affects the cursor only when it is atop the current element and does not set the cursor immediately on a global basis.


Example

 document.getElementById("hotStuff").style.cursor = "pointer"; 


Value

Any one cursor constant as a string, as supported by various browsers and versions.

Cursor name

IE/Windows

IE/Mac

Mozilla

Safari

Opera

alias

n/a

n/a

n/a

n/a

n/a

all-scroll

6

n/a

1.8

n/a

n/a

auto

4

4

all

all

7

cell

n/a

n/a

1.8

n/a

n/a

col-resize

6

n/a

1.8

n/a

n/a

context-menu

n/a

n/a

1.8

n/a

n/a

copy

n/a

n/a

1.8

n/a

n/a

count-down

n/a

n/a

n/a

n/a

n/a

count-up

n/a

n/a

n/a

n/a

n/a

count-up-down

n/a

n/a

n/a

n/a

n/a

crosshair

4

4

all

all

7

default

4

4

all

all

7

e-resize

4

4

all

all

7

grab

n/a

n/a

<1

n/a

n/a

grabbing

n/a

n/a

<1

n/a

n/a

hand

4

4

n/a

all

7

help

4

4

all

all

7

move

4

4

all

all

7

n-resize

4

4

all

all

7

ne-resize

4

4

all

all

7

nesw-resize

n/a

n/a

1.8

n/a

n/a

no-drop

6

n/a

1.8

n/a

n/a

none

n/a

n/a

n/a

n/a

n/a

not-allowed

n/a

n/a

n/a

n/a

n/a

nw-resize

4

4

all

all

7

nwse-resize

n/a

n/a

1.8

n/a

n/a

pointer

4

4

all

all

7

progress

6

n/a

<1

n/a

9

row-resize

6

n/a

1.8

n/a

n/a

s-resize

4

4

all

all

7

se-resize

4

4

all

all

7

spinning

n/a

n/a

all

n/a

n/a

sw-resize

4

4

all

all

7

text

4

4

n/a

n/a

n/a

url(uri)

6

n/a

n/a

n/a

n/a

vertical-text

6

n/a

1.8

n/a

n/a

w-resize

4

4

all

all

7

wait

4

4

all

all

7


The IE 6 setting of an external URL requires an address of a cursor file of extension .cur or .ani.


Default

auto


Returns the writing script direction of the current element. Intended primarily for elements inside documents with mixed writing script directions (e.g., French text intermingled among Arabic).


Example

 document.getElementById("term3").style.direction = "ltr"; 


Value

String constant values: ltr | rtl.


Default

ltr


Controls the CSS box type used to render the element. The most common settings for body content dictate whether an element is rendered as a block or inline element. When set to none, the element is hidden, and surrounding content cinches up to fill the space. Some box types are specific to tables and lists.


Example

 document.getElementById("instructionDiv").style.display = "none"; 


Value

Any one display type constant as a string, as supported by various browsers and versions.

Display type

IE/Win

IE/Mac

NN

Mozilla

Safari

Opera

CSS

block

5

4

4

all

all

7

2

compact

n/a

n/a

n/a

n/a

n/a

n/a

<2.1

inline

5

4

4

all

all

7

2

inline-block

5.5

n/a

n/a

n/a

n/a

n/a

<2.1

inline-table

n/a

5

n/a

n/a

all

7

2

list-item

5

5

n/a

all

all

7

2

marker

n/a

n/a

n/a

n/a

n/a

n/a

<2.1

none

4

4

4

all

all

7

2

run-in

n/a

5

n/a

n/a

n/a

7

2

table

n/a

5

n/a

all

all

7

2

table-caption

n/a

5

n/a

all

all

7

2

table-cell

n/a

5

n/a

all

all

7

2

table-column-group

n/a

5

n/a

n/a

n/a

n/a

2

table-footer-group

5.5

5

n/a

all

all

7

2

table-header-group

5

5

n/a

all

all

7

2

table-row

n/a

5

n/a

all

all

7

2

table-row-group

n/a

5

n/a

n/a

n/a

n/a

2



Default

Element-dependent.


See azimuth.


When a table is set to render the separate cell box format (the default), and a border is established for td elements in that table, the emptyCells style property controls whether the table renders borders around cells that have no content.


Example

 document.getElementById("myTable").style.emptyCells = "hide"; 


Value

String of allowable constant values: hide | show.


Default

show


Sets the visual, reveal, or blend filter used to display or change content of an element. A visual filter can be applied to an element to produce effects such as content flipping, glow, drop shadow, and many others. A reveal filter is applied to an element when its visibility changes. The value of the reveal filter determines what visual effect is to be applied to the transition from hidden to shown (or vice versa). This includes effects such as wipes, blinds, and barn doors. A blend filter sets the speed at which a transition between states occurs. Although the filter property is present in Internet Explorer for Macintosh, it does not operate there.


Example

 document.getElementById("fancy").style.filter= "dropshadow( )"; 


Value

Each filter property may have more than one space-delimited filter type associated with it. Each filter type is followed by a pair of parentheses, which may convey parameters about the behavior of the filter for the current element. A parameter generally consists of a name/value pair, with assignment performed by the equals symbol. Note that Microsoft instituted an entirely new filter syntax starting with IE 5.5 for Windows. The new syntax runs in parallel with the old (for now). See the filter style sheet attribute listing in Chapter 4 for details on filter settings and parameters.


Default

None.


This is a shorthand property that lets you set one or more font-related propertiesfontFamily, fontSize, lineHeight (which must be preceded by a / symbol in this property), fontStyle, fontVariant, and fontWeightwith one assignment statement. A space-delimited list of values (in any sequence) is applied to the specific font properties for which the value is a valid type. Or, you can short-circuit these individual settings by choosing one of the default (operating-system-dependent) system fonts: caption | icon | menu | message-box | small-caption | status-bar.


Example

 document.getElementById("subhead").style.font = "bolder small-caps 16pt"; 


Value

For syntax and examples of value types for font-related properties, see the respective property listing.


Default

None.


Provides a prioritized list of font families to be used to render the object's content. One or more font family names may be included in a comma-delimited list of property values. If a font family name consists of multiple words, the family name must be inside a set of inner quotes. Available in IE as a property of the style and runtimeStyle objects only, but the individual font properties are available in currentStyle, as well.


Example

 document.getElementById("subhead").style.fontFamily =     "'Century Schoolbook', Times, serif"; 


Value

Any number of font family names, comma delimited. Multiword family names must be quoted. Recognized generic family names are: serif | sans-serif | cursive | fantasy | monospace.


Default

Browser default.


Indicates the font size of the element. The font size can be set in several ways. A collection of constants (xx-small, x-small, small, medium, large, x-large, xx-large) defines what are known as absolute sizes. In truth, these are absolute only in a single browser in a single operating system, since the reference point for these sizes varies with browser and operating system (analogous to the old HTML font sizes of 1 through 7). But they do let the author have confidence that one element set to large is rendered larger than medium.

Another collection of constants (larger, smaller) is known as relative sizes. Because the font-size style attribute is inherited from the parent element, these relative sizes are applied to the parent element to determine the font size of the current element. It is up to the browser to determine exactly how much larger or smaller the font size is, and a lot depends on how the parent element's font size is set. If it is set with one of the absolute sizes (large, for example), a child's font size of larger means the font is rendered in the browser's x-large size. The increments are not as clear-cut when the parent font size is set with a length or percentage.

If you elect to use a length value for the fontSize property, you will achieve greater consistency across operating systems if units such as pixels (px) or ems (em), instead of points (pt). Em units are calculated with respect to the size of the parent element's font size. Finally, you can set fontSize to a percentage, which is calculated based on the size of the parent element's font size.


Example

 document.getElementById("teeny").style.fontSize = "x-small"; 


Value

Case-insensitive string values from any of the following categories. For an absolute size, one of the following constants: xx-small | x-small | small | medium | large | x-large | xx-large. For a relative size, one of the following constants: larger | smaller. For a length, see the discussion about CSS length values at the beginning of Chapter 4. For a percentage, the percentage value and the % symbol.


Default

Parent element's font size.


Provides the font aspect value, usually of the first font family in a font-family attribute sequence, forcing alternative font families to calculate their rendered font size to closely match that of the primary font family. Although this property is a member of the style object in IE 5/Mac and Mozilla, neither the style attribute nor scripted changes to it affect the font display.


Example

 document.getElementById("myDIV").style.fontSizeAdjust = "0.56"; 


Value

Numeric aspect value as a quoted string, or none.


Default

none


Provides the character spacing for the element, based on available spacing widths available for the current font family. Although this property is a member of the style object in IE 5/Mac and Mozilla, neither the style attribute nor scripted changes to it affect the font display.


Example

 document.getElementById("myDIV").style.fontStretch= "ultra-condensed"; 


Value

String of allowable constant values: normal | wider | narrower | ultra-condensed | extra-condensed | condensed | semi-condensed | semi-expanded | expanded | exTRa-expanded | ultra-expanded, or none.


Default

none


Specifies whether the element is rendered in a normal (roman), italic, or oblique font style. If the fontFamily includes font faces labeled Italic and/or Oblique, the setting of the fontStyle attribute summons those particular font faces from the browser's system. But if the specialized font faces are not available in the system, the normal font face is usually algorithmically slanted to look italic. Output sent to a printer with such font settings relies on the quality of arbitration between the client computer and printer to render an electronically generated italic font style. Personal computer software typically includes other kinds of font rendering under the heading of "Style." See fontVariant and fontWeight for other kinds of font "styles."


Example

 document.getElementById("emphasis").style.fontStyle = "italic"; 


Value

One the following string constant values: normal | italic | oblique.


Default

normal


Specifies whether the element should be rendered in all uppercase letters in such a way that lowercase letters of the source code are rendered in smaller uppercase letters. If a font family contains a small caps variant, the browser should use it automatically. More likely, however, the browser calculates a smaller size for the uppercase letters that take the place of source code lowercase letters. In practice, Internet Explorer 4 renders the entire source code content as uppercase letters of the same size as the parent element's font, regardless of the case of the source code. Later IE versions, Mozilla, Safari, and Opera use two different uppercase sizes.


Example

 document.getElementById("emphasis").style.fontVariant = "small-caps"; 


Value

Any of the following constant values as strings: normal | small-caps.


Default

normal


Sets the weight (boldness) of the element's font. CSS provides a weight rating scheme that is more granular than most browsers render on the screen, but the finely tuned weights may come into play when the content is sent to a printer. The scale is a numeric rating from 100 to 900 at 100-unit increments. Therefore, a fontWeight of 100 would be the least bold that would be displayed, while 900 would be the boldest. A setting of normal (the default weight for any font) is equivalent to a fontWeight value of 400; the standard bold setting is equivalent to 700. Other settings (bolder and lighter) let you specify a weight relative to the parent element's weight.


Example

 document.getElementById("hotStuff").style.fontWeight = "bold"; 


Value

Any of the following constant values: bold | bolder | lighter | normal | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900.


Default

normal


Indicate the height and width (and their units) of the element. Because the values are strings containing the assigned units, you cannot use these properties for calculation. Grab copies of the numbers by using parseFloat( ) on the values; or for IE, use pixelHeight, pixelWidth, posHeight, and posWidth properties. Changes to these properties may not be visible unless the element has its position style attribute set.

In IE 6 and 7 standards compatibility mode (where document.compatType == "CSS1Compat"), these dimensions apply to only the content portion of an element, irrespective of borders, padding, or margins. For example, if a positioned element that is equipped with padding and borders must be sized to a precise rectangular size, you must subtract the thicknesses of the padding and borders from the height and width values so that the overall element is the desired size.


Example

 document.getElementById("viewArea").style.height = "450px"; 


Value

String consisting of a numeric value and length measure or percentage.


Default

None.


Controls the presence of the Input Method Editor in IE for Windows for browser and system versions that support languages such as Chinese, Japanese, and Korean.


Example

 document.getElementById("nameEntry").style.imeMode = "active"; 


Value

String of allowable constant values: active | auto | disabled | inactive.


Default

auto


Intended primarily for languages that display characters in vertical sentences, controls the progression of content. Replaced starting with IE 5.5 for Windows by the writingMode property.


Value

One of the constant values (as a string): horizontal | vertical-ideographic.


Default

horizontal


This is a shorthand property that lets you set one or more layout grid properties (layoutGridChar, layoutGridLine, layoutGridMode, and layoutGridType) with one assignment statement. These attributes are used primarily with Asian language content.


Example

 document.getElementById("subhead").style.layoutGrid = "2em strict"; 


Value

For syntax and examples of value types for layoutGrid-related properties, see the respective property listing.


Default

None.


Dictates the size of Asian language character grid for block-level elements.


Example

 document.getElementById("subhead").style.layoutGrid Char= "auto"; 


Value

String consisting of an explicit CSS length value or auto or none.


Default

none


Dictates the line height of Asian language character grid for block-level elements.


Example

 document.getElementById("subhead").style.layoutGrid Line= "120%"; 


Value

String consisting of an explicit CSS length value or auto or none.


Default

none


Specifies whether the Asian language character grid should be one- or two-dimensional.


Example

 document.getElementById("subhead").style.layoutGrid Mode= "both"; 


Value

String constant values: both | char (for inline elements) | line (for block-level elements) | none.


Default

both


Controls how the layout grid responds to characters of varying width.


Example

 document.getElementById("subhead").style.layoutGrid Type = "strict"; 


Value

String constant values: fixed | loose | strict.


Default

loose


For positionable elements, defines the position of the left edge of an element's box (content plus left padding, border, and/or margin) relative to the left edge of the next outermost block content container. When the element is relative-positioned, the offset is based on the left edge of the inline location of where the element would normally appear in the content.

For calculations on this value, use parseFloat( ) on the returned value; or, in IE, retrieve the pixelLeft or posLeft properties, which return genuine numeric values.


Example

 document.getElementById("blockD2").style.left = "45px"; 


Value

String consisting of a numeric value and length unit measure, a percentage, or auto.


Default

auto


Officially a property of the W3C DOM CSSStyleDeclaration object, this property returns the number of individual CSS properties contained by the object.


Value

Integer.


Default

Varies with browser implementation.


Specifies the spacing between characters within an element. Browsers normally define the character spacing based on font definitions and operating system font rendering. Assigning a negative value tightens the spacing, but be sure to test the effect on the selected font for readability on different operating systems.


Example

 document.body.style.letterSpacing = "1.1em"; 


Value

A string of a length value (with unit of measure) or normal. The best results are achieved by using units that are based on the rendered font size (em and ex). A setting of normal is how the browser sets the letters without any intervention.


Default

normal


Controls line breaking rules for Japanese text.


Example

 document.body.style.lineBreak = "strict"; 


Value

String constant values: normal | strict.


Default

normal


Indicates the height of the inline box (the box holding one physical line of content). See the line-height style attribute in Chapter 4 for details on browser quirks and inheritance traits of different types of values.


Example

 document.getElementById("tight").style.lineHeight = "1.1em"; 


Value

A string of a length value (with unit of measure) or normal.


Default

normal


This is a shorthand property for setting up to three list-style properties in one assignment statement. Whichever attributes you don't explicitly set with this attribute assume their default values. These properties define display characteristics for the markers automatically rendered for list items inside ol and ul elements. This is available in IE as a property of the style and runtimeStyle objects only, but individual properties are properties of currentStyle, as well.


Example

 document.getElementById("itemList").style.listStyle = "square outside none"; 


Value

See the individual attribute entries for listStyleType, listStylePosition, and listStyleImage for details on acceptable values for each. You may include one, two, or all three values in the list-style attribute setting in any order you wish.


Default

None.


Provides the URL for an image that is to be used as the marker for a list item. Because this attribute can be inherited, a setting (including none) for an individual list item can override the same attribute or property setting in its parent.


Example

 document.getElementById("itemList").style.listStyleImage = "url(images/3DBullet.gif)"; 


Value

Use none (as a string) to override an image assigned to a parent element. Otherwise, supply any valid full or relative URL (in the CSS URL format) to an image file with a MIME type that is readable by the browser.


Default

none


Specifies whether the marker is inside or outside (outdented) the box containing the list item's content. When listStylePosition is set to inside and the content is text, the marker appears to be part of the text block. In this case, the alignment (indent) of the list item is the same as normal, but without the outdented marker.


Example

 document.getElementById("itemList").style.listStylePosition = "inside"; 


Value

Either constant value as a string: inside | outside.


Default

outside


Specifies the kind of item marker to be displayed with each item. This attribute is applied only if listStyleImage is none (or not specified). The constant values available for this attribute are divided into two categories. One set is used with ul elements to present a filled disc, an empty circle, or a filled square. The other set is for ol elements, which has list items that can be marked in sequences of arabic numerals, roman numerals (uppercase or lowercase), letters of the alphabet (uppercase or lowercase), and some other character sequences of other languages if the browser and operating system supports those languages.


Example

 document.getElementById("itemList").style.listStyleType = "circle"; 


Value

One constant value as a string that is relevant to the type of list container. For ul: circle | disc | square. For ol: decimal | decimal-leading-zero | lower-roman | upper-roman | lower-greek | lower-alpha | lower-latin | upper-alpha | upper-latin | hebrew | armenian | georgian | cjk-ideographic | hiragana | katakana | hiragana-iroha | katakana-iroha. Commonly supported ol element sequences are treated as shown in the following table.

Type

Example

decimal

1, 2, 3, ...

decimal-leading-zero

01, 02, 03, ...

lower-alpha

a, b, c, ...

lower-greek

α, β, γ, ...

lower-roman

i, ii, iii, ...

upper-alpha

A, B, C, ...

upper-roman

I, II, III, ...



Default

disc (for ul); decimal (for ol).


This is a shortcut property that can set the margin widths of up to four edges of an element with one statement. A margin is space that extends beyond the border of an element to provide extra empty space between adjacent or nested elements, especially those that have border attributes set. You may supply one to four space-delimited margin values. The number of space-delimited values determines which sides receive the assigned margins.


Example

 document.getElementById("logoWrapper").style.margin = "5px 8px"; 


Value

This property accepts one, two, three, or four space-delimited values inside one string, depending on how many and which margins you want to set. See the margin attribute listing in Chapter 4 for complete details on how the number of values affects this property. Values for the margins can be lengths, percentages of the next outermost element size, or the auto constant.


Default

0


All four properties set the width of a single margin edge of an element. A margin is space that extends beyond the element's border and is not calculated as part of the element's width or height.


Example

 document.getElementById("logoWrapper").style.marginTop = "5px"; document.getElementById("navPanel").style.marginLeft = "10%"; 


Value

Values for margin widths can be length values, percentages of the next outermost element size, or the auto constant.


Default

0


Controls the space between list item markers (which occupy their own box in the CSS box model) and the box that contains the list item text. Although the property is available for Mozilla and Opera, the value is an empty string and the rendered content does not change if you assign it a new value. Additionally, the corresponding CSS property has been deleted from CSS 2.1.


Value

A string of a length value (with unit of measure) or auto.


Default

None.


Sets crop mark type for an @page rule. Although the property is available for IE 5 Macintosh, Mozilla, and Opera, the values are empty strings and the rendered content does not change if you assign it a new value.


Value

Case-insensitive string of any of the following constants: crop | cross | none.


Default

none


Define loose heights and widths for an element so that, for "max" properties, an element is allowed to grow no bigger in the designated dimension, or, for "min" properties, an element can expand in the designated dimension to accommodate more than expected content or rendering situations. IE 6 supports only the minHeight property, and it can be used only for tr, th, and td elements. IE 7, however, implements all properties correctly when running in CSS compatibility mode (i.e., with a modern DOCTYPE declaration).


Value

CSS length value (see Chapter 4) as a string.


Default

None.


A shortcut property that lets you set the radius of one or more border corners.


Value

One to four length values as a string. See -moz-border-radius in Chapter 4 for value details.


Default

0


Each property controls the radius of one border corner.


Value

Length value as a string. See -moz-border-radius in Chapter 4 for value details.


Default

0


Defines the level of opacity of the element. The lower the value, the more transparent the element becomes. This is the proprietary Mozilla version of the proprietary Microsoft opaque filter, and has been superceded in more recent versions by the genuine opacity property.


Example

 document.getElementById("menuWrapper").style.MozOpacity = "40%"; 


Value

Numeric string value between 0 and 1.


Default

1 (completely opaque)


Defines the level of opacity of the element. The lower the value, the more transparent the element becomes.


Example

 document.getElementById("menuWrapper").style.MozOpacity = "40%"; 


Value

Numeric string value between 0 and 1.


Default

1 (completely opaque)


For a block-level element's content that spreads across page boxes, specify the minimum number of lines of the element that must appear at the bottom of the page (orphans) or at the top of the next page (widows). Although these properties are members of the style object in IE 5/Mac, Mozilla, and Opera, neither the style attribute nor scripted changes to it affect the printed output.


Example

 document.getElementById("sec23").style.orphans = "3"; 


Value

Integer as a string.


Default

None.


This is a shorthand property for getting or setting the outlineColor, outlineStyle, and/or outlineWidth properties of an outline around an element in one statement. You must specify an outline style (see outlineStyle) for changes of this property to affect the display. An outline is like a border, but overlays the element without occupying any content space or affecting the element's dimensions.


Example

 document.getElementById("announce").style.outline = "solid blue 4px"; 


Value

Space-delimited string. For the outlineStyle and outlineWidth component values, see the respective properties in this chapter. For details on the outlineColor value, see the section about CSS colors at the beginning of Chapter 4.


Default

None.


Controls the color of an outline.


Example

 document.getElementById("announce").style.outlineColor = "rgb(100, 75, 0)"; 


Value

CSS color value or constant invert. For details on CSS color values, see the section about colors at the beginning of Chapter 4.


Default

invert


Controls the distance beyond the element's border (equally in each direction) where the outline is drawn..


Example

 document.getElementById("announce").style.outlineOffset = "5px"; 


Value

A CSS length value. One value controls all sides of the outline.


Default

0


Controls the line type of an outline.


Example

 document.getElementById("announce").style.outlineStyle = "solid"; 


Value

Style values are case-insensitive constants that are associated with specific ways of rendering outline (and border) lines. The CSS style constants are: dashed, dotted, double, groove, hidden, inset, none, outset, ridge, and solid.


Default

none


Controls the thickness of the outline lines.


Example

 document.getElementById("announce").style.outlineWidth = "2px"; 


Value

Three case-insensitive constantsthin | medium | thickallow the browser to define exactly how many pixels are used to show the border. For more precision, you can also assign a length value (see the discussion of CSS length values at the beginning of Chapter 4).


Default

medium


Specifies how a positioned element should treat content that extends beyond the boundaries established in the style sheet rule. See the discussion of the overflow style sheet attribute in Chapter 4 for details.


Example

 document.getElementById("myDiv").style.overflow = "scroll"; 


Value

Any of the following constants as a string: auto | hidden | scroll | visible.


Default

visible


Specify how a positioned element should treat content that extends beyond the horizontal (overflowX) or vertical (overflowY) boundaries established in the style sheet rule.


Example

 document.getElementById("myDiv").style.overflow X= "scroll"; 


Value

Any of the following constants as a string: auto | hidden | scroll | visible.


Default

visible


This is a shortcut property that can set the padding widths of up to four edges of an element with one statement. Padding is space that extends around the content box of an element up to but not including any border that may be specified for the element. Padding picks up the background image or color of its element. As you add padding to an element, you increase the size of the visible rectangle of the element without affecting the content block size. You may supply one to four space-delimited padding values. The number of values determines which sides receive the assigned padding.


Example

 document.getElementById("logoWrapper").style.padding = "3px 5px"; 


Value

This property accepts one, two, three, or four space-delimited values inside one string, depending on how many and which edges you want to pad. See the padding attribute listing in Chapter 4 for complete details on how the number of values affects this property. Values for padding widths can be lengths, percentages of the next outermost element size, or the auto constant.


Default

0


All four properties set the width of a single padding edge of an element. Padding is space that extends between the element's border and content box. Padding is not calculated as part of the element's width or height.


Example

 document.getElementById("logoWrapper").style.paddingTop = "3px"; document.getElementById("navPanel").style.paddingLeft = "10%"; 


Value

Values for padding widths can be length values, percentages of the next outermost element size, or the auto constant.


Default

0


Points to the name of an existing @page rule (when the rule contains an identifier, such as @page figures {size: landscape}) in order to apply that rule to the current block-level element. Although this property is a member of the style object in IE 5/Mac, Mozilla, and Opera, neither the style attribute nor scripted changes to it affect the printed output.


Value

String identifier.


Default

None.


Define how content should treat a page break around an element when the document is sent to a printer. Page breaks are not rendered in the visual browser as they may be in word processing programs; on screen, long content flows in one continuous scroll on the screen. Also see the extensive discussion of page breaks in the listing for the page-break-after and page-break-before style attributes in Chapter 4.


Example

 document.getElementById("hardBR").style.pageBreakAfter = "always"; document.getElementById("navPanel").style.paddingLeft = "10%"; 


Value

All supporting browsers recognize four constant values (as strings): always | auto | left | right. Additionally, IE for Windows supports an empty string, which has the same effect as the W3C CSS avoid constant.


Default

auto


Defines whether the element allows itself to be split across printed pages. Although this property is a member of the style object in IE 5/Mac, Mozilla, and Opera, neither the style attribute nor scripted changes to it affect the printed output.


Value

A constant value (as a string): auto | avoid.


Default

auto


Officially a property of the W3C DOM CSSStyleDeclaration object, this property returns a reference to the styleSheet object that is the parent of the current style sheet. This occurs only in nested situation, such as when a style rule is contained in a construction such as an @media block.


Value

Reference to a styleSheet object.


Default

None.


See azimuth.


For positionable elements, these properties define the pixel position of the edges of an element's box (content plus padding, border, and/or margin) relative to the corresponding edges of the next outermost block content container. When the element is relative-positioned, the measure is based on the edges of the inline location of where the element would normally appear in the content. Use these properties for calculation (including path animation) instead of the bottom, left, right, and top properties, which store their values as strings with the unit names. Available as a property of the IE style and runtimeStyle objects only.


Example

 document.getElementById("myDIV").style.pixelLeft++; 


Value

Integer.


Default

None.


Specify the height and width of the element in pixels. Use these properties for calculation instead of properties such as height and width, which return strings including units. Changes to these properties may not be visible unless the element has its position style attribute set. Available as a property of the IE style and runtimeStyle objects only.


Example

 var midWidth = document.getElementById("myDIV").style.pixelWidth/2; 


Value

Integer


Default

None.


See azimuth.


For positionable elements, these properties define the position of the edges of an element's box (content plus padding, border, and/or margin) relative to the corresponding edges of the next outermost block content container. When the element is relative-positioned, the measure is based on the edges of the inline location where the element would normally appear in the content. Most importantly, these properties' values are numeric and in the unit of measure set in the CSS bottom, left, right, or top attribute. Use these properties for calculation (including path animation) instead of the bottom, left, right, and top properties, which store their values as strings with the unit names. All math is in the specified units. Also contrast these properties with the pixelBottom, pixelLeft, pixelRight, and pixelTop properties, which are integer values for pixel measures only. Available as a property of the IE style and runtimeStyle objects only.


Example

 document.getElementById("myDIV").style.posLeft =   document.getElementById("myDIV").style.posLeft + 1.5; 


Value

Floating-point number.


Default

None.


Specify the numeric height and width of the element in the units set by the CSS positioning-related attributes. Use these properties for calculation instead of properties such as height and width, which return strings including units. All math is in the specified units. Also contrast these properties with the pixelHeight and pixelWidth properties, which are integer values for pixel measures only. Available as a property of the IE style and runtimeStyle objects only.


Example

 document.getElementById("myDIV").style.posWidth = 10.5; 


Value

Floating-point number.


Default

None.


For positionable elements, returns the value assigned to the style sheet position attribute. This property is actually read/write, but you cannot change a positioned element into a static one or vice-versa.


Example

 var posType = document.getElementById("myDIV").style.position; 


Value

String constant: absolute | fixed | relative | static. The fixed value is not supported in IE for Windows through Version 6.


Default

None.


Assigns pairs of characters to be used as quote marks (especially for the q element). See the quotes CSS property in Chapter 4 for implementation notes. Don't be surprised if attempts to write new values to this property are unsuccessful.


Value

A string consisting of two or four quoted strings (nested quotes). The first pair provides characters for first-level quotes; the second pair supplies characters to nested quotes.


Default

None.


See azimuth.


For an absolute-positioned element, defines the position of the right edge of an element's box (content plus right padding, border, and/or margin) relative to the right edge of the next outermost block content container.

For numeric calculations on this value in IE, retrieve the pixelRight or posRight style properties, which return genuine numeric values.


Example

 document.getElementById("blockD2").style.right = "25px"; 


Value

String consisting of a numeric value and length unit measure, a percentage, or auto.


Default

auto


Controls alignment of content in a ruby element. Changes to this property affect IE for Windows only. Ruby-related styles are defined in CSS3.


Example

 document.getElementById("myRuby").style.rubyAlign = "center"; 


Value

Case-insensitive string of any of the following constants: auto | center | distribute-letter | distribute-space | left | line-edge | right.


Default

auto


Controls text overhang characteristics of content in a ruby element. Changes to this property affect IE for Windows only. Ruby-related styles are defined in CSS3.


Example

 document.getElementById("myRuby").style.rubyOverhang="whitespace"; 


Value

Case-insensitive string of any of the following constants: auto | none | whitespace.


Default

auto


Controls whether ruby (rt element) text renders on the same line or above its related ruby base (rb element) text. Changes to this property affect IE for Windows only. Ruby-related styles are defined in CSS3.


Example

 document.getElementById("myRuby").style.rubyPosition = "inline"; 


Value

Case-insensitive string of any of the following constants: above | inline.


Default

above


Controls the colors for specific components of a scrollbar user interface element associated with an applet, body, div, embed, object, or textarea element. See the description of these CSS attributes in Chapter 4 for details about which component each property governs.


Example

 document.getElementById("comments").style.scrollbarArrowColor = "rgb(100, 75, 0"); 


Value

Case-insensitive CSS color specification (see discussion at beginning of Chapter 4).


Default

None.


For a page context defined by an @page rule, this property controls the page size or orientation. Although the property is available for Mozilla and Opera, the value is an empty strings and the property has no influence over the page context.


Value

CSS length values (as a string) or case-insensitive string of any of the following constants: auto | landscape | portrait. For length values, a single value is applied to height and width; two space-delimited length values are applied to width and height, respectively.


Default

auto


See azimuth.


Specifies on which side of the containing box the element aligns so that other content wraps around the element. When the property is set to none, the element appears in its source code sequence, and at most one line of surrounding text content appears in the same horizontal band as the element. See the float style attribute in Chapter 4 for more details. IE 5 for Macintosh duplicates this property as cssFloat, the DOM 2 version.


Example

 document.getElementById("myDIV").style.styleFloat = "right"; 


Value

One of the following constants (as a string): none | left | right.


Default

None.


Acts as a switch at load time to direct the browser to start rendering the table based on column widths set by the first row, or wait until the table data is loaded so that the browser can calculate optimum column widths based on cell contents. Changes to this property have no effect on a rendered table.


Example

 document.getElementById("myTable").style.tableLayout = "fixed"; 


Value

One of the following constants (as a string): auto | fixed.


Default

auto


Determines the horizontal alignment of text within an element's box.


Example

 document.getElementById("myDIV").style.textAlign = "right"; 


Value

One of the four constants (as a string): center | justify | left | right.


Default

Depends on default language of the browser.


Determines the horizontal alignment of the last line of text within an element's box. This style attribute may be helpful to obtain the desired look if you use some of the other proprietary text alignment style properties in IE 5.5.


Example

 document.getElementById("myDIV").style.textAlignLast = "justify"; 


Value

One of the following constants (as a string): auto | center | justify | left | right.


Default

auto


Controls the spacing between ideographic (typically Asian languages) and nonideographic characters.


Example

 document.getElementById("myDIV").style.textAutospace = "ideograph-numeric"; 


Value

One of the following constants (as a string): ideograph-alpha | ideograph-numeric | ideograph-parenthesis | ideograph-space | none.


Default

none


Specifies additions to the text content of the element in the form of underlines, strikethroughs, overlines, and (in Navigator and CSS) blinking. Browsers use this style attribute internally to assign by default underlines to a elements and strikethroughs to strike elements, so the default value varies with element type. You may specify more than one decoration style by supplying values in a space-delimited list. While browsers accept the (CSS optional) blink value, they (thankfully) do not cause the text to blink. Text decoration has an unusual parent-child relationship. Values are not inherited, but the effect of a decoration carries over to nested items in most cases. Therefore, unless otherwise overridden, an underlined p element underlines a nested b element within. Internet Explorer also includes Boolean properties for each decoration type.


Example

 document.getElementById("emphasis").style.textDecoration = "underline"; 


Value

In addition to none, any of the following four constants (as a string): blink | line-through | overline | underline. Multiple values may be included in the string as a space-delimited list.


Default

Element and internal style sheet dependent.


Specifies whether the specified text decoration feature is enabled for the element. Each of these properties corresponds to a value that can be assigned to the text-decoration style attribute in CSS (see Chapter 4). Internet Explorer does not blink text, so the textdecorationBlink property is ignored. Setting textdecorationNone to true sets all other related properties to false. Setting these properties on the Macintosh version of IE 4 does not alter the content. Use the texTDecoration property insteadgood practice all around.


Example

 document.getElementById("emphasis").style.textDecorationLineThrough = "true"; 


Value

Boolean value: true | false.


Default

false


Specifies the size of the indent at the first line of a block of inline text (such as a p element). Only the first line is affected by this setting. A negative value can be used to outdent the first line, but be sure the text does not run beyond the left edge of the browser window or frame.


Example

 document.getElementById("firstGraph").style.textIndent = "0.5em"; 


Value

Positive or negative CSS length value (see Chapter 4) as a string.


Default

0px


Specifies detailed character distribution techniques for any block-level element that has a text-align CSS attribute or a textAlign style property set to justify.


Example

 document.getElementById("inset").style.textJustify = "distribute-center-last"; 


Value

One of the following constants (as a string): auto | distribute | distribute-all-lines | distribute-center-last | inter-cluster | inter-ideograph | inter-word | kashdia | newspaper. See the text-justify attribute in Chapter 4 for details on the meanings of these values.


Default

auto


For Arabic text in a block-level element with a text alignment style that is set to justify, controls the ratio of kashida expansion to white space expansion.


Example

 document.getElementById("inset").style.textKashidaSpace = "15%"; 


Value

Percentage value as a string.


Default

0%


Controls whether text content that overflows a fixed box should display an ellipsis (...) at the end of the line to indicate more text is available. The element should also have its overflow style attribute or property set to hidden.


Example

 document.getElementById("textBox").style.textOverflow = "ellipsis"; 


Value

One of the allowable constant string value: clip | ellipsis.


Default

clip


Controls the specifications for shadow effects on the element's text. Although this property is a member of the style object in IE 5/Mac, Mozilla, and Opera, neither the style attribute nor scripted changes to it affect the element's text display.


Value

A string consisting of one or more shadow specifications. Each shadow specification consists of space-delimited values for a color, a length for the offset to the right of the text, a length for the offset below the text, and an optional blur radius value. Multiple shadow specifications are comma-delimited or a value of none to turn off the shadow.


Default

none


Controls the capitalization of the element's text. When a value other than none is assigned to this attribute, the cases of all letters in the source text are arranged by the style sheet, overriding the case of the source text characters.


Example

 document.getElementById("heading").style.textTransform = "capitalize"; 


Value

A value of none allows the case of the source text to be rendered as is. Other available constant values (as strings) are: capitalize | lowercase | uppercase. A value of capitalize sets the first character of every word to uppercase. Values lowercase and uppercase render all characters of the element text in their respective cases.


Default

none


Controls whether an underline (i.e., an element with a text-decoration style set to underline) is rendered above or below the text.


Example

 document.getElementById("heading").style.textUnderlinePosition = "above"; 


Value

IE 5.5 recognizes two constant values: above | below. IE 6 adds the values auto and auto-pos (which appear to do the same thing). The default value also changed between versions, from below to auto. In IE 6, the auto value underlines vertical Japanese text "above" (to the right) of the characters.


Default

none (IE 5.5); auto (IE 6).


For positionable elements, defines the position of the top edge of an element's box (content plus top padding, border, and/or margin) relative to the top edge of the next outermost block content container. When the element is relative-positioned, the offset is based on the top edge of the inline location of where the element would normally appear in the content.

For calculations on this value, use parseFloat( ) on the returned value; or, in IE, retrieve the pixelTop or posTop properties, which return genuine numeric values.


Example

 document.getElementById("blockD2").style.top = "40px"; 


Value

String consisting of a numeric value and length unit measure, a percentage, or auto.


Default

auto


Controls the embedding of bidirectional text (such as a mixture of French and Arabic) in concert with the direction style attribute.


Example

 document.getElementById("blockD2").style.unicodeBidi = "bidi-override"; 


Value

String constant values: bidi-override | embed | normal.


Default

normal


Specifies the vertical alignment characteristic of the element. This property operates in two spheres, depending on the selection of values you use. See the in-depth discussion of the vertical-align style sheet property in Chapter 4 for details.


Example

 document.getElementById("myDIV").style.verticalAlign = "text-top"; 


Value

String value of an absolute measure (with units), a percentage (relative to the next outer box element), or one of the many constant values: bottom | top | baseline | middle | sub | super | text-bottom | text-top.


Default

baseline


Specifies the state of the positioned element's visibility. Surrounding content does not close up the space left by an element that has its visibility property set to hidden.


Example

 document.getElementById("myDIV").style.visibility = "hidden"; 


Value

One of the constant values (as a string): collapse | hidden | inherit | visible.


Default

visible


See azimuth.


Controls intepretation of whitespace (such as leading spaces and line breaks) from the source code.


Example

 document.getElementById("myDIV").style.whiteSpace = "pre"; 


Value

One of the constant values (as a string): normal | nowrap | pre. Value of normal allows browsers to word-wrap lines in block elements and ignore leading spaces. Value of nowrap causes source code not to word-wrap, but still ignores leading spaces. Value of pre preserves leading spaces, extra spaces, and carriage returns in the source code. Note that IE 6 for Windows does not respond to the pre value unless the DOCTYPE element values place the browser into standards compatibility mode.


Default

normal


See orphans.


See height.


Specifies the word-break style for ideographic languages or content that mixes Latin and ideographic languages.


Example

 document.getElementById("myDIV").style.wordBreak = "keep-all"; 


Value

One of the constant values (as a string): break-all | keep-all | normal.


Default

normal


Governs the length of space between words. IE 5 for Macintosh may exhibit overlap problems with the word-spacing of elements nested inside the one being controlled.


Example

 document.getElementById("myDIV").style.wordSpacing = "1.0em"; 


Value

CSS length value (as a string) or the constant normal.


Default

normal


Specifies the word-wrapping style for block-level, specifically sized inline, or positioned elements. If a single word (i.e., without any whitespace) extends beyond the width of the element containing box, the normal behavior is to extend the content beyond the normal box width, without breaking. But you can force the long word to break at whatever character position occurs at the edge of the box.


Example

 document.getElementById("myDIV").style.wordWrap = "break-word"; 


Value

One of the constant values (as a string): break-word | normal.


Default

normal


Intended primarily for languages that display characters in vertical sentences, this controls the progression of content, left-to-right, or right-to-left.


Example

 document.getElementById("myDIV").style.writingMode = "lr-tb"; 


Value

One of the constant values (as a string): lr-tb | tb-rl. Value of tb-rl can rotate text of some languages by 90 degrees.


Default

lr-tb


For a positioned element, this specifies the stacking order relative to other elements within the same parent container. See Online Section VI for details on relationships of element layering amid multiple containers.


Example

 document.getElementById("myDIV").style.zIndex = "3"; 


Value

Integer. Mozilla prefers that this value be in string form (that's how the property returns its value), while IE returns a number.


Default

0


Governs the magnification of rendered content. Particularly useful for output that might be displayed on monitors with very high pixel density. See screen.logicalXDPI property.


Example

 document.body.style.zoom = "200%"; 


Value

Percentage value (where 100% is normal), floating-point multiplier (where 1.0 is normal), or constant normal.


Default

normal


getPropertyCSSValue(" CSSAttributeName")

Returns an object that represents a CSS value. In the W3C DOM, the CSSValue object returned from this method has properties that reveal the text of the attribute/value pair and a numeric value corresponding to a long list of primitive value types (indicating types such as percentage, pixel lengths, and RGB color).


Returned Value

Reference to a CSSValue object.


Parameters


CSSAttributeName

The CSS attribute name from an inline style declaration (not the DOM version of the property name).


getPropertyPriority(" CSSAttributeName")

Returns the string value of any priority (such as !important) associated with the inline CSS attribute.


Returned Value

String.


Parameters


CSSAttributeName

The CSS attribute name from an inline style declaration (not the DOM version of the property name).


getPropertyValue(" CSSAttributeName")

Returns the string value of the inline CSS attribute/value pair.


Returned Value

String.


Parameters


CSSAttributeName

The CSS attribute name from an inline style declaration (not the DOM version of the property name).


item( index)

Returns the attribute name of the inline CSS attribute/value pair corresponding to the integer index value in source code order. Safari incorrectly returns the CSS value, not the name.


Returned Value

String. IE for Macintosh returns name in all-uppercase characters, while Mozilla returns all-lowercase characters.


Parameters


index

Zero-based integer corresponding to the specified inline CSS attribute/value pair in source code order.


removeProperty(" CSSAttributeName")

Deletes the inline CSS attribute/value pair and returns a string with the previous value.


Returned Value

String.


Parameters


CSSAttributeName

The CSS attribute name from an inline style declaration (not the DOM version of the property name).


setProperty(" CSSAttributeName", " value", " priority")

Sets an inline style attribute/value pair. If the attribute already exists, the new value is applied to the existing attribute; otherwise, the attribute and value are added to the element.


Returned Value

None.


Parameters


CSSAttributeName

The CSS attribute name from an inline style declaration (not the DOM version of the property name).


value

String of the value in the format applicable to the attribute.


priority

String of the priority assignment (such as !important) or empty string.


The styleSheet object (CSSStyleSheet object in the W3C DOM abstract model, which inherits the DOM StyleSheet object) represents a style sheet that may have been created as a style element or imported with a link element or @import statement inside a style element. This object is different from the style element object, which strictly reflects the style HTML element and its attributes. The document.styleSheets[] collection contains zero or more styleSheet objects. The shared disabled property is available in all supporting browsers, facilitating the enabling and disabling of entire style sheets with simple Boolean assignments.


Object Model Reference

 [window.]document.styleSheets[i] 


Object-Specific Properties

cssRules[]
cssText
href
imports[]
media
ownerNode
ownerRule
owningElement
pages[]
parentStyleSheet
readOnly
rules[]
title
type

Object-Specific Methods

addImport( )
addRule( )
deleteRule( )
insertRule( )
removeRule( )

Object-Specific Events

None.


Returns a collection of cssRule objects nested within the current styleSheet object. The IE equivalent is the rules property. See the cssRules object earlier in this chapter for a description of this collection object's property and methods; see the cssRule object earlier in this chapter for a description of the individual members of this collection.


Example

 var allCSSRules = document.styleSheets[0].cssRules; 


Value

Reference to a CSSRules collection object.


Default

Array of zero length.


Contains the entire text (as a string) of all rules defined in the style sheet. This is useful primarily if you wish to replace the entire set of rules with a new set. To act on the text of an individual rule in IE, access the cssText property of a single rule object (obtained by the styleSheet object's rules[i].cssText property); or, in W3C DOM browsers, you can use the cssRules[i].cssText property.


Example

 var allCSSText = document.styleSheets[0].cssText; 


Value

String.


Default

Empty string.


This is the URL specified by a link element's href attribute (when the link is used to import a style sheet). This value is read/write in IE for Windows, but read-only in W3C DOM browsers.


Example

 document.styleSheets[1].href = "css/altStyles.css"; 


Value

String of complete or relative URL.


Default

None.


Returns a collection (array) of styleSheet objects imported into an explicit styleSheet object via the @import rule. See the imports collection object earlier in this chapter for further discussion. For W3C DOM browsers, you must loop through all cssRule objects of a styleSheet object in search of those with type property values equal to 3 (the same as the cssRule object's IMPORT_RULE constant).


Example

 var allImportRules = document.styleSheets[0].imports; 


Value

Reference to an imports collection object.


Default

Array of zero length.


Specifies the intended output device for the content governed by the style sheet (reflecting the media attribute of the link and style elements). IE uses a string for this value, while W3C DOM browsers use a read-only MediaList object (which has properties and methods of its own).


Example

 var theMedia = document.styleSheets[2].media; theMedia = (typeof theMedia.mediaText != "undefined") ? theMedia.mediaText : theMedia; if (theMedia.match(/print/) {     // process for print output } 


Value

For IE, any one of the following constant values as a string: all | print | screen; for W3C DOM browsers a MediaList object.


Default

all


Returns a reference to the document tree node that contains the styleSheet object. This node is either a style or link element, depending on the way the style sheet is defined in the document. The IE (Windows and Mac) equivalent property is owningElement.


Example

 var mama = document.styleSheets[2].ownerNode; 


Value

Object reference.


Default

None.


For a styleSheet object brought into the document via an @import rule, returns a reference to that @import rule object (a W3C DOM CSSImportRule object). The cssRule object earlier in this chapter provides the properties and methods that apply to a CSSImportRule object. For other style sheet types, the property returns null.


Example

 var hostRule = document.styleSheets[2].ownerRule; 


Value

Object reference or null.


Default

null


Returns a reference to the style or link element object that defines the current styleSheet object. Each document maintains a collection of style sheets created with both the style and link elements. The comparable W3C DOM property is ownerNode.


Example

 var firstStyleID = document.styleSheets[0].owningElement.id; 


Value

Element object reference.


Default

None.


Returns a collection (array) of page objects (@page rules) nested within a styleSheet object. For W3C DOM browsers, you must loop through all cssRule objects of a styleSheet object in search of those with type property values equal to 6 (the same as the cssRule object's PAGE_RULE constant). See the page object.


Example

 var allPageRules = document.styleSheets[0].pages; 


Value

Reference to a pages collection object.


Default

Array of zero length.


For a styleSheet object generated by virtue of inclusion with an @page rule, the parentStyleSheet property returns a reference to the styleSheet (created as a link or style element) object that imported the current style sheet. For a nonimported style sheet, the property returns null.


Example

 var myMaker = document.styleSheets[0].parentStyleSheet; 


Value

Reference to a styleSheet object.


Default

null


Specifies whether the style sheet can be modified under script control. Style sheets imported through a link element or an @import rule cannot be modified, so they return a value of true.


Value

Boolean value: true | false.


Default

false


Returns a collection of rule objects nested within the current styleSheet object. The W3C DOM equivalent is the cssRules property (Safari supports both properties). See the cssRules object earlier in this chapter for a description of this collection object's property and methods; see the cssRule object earlier in this chapter for a description of the individual members of this collection.


Example

 var allrules = document.styleSheets[0].rules; 


Value

Reference to a rules collection object.


Default

Array of zero length.


Exposes the title attribute of the style or link element that owns the current styleSheet object. Since the attribute does not affect user interface elements (the elements are unrendered, and thus don't show tool tips), it is available to convey other string information to the styleSheet object under script control.


Example

 if (document.styleSheets[2].title == "corpStyleWindows") {     // process for the designated style } 


Value

String value.


Default

Empty string.


Returns the style sheet MIME type specified by the type attribute of the style or link element.


Example

 if (document.styleSheets[0].type == "text/css") {     ... } 


Value

String (text/css for typical CSS style sheets).


Default

None.


addImport( url, [ index])

Adds an external style sheet specification to a styleSheet object.


Returned Value

Integer of the index position within the styleSheets[] collection where the style sheet was added (in case you omit the second parameter and let the browser find the endposition).


Parameters


url

A complete or relative URL to the style sheet (.css) file.


index

An optional integer indicating where in the collection the new element should be placed.


addRule(" selector", " style"[, index])

Adds a new rule for a style sheet. This method offers a scripted way of adding a rule to an existing styleSheet object:

 document.styleSheets[1].addRule("p b","color:red"); 

You may duplicate a selector that already exists in the styleSheet and, therefore, override an existing rule for the same element selector. The only prohibition is that you may not override a rule to convert a plain style rule into one that creates a positionable element (or vice versa). The new rule is governed by the same cascading rules as all style sheet rules (that includes the rule's source code position among other rules with the same selector). Therefore, a new rule in a styleSheet object does not supersede a style set in an element's style property.


Returned Value

Early versions of IE returned no value. More recently, IE for Windows returns -1, while IE for Macintosh returns null. In the future, the returned value may become the integer of the index location of the new rule.


Parameters


selector

The style rule selector as a string.


style

One or more style attribute:value pairs. Multiple pairs are semicolon delimited, just as they are in the regular style sheet definition.


index

An optional integer indicating where in the collection the new element should be placed.


deleteRule( index)

Removes a rule from the styleSheet object. The integer index parameter value points to the zero-based item in the cssRules array to delete. Note that IE 5 for Macintosh implements both the Microsoft removeRule( ) and W3C DOM deleteRule( ) method for the same operation.


Returned Value

None.


Parameters


index

A zero-based integer indicating which rule in the cssRules collection is to be deleted.


insertRule(" ruleText", index)

Adds a new rule for a style sheet. This method offers a scripted way of adding a rule to an existing W3C DOM styleSheet object:

 document.styleSheets[1].insertRule("p b {color:red}", 0); 

You may duplicate a selector that already exists in the styleSheet and, therefore, override an existing rule for the same element selector. The only prohibition is that you may not override a rule to convert a plain style rule into one that creates a positionable element (or vice versa). The new rule is governed by the same cascading rules as all style sheet rules (that includes the rule's source code position among other rules with the same selector). Therefore, a new rule in a styleSheet object does not supersede a style set in an element's style property. Note that IE 5 for the Macintosh implements both the W3C DOM insertRule( ) and Microsoft addRule( ) methods to accomplish the same result.


Returned Value

Integer of the index location of the new rule.


Parameters


ruleText

The entire style rule selector as a string in exactly the same format as assigned in a style element: selector {attribute:value; attribute:value;...}.


index

Zero-based integer indicating where in the cssRules collection the new rule should be placed.


removeRule( index)

Removes a rule from the styleSheet object. The integer index parameter value points to the zero-based item in the rules array to delete.


Returned Value

None.


Parameters


index

A zero-based integer indicating which rule in the rules collection is to be deleted.


A collection of styleSheet objects that are members of a document object. The W3C DOM abstract representation of this collection is called a StyleSheetList object. Members of this collection are accessed via their integer index number, but you may iterate through the collection and examine properties of each style sheet object (such as the selectorText property) to distinguish one rule from another.


Object Model Reference

 document.styleSheets 


Object-Specific Properties

length


Object-Specific Methods

item( )


Object-Specific Events

None.


Returns the number of elements in the collection.


Example

 var howMany = document.styleSheets.length; 


Value

Integer.


item( index)

Returns a styleSheet object corresponding to the object matching the index value in source code order.


Returned Value

Reference to a styleSheet object. If there are no matches to the parameters, the returned value is null.


Parameters


index

A zero-based integer corresponding to the specified item in source code order (nested within the current document object).


The sub object reflects the sub element; the sup object reflects the sup element. Browsers tend to render these objects' content in a smaller size than surrounding content. IE 5 for Macintosh provides object-specific, read-only height and width properties for these elements, but no other object model does.


HTML Equivalent

 <sub> <sup> 


Object Model Reference

 [window.]document.getElementById("elementID") 


Object-Specific Properties

None.


Object-Specific Methods

None.


Object-Specific Events

None.


See input.


See sub.


The table object reflects the table element. Other objects related to the table object are: caption, col, colgroup, tbody, TD, tfoot, thead, and TR.


HTML Equivalent

<table>


Object Model Reference

 [window.]document.getElementById("elementID") 


Object-Specific Properties

align
background
bgColor
border
borderColor
borderColorDark
borderColorLight
caption
cellPadding
cells[]
cellSpacing
cols
dataPageSize
frame
height
rows[]
rules
summary
tbodies[]
tFoot
tHead
width

Object-Specific Methods

createCaption( )
createTFoot( )
createTHead( )
deleteCaption( )
deleteRow( )
deleteTFoot( )
deleteTHead( )
insertRow( )
lastPage( )
moveRow( )
nextPage( )
previousPage( )
refresh( )

Object-Specific Events

None.


Defines the horizontal alignment of the element within its surrounding container.


Example

 document.getElementById("myTable").align = "center"; 


Value

Any of the three horizontal alignment constants: center | left | right.


Default

left


Provides the URL of the background image for the table. If you set a backgroundColor to the element as well, the color appears if the image fails to load; otherwise, the image overlays the color.


Example

 document.getElementById("myTable").background = "images/watermark.jpg"; 


Value

Complete or relative URL to the background image file.


Default

None.


Specifies the background color of the element. This color setting is not reflected in the style sheet backgroundColor property. Even if the bgcolor attribute or bgColor property is set with a plain-language color name, the returned value is always a hexadecimal triplet.


Example

 document.getElementById("myTable").bgColor = "yellow"; 


Value

A hexadecimal triplet or plain-language color name. See Appendix A for acceptable plain-language color names.


Default

Varies with browser and operating system.


Specifies the thickness of the border around the table (in pixels). This is the default 3D-look border and should not be confused with borders created with style sheets.


Example

 document.getElementById("myTable").border = 4; 


Value

An integer value. A setting of zero removes the border entirely.


Default

0


Specifies the color of the table's border. Internet Explorer applies the color to all four lines that make up the interior border of a cell. Therefore, colors of adjacent cells do not collide.


Example

 document.getElementById("myTable").borderColor = "salmon"; 


Value

A hexadecimal triplet or plain-language color name. A setting of empty is interpreted as "#000000" (black). See Appendix A for acceptable plain-language color names.


Default

Varies with operating system.


The 3D effect of table borders in Internet Explorer is created by careful positioning of light and dark lines around the page's background or default color. You can independently control the colors used for the dark and light lines by assigning values to the borderColorDark (left and top edges of the cell) and borderColorLight (right and bottom edges) properties.

Typically, you should assign complementary colors to the pair of properties. There is also no rule that says you must assign a dark color to borderColorDark. The attributes merely control a well-defined set of lines so you can predict which lines of the border change with each attribute.


Example

 document.getElementById("myTable").borderColorDark = "blue"; document.getElementById("myTable").borderColorLight = "cornflowerblue"; 


Value

A hexadecimal triplet or plain-language color name. A setting of empty is interpreted as "#000000" (black). See Appendix A for acceptable plain-language color names.


Default

Varies with operating system.


Returns a reference to a caption element nested inside the table. From this reference you can access properties and methods of the caption object. In W3C DOM browsers, you can create a new caption element, and assign that new element's reference to the caption property of a table, making the property read/write in that browser (although you really should be using the createCaption( ) method). For all browsers, however, you can modify properties of the caption object returned by the caption property.


Example

 var capText = document.getElementById("myTable").caption.innerHTML; 


Value

Object reference.


Default

None.


Specifies the amount of empty space between the (visible or invisible) border of a table cell and the content of the cell. Note that this property applies to space inside a cell. Minor adjustments to this property are not as noticeable when the table does not also display borders (in which case the cellSpacing property can assist in adjusting the space between cells).


Example

 document.getElementById("myTable").cellPadding = "15"; 


Value

A string value for a length in pixels or percentage.


Default

0


Returns a collection of all td elements inside the table. Entries in the array are in source code order of td elements. This property is more widely available for a tr element (one row at a time).


Example

 var totCells = document.getElementById("myTable").cells.length; 


Value

Reference to a cells collection object.


Default

Array of zero length.


Specifies the amount of empty space between the outer edges of each table cell. If the table has a border, the effect of setting cellSpacing is to define the thickness of borders rendered between cells. Even without a visible border, the readability of a table often benefits from cell spacing, or a combination of cell spacing and cell padding.


Example

 document.getElementById("myTable").cellSpacing = "5"; 


Value

A string value for a length in pixels or percentage.


Default

0 (with no table border); 2 (with table border).


Specifies the number of columns of the table. The corresponding IE-specific cols attribute assists the browser in preparation for rendering the table. Without this attribute, the browser relies on its interpretation of all downloaded tr and TD elements to determine how the table is to be divided. You cannot change the column makeup of a table from this property, despite its read/write status. See also the col object earlier in this chapter.


Example

 document.getElementById("myTable").cols = 5; 


Value

Integer.


Default

None.


Used with IE data binding, this property advises the browser how many instances of a table row must be rendered to accommodate the number of data source records set by this attribute. See lastPage( ), nextPage( ), and previousPage( ) methods for navigating through groups of records.


Example

 document.getElementById("inventoryTable").dataPageSize = 10; 


Value

Integer.


Default

None.


Indicates which (if any) sides of a table's outer border (set with the border attribute or border property) are rendered. This property does not affect the interior borders between cells.


Example

 document.getElementById("orderForm").frame = "hsides"; 


Value

Any one case-insensitive frame constant (as a string):


above

Renders border along top edge of table only


below

Renders border along bottom edge of table only


border

Renders all four sides of the border (same as box)


box

Renders all four sides of the border (same as border)


hsides

Renders borders on top and bottom edges of table only (a nice look)


lhs

Renders border on left edge of table only


rhs

Renders border on right edge of table only


void

Hides all borders (default in HTML 4)


vsides

Renders borders on left and right edges of table only


Default

void (when border=0); border (when border is any other value)


Specify the height and width in pixels of the element. Changes to these values are immediately reflected in reflowed content on the page. Only the width property is available in W3C DOM browsers, as the table's height is considered to be the sum of the highest cell in each row.


Example

 document.getElementById("myTable").height = 250; 


Value

Integer.


Default

None.


Returns a collection of tr elements inside the entire table. You can also get a group of rows for each table section (tbody, tfoot, and thead element objects).


Example

 var allTableRows = document.getElementById("myTable").rows; 


Value

Reference to a rows collection object.


Default

Array of zero length.


Indicates where (if at all) interior borders between cells are rendered by the browser. In addition to setting the table to draw borders to turn the cells into a matrix, you can set borders to be drawn only to separate borders, columns, or any sanctioned cell grouping (thead, tbody, tfoot, colgroup, or col). The border attribute must be presenteither as a Boolean or set to a specific border sizefor any cell borders to be drawn. Do not confuse this property with the rules[] collection of styleSheet objects. Scripted changes to this property do not always yield the desired results, especially in early versions of Netscape 6.


Example

 document.getElementById("myTable").rules = "groups"; 


Value

Any one case-insensitive rule constants (as a string):


all

Renders borders around each cell


cols

Renders borders between columns only


groups

Renders borders between cell groups as defined by thead, tfoot, tbody, colgroup, or col elements


none

Hides all interior borders


rows

Renders borders between rows only


Default

none (when border=0); all (when border is any other value).


Reflects the HTML 4 summary attribute, which provides no particular functionality in mainstream browsers. But you can assign a value to it in the source code to convey data to a script that reads the property.


Example

 var data = document.getElementById("myTable").summary; 


Value

String.


Default

Empty string.


Returns a collection of tBody element objects in the current table. Every table element has at least one (explicit or implied) tBody element object nested inside.


Example

 var bodSections = document.getElementById("myTable").tBodies; 


Value

Reference to a collection of tBody objects.


Default

Array of length one.


Returns a reference to the tfoot element object if one has been defined for the table. If no tfoot element exists, the value is null. You can access tfoot element object properties and methods through this reference if you like.


Example

 var tableFootTxt = document.getElementById("myTable").tFoot.firstChild.nodeValue; 


Value

tfoot element object reference.


Default

null


Returns a reference to the thead element object if one has been defined for the table. If no thead element exists, the value is null. You can access thead element object properties and methods through this reference if you like.


Example

 var tableHeadTxt = document.getElementById("myTable").tHead.firstChild.nodevalue; 


Value

thead element object reference.


Default

null


See height.


Add or remove a caption element nested within the current table element. If no caption exists, the creation method produces an empty element, which your scripts must then populate with caption text (through common element content modification techniques). If a caption exists, the method is essentially ignored, and returns a reference to the existing caption element.


Returned Value

Reference to new caption element (for createCaption( )); nothing for deleteCaption( ).


Parameters

None.


Add or remove a thead or tfoot element nested within the current table element. If no head or foot table section exists, the creation method produces an empty element, which your scripts must then populate with rows (through thead.insertRow( ) and tfoot.insertRow( ) methods). If the desired table section exists, the method is essentially ignored, and returns a reference to the existing thead or tfoot element.


Returned Value

Reference to newly created element (for createTFoot( ) and createTHead( )); nothing for deleteTHead( ) and deleteTFoot( ).


Parameters

None.


deleteRow( index)

Removes a TR element nested within the current table element. The integer parameter points to the zero-based item in the rows collection. To repopulate a table with new or sorted content, empty the table (or just a table section) with iterative calls to the deleteRow( ) method:

 while (tableReference.rows.length > 0) {     tableReference.deleteRow(0); } 


Returned Value

None.


Parameters


index

Zero-based integer corresponding to the said numbered tr element in source code order (nested within the current element).


insertRow( index)

Inserts a tr element nested within the current table element. The integer parameter points to the zero-based index in the rows collection where the new row should go, but in IE you can also use the shortcut value of -1 to append the row to the end of the collection. Adding the row inserts an empty element, to which you add cells via the insertCell( ) method. Unfortunately, scripting the addition of table rows and cells in IE for the Macintosh (including Version 5.1) is very broken, yielding elephantine row and cell dimensions. For nonnested tables, you might be able to get away with regular document tree node creation and insertion instead of the table (and related) object convenience methods.


Returned Value

Reference to the newly inserted row.


Parameters


index

Zero-based integer corresponding to a row of the rows collection before which the new row is to be inserted.


Advises the data binding facilities to load the last, next, or previous group of records from the data source to fill the number of records established with the dataPageSize property. The lastPage( ) method is available in IE 5 or later.


Returned Value

None.


Parameters

None.


moveRow( indexToMove, destinationIndex)

Moves a row in the table from its original location to a different row position. The first parameter is a zero-based index of the row (within the rows collection) you wish to move. The second parameter is the index of the row before which you want to move the row. As a method of the table object, moveRow( )'s index parameters include the first row, which may contain th elements you don't want to move. Invoke the method on the tbody object if you want counting to be just within a table section.


Returned Value

Reference to the moved row.


Parameters


indexToMove

A zero-based integer pointing to the row to move.


destinationIndex

A zero-based integer pointing to the row above which the row is to be moved.


Advises the data binding facilities to reload the current page of data from the data source. If your table is retrieving frequently changing data from a database, you can create a setTimeout( ) loop to invoke document.getElementById("myTable").refresh( ) as often as users would want updated information from the database.


Returned Value

None.


Parameters

None.


The tags object is used by JavaScript syntax for style sheets in Navigator 4 only. As a property of the document object, this tags object is used in building references to particular HTML elements to get or set their style-related properties. The direct properties of the tags object are all HTML element types. For example:

 [document.]tags.p [document.]tags.h1 

There is no need to repeat a list of all HTML elements as properties for this object. These references are usable inside style elements with a type set to text/javascript. That's where you assign values to style sheet properties with JavaScript syntax, as in the following examples:

 tags.p.color = "green"; tags.h1.fontSize = "14pt"; 

The properties in the following list are not properties of the tags object per se, but rather of the style sheet associated with an element, class, or ID singled out by a JavaScript syntax assignment statement. The properties are listed here for convenience (and historical completeness). Properties dedicated to element positioning are listed separately from regular style properties. For information about these property values, consult the CSS reference chapter, where you can find details of all style sheet properties listed by CSS syntax.


Style Object-Specific Properties

backgroundColor
backgroundImage
borderBottomWidth
borderColor
borderLeftWidth
borderRightWidth
borderStyle
borderTopWidth
borderWidths( )
color
display
fontFamily
fontSize
fontStyle
fontWeight
listStyleType
marginBottom
marginLeft
marginRight
margins( )
marginTop
paddingBottom
paddingLeft
paddingRight
paddings
paddingTop
textAlign
textdecoration
textTRansform
verticalAlign
whiteSpace

Position Object-Specific Properties

background
bgColor
clip
left
top
visibility
zIndex

This is a collection of all tbody elements contained within a single table element. Collection members are sorted in source code order.


Object Model Reference

 document.getElementById("tableID").tBodies 


Object-Specific Properties

length

Object-Specific Methods

item( )
namedItem( )
tags( )
urns( )

Object-Specific Events

None.


Returns the number of elements in the collection.


Example

 var howMany = document.getElementById("myTable").tBodies.length; 


Value

Integer.


item( index[, subindex]) item( index)

Returns a single tBody object or collection of tBody objects corresponding to the element matching the index value (or, optionally in IE, the index and subindex values).


Returned Value

One tBody object or collection (array) of tBody objects. If there are no matches to the parameters, the returned value is null.


Parameters


index

When the parameter is a zero-based integer, the returned value is a single element corresponding to the specified item in source code order (nested within the current element); when the parameter is a string (IE only), the returned value is a collection of elements with id properties that match that string.


subindex

In IE only, if you specify a string value for the first parameter, you can use the second parameter to specify a zero-based index that retrieves the specified element from the collection with id properties that match the first parameter's string value.


namedItem(" ID")

Returns a single tBody object or collection of tBody objects corresponding to the element matching the parameter string value.


Returned Value

One tBody object or collection (array) of tBody objects. If there are no matches to the parameters, the returned value is null.


Parameters


ID

The string that contains the same value as the desired element's id attribute.


tags(" tagName")

Returns a collection of objects (among all objects nested within the current collection) whose tags match the tagName parameter.


urns( URN)

See the all.urns( ) method.


The tbody, tfoot, and thead objects reflect the tbody, tfoot, and thead elements, respectively. For scripting purposes, you can treat each of these as a container of row groups inside a table. They all share the same properties and methods, so you need to keep their HTML functionality straight as you script these elements. A table can have only one tfoot and one thead element, but multiple tbody elements. Also, by default, Internet Explorer 4 or later and W3C DOM browsers create a tbody object for every table even if you don't include one in your table's source code. This default tbody element encompasses all rows of the table (except those you have wrapped inside thead or tfoot elements, if any).


HTML Equivalent

 <tbody> <tfoot> <thead> 


Object Model Reference

 [window.]document.getElementById("elementID") [window.]document.getElementById("tableID").tBodies[i] [window.]document.getElementById("tableID").tfoot [window.]document.getElementById("tableID").thead 


Object-Specific Properties

align
bgColor
ch
chOff
rows
vAlign

Object-Specific Methods

deleteRow( )
insertRow( )
moveRow( )

Object-Specific Events

None.


Defines the horizontal alignment of content within all cells contained by the tbody element.


Example

 document.getElementById("myTbody").align = "center"; 


Value

One of the three horizontal alignment string constants: center | left | right.


Default

left


Specifies the background color of the cells contained by the tbody, tfoot, or thead element. This color setting is not reflected in the style sheet backgroundColor property. Even if the bgcolor attribute or bgColor property is set with a plain-language color name, the returned value is always a hexadecimal triplet.


Example

 document.getElementById("myTable").tHead.bgColor = "yellow"; 


Value

A hexadecimal triplet or plain-language color name. See Appendix A for acceptable plain-language color names.


Default

Varies with browser and operating system.


Defines the text character used as an alignment point for text within a column or column group (reflecting the char attribute). This property is normally of value only for the align attribute set to "char". In practice, even though the table section element object has this property, the browser does not respond to values assigned to it.


Example

 document.getElementById("myTBody").ch = "."; 


Value

Single character string.


Default

None.


Defines the offset point at which the character specified by the char attribute is to appear within a cell. In practice, even though the table section element object has this property, the browser does not respond to values assigned to it.


Example

 document.getElementById("myTBody").chOff = "80%"; 


Value

String value of the number of pixels or percentage (within the cell).


Default

None.


Returns a collection of tr elements inside the table section. You can also get a group of rows for an entire table in IE for Windows.


Example

 var allTableRows = document.getElementById("myTFoot").rows; 


Value

Reference to a rows collection object.


Default

Array of zero length.


Specifies the manner of vertical alignment of text within the cells contained by the tbody, tfoot, or thead element.


Example

 document.getElementById("myTbody").vAlign = "baseline"; 


Value

Case-insensitive constant (as a string): baseline | bottom | middle | top.


Default

middle


deleteRow( index)

Removes a tr element nested within the current tbody, tfoot, or thead element. The integer parameter points to the zero-based item in the section's rows collection. To repopulate a table section with new or sorted content, empty the section with iterative calls to the deleteRow( ) method:

 while (tBodyReference.rows.length > 0) {     tBodyReference.deleteRow(0); } 


Returned Value

None.


Parameters


index

Zero-based integer corresponding to the said numbered TR element in source code order (nested within the current element).


insertRow( index)

Inserts a TR element nested within the current tbody, tfoot, or thead element. The integer parameter points to the zero-based index in the rows collection where the new row should go, but in IE you can also use the shortcut value of -1 to append the row to the end of the collection. Adding the row inserts an empty element, to which you add cells via the insertCell( ) method. Unfortunately, scripting the addition of table rows and cells in IE for the Macintosh (including Version 5.1) is very broken, yielding elephantine row and cell dimensions. For nonnested tables, you might be able to get away with regular document tree node creation and insertion instead of the table section object convenience methods.


Returned Value

Reference to the newly inserted row.


Parameters


index

Zero-based integer corresponding to a row of the rows collection before which the new row is to be inserted.


moveRow( indexToMove, destinationIndex)

Moves a row in the tbody, tfoot, or thead element from its original location to a different row position within the same section. The first parameter is a zero-based index of the row (within the rows collection) you wish to move. The second parameter is the index of the row before which you want to move the row.


Returned Value

Reference to the moved row.


Parameters


indexToMove

A zero-based integer pointing to the row to move.


destinationIndex

A zero-based integer pointing to the row above which the row is to be moved.


The td and th objects reflect the TD and th elements. From an HTML structure viewpoint, the two elements have different purposes within a table; but from a scripting perspective, the elements share the same properties and methods. A cell is a cell.

While a table cell element may inherit a number of visual properties from containers (e.g., a td element appearing to pick up the bgColor of a tbody or tr element), those inherited property values are not automatically assigned to the TD object. Therefore, just because a cell may have a yellow background color doesn't mean its bgColor property is set at all.


HTML Equivalent

 <td> <th> 


Object Model Reference

 [window.]document.getElementById("elementID") [window.]document.getElementById("tableRowID").cells[i] 


Object-Specific Properties

abbr
align
axis
background
bgColor
borderColor
borderColorDark
borderColorLight
cellIndex
ch
chOff
colSpan
headers
height
noWrap
rowSpan
scope
vAlign
width

Object-Specific Methods

None.


Object-Specific Events

None.


Reflects the abbr attribute (cell description for speech), for which mainstream browsers have no functionality at this time.


Value

String.


Default

Empty string.


Defines the horizontal alignment of content within the cell.


Example

 document.getElementById("myTD").align = "center"; 


Value

Any of the three horizontal alignment constants: center | left | right.


Default

left


Reflects the axis attribute (cell category description for speech), for which mainstream browsers have no functionality at this time.


Value

String.


Default

Empty string.


Specifies the URL of the background image for the cell. If you set a bgColor to the element as well, the color appears if the image fails to load; otherwise, the image overlays the color.


Example

 document.getElementById("myTD").background = "images/watermark.jpg"; 


Value

Complete or relative URL to the background image file.


Default

None.


Provides the background color of the table cell. This color setting is not reflected in the style sheet backgroundColor property. Even if the bgcolor attribute or bgColor property is set with a plain-language color name, the returned value is always a hexadecimal triplet.


Example

 document.getElementById("myTD").bgColor = "yellow"; 


Value

A hexadecimal triplet or plain-language color name. See Appendix A for acceptable plain-language color names.


Default

Varies with browser and operating system.


Provides the color of the element's border. Internet Explorer applies the color to all four lines that make up the interior border of a cell. Therefore, colors of adjacent cells do not collide.


Example

 document.getElementById("myTD").borderColor = "salmon"; 


Value

A hexadecimal triplet or plain-language color name. A setting of empty is interpreted as "#000000" (black). See Appendix A for acceptable plain-language color names.


Default

Varies with operating system.


The 3D effect of table borders in Internet Explorer is created by careful positioning of light and dark lines around the page's background or default color. You can independently control the colors used for the dark and light lines by assigning values to the borderColorDark (left and top edges of the cell) and borderColorLight (right and bottom edges) properties.

Typically, you should assign complementary colors to the pair of properties. There is also no rule that says you must assign a dark color to borderColorDark. The attributes merely control a well-defined set of lines so you can predict which lines of the border change with each attribute.


Example

 document.getElementById("myTD").borderColorDark = "blue"; document.getElementById("myTD").borderColorLight = "cornflowerblue"; 


Value

A hexadecimal triplet or plain-language color name. A setting of empty is interpreted as "#000000" (black). See Appendix A for acceptable plain-language color names.


Default

Varies with operating system.


Returns a zero-based integer representing the position of the current cell among all other TD elements in the same row. The count is based on the source code order of the td elements within a tr element.


Example

 var whichCell = document.getElementById("myTD").cellIndex; 


Value

Integer.


Default

None.


Defines the text character used as an alignment point for text within a cell. This property is normally of value only for the align attribute set to "char". In practice, even though the table section element object has this property, the browser does not respond to values assigned to it.


Example

 document.getElementById("myTD").ch = "."; 


Value

Single character string.


Default

None.


Defines the offset point at which the character specified by the char attribute is to appear within a cell. In practice, even though the table section element object has this property, the browser does not respond to values assigned to it.


Example

 document.getElementById("myTD").chOff = "80%"; 


Value

String value of the number of pixels or percentage (within the cell).


Default

None.


Specifies the number of columns across which the current table cell should extend itself. For each additional column included in the colSpan count, one less td element is required for the table row. If you set the align property to center or right, the alignment is calculated on the full width of the td element across the specified number of columns. Unless the current cell also specifies a rowspan attribute, the next table row returns to the original column count.


Example

 document.getElementById("myTD").colSpan = 2; 


Value

Integer, usually 2 or larger.


Default

1


Points to the ID of a table cell element designated as a column header for the current cell. In practice, no mainstream browsers provide functionality for this property.


Value

String ID value.


Default

None.


Specify the height and width of the element. Changes to these values are immediately reflected in reflowed content on the page.


Example

 document.getElementById("myTD").height = "250"; 


Value

Pixel integer count (as a string) or a percentage.


Default

None.


Indicates whether the browser should render the cell as wide as is necessary to display a line of nonbreaking text on one line. Abuse of this attribute can force the user into a great deal of inconvenient horizontal scrolling of the page to view all of the content.


Example

 document.getElementById("myTD").noWrap = "true"; 


Value

Boolean value: true | false.


Default

false


Specifies the number of rows through which the current table cell should extend itself downward. For each additional row included in the rowSpan count, one less TD element is required for the next table row. If you set the vAlign property to middle, the alignment is calculated on the full height of the TD element across the specified number of rows.


Example

 document.getElementById("myTD").rowSpan = 12; 


Value

Integer, usually 2 or larger.


Default

1


Reflects the scope attribute of table cell elements. In practice, no mainstream browsers provide functionality for this property.


Value

One of the recognized string constants: cols | colgroup | rows | rowgroup.


Default

None.


Specifies the manner of vertical alignment of text within the element's content box.


Example

 document.getElementById("myTD").vAlign = "baseline"; 


Value

Case-insensitive constant (as a string): baseline | bottom | middle | top.


Default

middle


See height.


See input.


A Text object is what this book calls in many places a "text node." Microsoft refers to this object as a TextNode object. This object represents the child object containing the characters that go between start and end tags of an element. The Text object exists in the abstract W3C DOM model by virtue of an inheritance chain between it and the fundamental Node object (Node to CharacterData to Text). The Node object ancestry automatically equips the Text object with a long list of properties and methods described among the shared items at the start of this chapter (and itemized in the Node object section in this chapter). Along this inheritance chain, the Text object gains some additional properties and methods (described below) that let us manipulate the node's content within the constructs dictated by the formal W3C DOM model. Because the DOM is scripting language-independent, you find properties and methods that may be more easily or more powerfully manipulated through JavaScript string handling (see Chapter 5). Feel free to use those techniques in a client-side JavaScript environment of the browser.

Scripts refer to the Text node (or IE TextNode object) only through references that locate the node in the document tree (such as the first child of a particular element node) or as returned by the document.createTextNode( ) method.


Object Model Reference

 elementReference.childReference textNodeReference.siblingReference 


Object-Specific Properties

data
length

Object-Specific Methods

appendData( )
deleteData( )
insertData( )
replaceData( )
splitText( )
substringData( )

Object-Specific Events

None.


Contains the string of characters in the text node. The value is the same as the nodeValue property value, and there is no reason to favor one property over the other, except perhaps for plain-language syntactic preferences for reading the code.


Example

 document.getElementById("myP").firstSibling.data = "Some new text."; 


Value

String.


Default

Empty string.


Provides a count of characters in the text node.


Example

 var howMany = document.getElementById("myP").firstSibling.length; 


Value

Integer.


Default

0


appendData(" newText")

Adds characters (passed as a string parameter) to the end of the current text node. The content consists of raw characters, so if you intend to add a sentence to a text node, your scripts are responsible for sentence spacing.


Returned Value

None.


Parameters


newText

String value of text to be appended. A reference that evaluates to a string (such as the data property of another text node in the document) copies the referenced value to the append location.


deleteData( startOffset, count)

Removes characters from the current text node starting with the character in (zero-based) position signified by startOffset, and for a length of count characters in the normal text direction of the current language. If the length specified for deletion goes beyond the length of the data, all characters to the end of the text node are deleted without throwing an exception. Early Mozilla versions include source code whitespace in its counts for both parameters.


Returned Value

None.


Parameters


startOffset

Positive integer specifying the zero-based starting character point for the deletion.


count

Positive integer specifying the number of characters to be deleted.


insertData( startOffset, " newText")

Inserts text into a zero-based character position in the text node.


Returned Value

None.


Parameters


startOffset

Positive integer specifying the zero-based character before which the new text is to be inserted.


newText

String value of text to be inserted. A reference that evaluates to a string (such as the data property of another text node in the document) copies the referenced value to the append location.


replaceData( startOffset, count, " newText")

Replaces text in the current text node with new text. The original content to be removed is signified by the zero-based start position and the number of characters. The string passed as a third parameter goes into the space vacated by the removed text. A bug in IE 5 for Macintosh crops the new text to the length of the removed text.


Returned Value

None.


Parameters


startOffset

Positive integer specifying the zero-based starting character point for the deletion.


count

Positive integer specifying the number of characters to be deleted.


newText

String value of text to be inserted where the remaining text collapses. A reference that evaluates to a string (such as the data property of another text node in the document) copies the referenced value to the append location.


splitText( offset)

Divides the current text node into two sibling text nodes; otherwise, doesn't disturb the text.


Returned Value

Reference to the second text node.


Parameters


offset

Positive integer specifying the zero-based character point before which the split occurs.


substringData( startOffset, count)

Returns a copy of the designated segment of the text node content. The section to be copied is signified by the zero-based start position and the number of characters


Returned Value

String.


Parameters


startOffset

Positive integer specifying the zero-based starting character point for the copy action.


count

Positive integer specifying the number of characters to be copied.


The textarea object reflects the textarea element and is used as a form control. This object is the primary way of getting a user to enter multiple lines of text for submission to the server. Note that the innerHTML property is not available on the Macintosh version of Internet Explorer 4. Only a limited number of properties and methods shown below are available in early browsers that do not support addressing all HTML elements (prior to IE 4 and Netscape 6). IE 5 and later support the shared doScroll( ) method for this object.


HTML Equivalent

<textarea>


Object Model Reference

 [window.]document.formName.elementName [window.]document.forms[i].elements[j] [window.]document.getElementById("elementID") 


Object-Specific Properties

accept
autofocus
cols
dataFld
dataSrc
defaultValue
form
forms[]
inputmode
labels[]
maxlength
name
pattern
readOnly
required
rows
selectionEnd
selectionStart
status
textLength
type
validationMessage
validity
value
willValidate
wrap

Object-Specific Methods

checkValidity( )
createTextRange( )
dispatchChange( )
dispatchFormChange( )
handleEvent( )
select( )
setCustomValidity( )

Object-Specific Events

Event

IE

Mozilla

Safari

Opera

W3C DOM

change

·

·

·

·

scroll

·

select

·

·

·

·



A Web Forms 2.0 extension, the accept attribute specifies one or more MIME types for allowable content to be entered into the element. If the browser provides alternate input editors for content other than straight text, this attribute prepares the element for the content and encodes it correctly for submission with the form.


Example

 document.forms[0].comments.accept = "message/news"; 


Value

MIME type string.


Default

Varies with browser and operating system.


Web Forms 2.0 extension that brings focus to the element after the page loads. Should be assigned to only one form control element per page.


Value

Boolean value: true | false.


Default

false


Specifies the width of the editable space of the textarea element. The value represents the number of monofont characters that are to be displayed within the width. When the font size can be influenced by style sheets, the actual width changes accordingly.


Example

 document.forms[0].comments.cols = 60; 


Value

Integer.


Default

20 (IE/Windows); -1 (Mozilla, meaning that the attribute or property hasn't been set); 0 (Safari, Windows).


Used with IE data binding to associate a remote data source column name to a textarea object's value property. A datasrc attribute must also be set for the element. Setting both the dataFld and dataSrc properties to empty strings breaks the binding between element and data source. Works only with text file data sources in IE 5/Mac.


Example

 document.myForm.myTextArea.dataFld = "description"; 


Value

Case-sensitive identifier of the data source column.


Default

None.


Used with IE data binding to specify the ID of the page's object element that loads the data source object for remote data access. Content from the data source is specified via the datafld attribute. Setting both the dataFld and dataSrc properties to empty strings breaks the binding between element and data source. Works only with text file data sources in IE 5/Mac.


Example

 document.myForm.myTextArea.dataSrc = "DBSRC3"; 


Value

Case-sensitive identifier of the data source.


Default

None.


Specifies the default text for the textarea element, as established by the text between the start and end tags in the page's source code.


Example

 var txtAObj = document.forms[0].myTextArea; if (txtAObj.value != txtAObj.defaultValue ) {     ... } 


Value

Any string value.


Default

None.


Returns a reference to the form element that contains the current element. When processing an event from this element, the event handler function automatically has access to the select element (as the event object's target or srcElement property). By reading the form property, the script can easily access other controls within the same form.


Example

 var theForm = evt.srcElement.form; 


Value

form element object reference.


Default

None.


Web Forms 2.0 extension that returns an array (NodeList) of references to form objects with which the current textarea element is associated.


Example

 var formList = document.getElementById("myTextarea").forms; 


Value

Array.


Default

One-item array with a reference to any enclosing form element.


Web Forms 2.0 extension (adopted whole from the W3C XForms 1.0 specification at http://www.w3.org/TR/xforms/sliceE.html) that directs the browser to display the appropriate text input user interface for a written language. Consult the W3C XForms 1.0 documents for details.


Example

 document.orderForm.searchText.inputmode = "hiragana"; 


Value

Written language script token with an optional modifier token (space-delimited). Tokens generally correspond to Unicode scripts (http://www.unicode.org/unicode/reports/tr24/).


Default

None.


Web Forms 2.0 extension that returns an array (HTMLCollection) of references to label element objects associated with the current form control element.


Example

 var textboxLabels = document.getElementById("myTextarea").labels; 


Value

Array of label element object references.


Default

Empty array.


Web Forms 2.0 extension that defines the maximum number of characters that may be typed into a textarea element. In practice, browsers beep or otherwise alert users when a typed character would exceed the maxlength value. There is no innate correlation between the maxlength and size attributes. If the maxlength allows for more characters than fit within the specified width of the element, the browser provides horizontal scrolling (albeit awkward for many users) to allow entry and editing of the field.


Example

 document.getElementById("query").maxlength=10; 


Value

Positive integer.


Default

Unlimited.


This is the identifier associated with the form control. The value of this property is submitted as one-half of the name/value pair when the form is submitted to the server. Names are hidden from user view, since control labels are assigned via other means, depending on the control type. Form control names may also be used by script references to the objects. Despite the modern standards' preference for the id attribute, many browsers still require that a control be assigned a name attribute to allow the control's value to be submitted.


Example

 document.orderForm.myTextArea.name = "customerComment"; 


Value

Case-sensitive identifier that follows the rules of identifier naming: it may contain no whitespace, cannot begin with a numeral, and should avoid punctuation except for the underscore character.


Default

None.


Web Forms 2.0 extension that lets you specify a regular expression pattern that the user's input must match to pass validation.


Example

 document.getElementById("partNum").pattern = "[A-Z][0-9]{7}" 


Value

A regular expression (but not surrounded by the slash symbols, as used in JavaScript regular expressions).


Default

None.


Indicates whether the form element can be edited on the page by the user. A form control that has its readOnly property set to TRue may still be modified by scripts, even though the user may not alter the content.


Example

 document.forms[0].myTextArea.readOnly = "true"; 


Value

Boolean value: TRue | false.


Default

false


Web Forms 2.0 extension that signifies whether the textarea element's value is required for submission. Sets the missingValue property of the ValidityState object to true if the element receives no value.


Value

Boolean value: true | false.


Default

false


Specifies the height of the textarea element based on the number of lines of text that are to be displayed without scrolling. The value represents the number of monofont character lines that are to be displayed within the height before the scrollbar becomes active. When the font size can be influenced by style sheets, the actual height changes accordingly.


Example

 document.forms[0].comments.rows = 6; 


Value

Integer.


Default

2 (IE/Windows); -1 (Mozilla, meaning that the attribute or property hasn't been set); 0 (Safari, Windows).


The selectionEnd and selectionStart properties are convenience properties that allow scripts to get and set the endpositions of a text selection within a text-oriented input element. Values are zero-based integer counters of positions between characters in the text entered into the field. When both properties have the same value, the visual result is the same as a text insertion pointer. For example, to place the cursor at the end of a text box, set the two values to the element's text length (see the textLength property). The equivalent IE functionality requires creating an IE text range in the element, adjusting the range's endpoints, and selecting the range (see the TexTRange object).


Example

 var elem = document.forms[0].myTextarea; elem.selectionEnd = elem.textLength; elem.selectionStart = elem.textLength; 


Value

Positive integer.


Default

None.


This is implemented in IE, but has no function for the textarea object.


Value

Boolean value: TRue | false; or null.


Default

null


Returns the number of characters in the textarea element.


Value

Integer.


Default

0


Returns the type of form control element. The value is returned in all lowercase letters. It may be necessary to cycle through all form elements in search of specific types to do some processing on (e.g., emptying all form controls of type "textarea" while leaving other controls untouched).


Example

 if (document.forms[0].elements[3].type == "textarea") {     ... } 


Value

Any of the following constants (as a string): button | checkbox | file | hidden | image | password | radio | reset | select-multiple | select-one | submit | text | textarea.


Default

textarea


Web Forms 2.0 extension that returns a browser-generated message if the form control fails to validate according to its specifications. An empty string means that the entry validates properly.


Value

String.


Default

Empty string.


Web Forms 2.0 extension that returns a ValidityState object. See the ValidityState object.


Value

ValidityState object.


Default

ValidityState object.


Specifies the current value associated with the form control that is submitted with the name/value pair for the element. All values are strings.


Example

 var comment = document.forms[0].myTextArea.value; 


Value

String.


Default

None.


Web Forms 2.0 extension that returns a Boolean value indicating whether the form control element meets criteria for validating under the Web Forms 2.0 mechanism.


Value

Boolean value: true | false.


Default

false


Indicates whether the browser should wrap text in a textarea element and whether wrapped text should be submitted to the server with soft returns converted to hard carriage returns. A value of hard engages word-wrapping and converts soft returns to CR-LF characters in the value submitted to the server. A value of soft turns on word-wrapping, but does not include the CR-LF characters in the text submitted with the form. A value of off turns word-wrapping off.


Example

 document.forms[0].comments.wrap = "soft"; 


Value

One of the constant values (as a string): hard | off | soft.


Default

soft


Web Forms 2.0 method that returns a Boolean value representing whether the form control element meets its validity criteriaultimately, whether the validity.valid property is TRue.


Returned Value

Boolean value: true | false.


Parameters

None.


Creates a Textrange object from the content of the textarea object. See the Textrange object for details.


Returned Value

TexTRange object.


Web Forms 2.0 methods that fire the change and formchange events on the current element. You could, for example "convert" a click event to a change or formchange event by having the onclick event handler invoke either method.


Returned Value

None.


Parameters

None.


handleEvent( event)

Instructs the object to accept and process the event whose specifications are passed as the parameter to the method. The object must have an event handler for the event type to process the event. Navigator 4 only.


Returned Value

None.


Parameters


event

A Navigator 4 event object.


Selects all the text displayed in the form element. To position the insertion pointer in a specific location inside a textarea element in IE, see the TexTRange object.


Returned Value

None.


Parameters

None.


setCustomValidity([ errorString])

Web Forms 2.0 method that sets the customError Boolean value of the validity property (itself a ValidityState object). If the method does not impact an element type, it throws a NOT_SUPPORTED_ERR error.


Returned Value

None.


Parameters


errorString

If null or an empty string, the parameter resets the validity object's customError property, signifying the form control is not valid. An error string is to be remembered by the browser (during the current session) so that it displays the string upon subsequent validation failures.


See Text.


The TexTRange object--similar in concept to the W3C DOM Range objectrepresents the text of zero or more characters in a document. When a text range consists of zero characters, it represents an insertion point between two characters (or before the first or after the last character).

A Textrange object is created via the createTextRange( ) method associated with the body, button, text, or textarea objects. You can also turn a user selection into a range via the selection object's createRange( ) (note the slight difference in the method name). Once you have created a text range, use its methods to adjust its start and endpoints to encompass a desired segment of the text (such as text that matches a search string). Once the range has been narrowed to the target text, assign values to its text property to change, remove, or insert text (or use pasteHTML( ) to insert HTML into the range). A library of direct commands that perform specific textual modifications can also be invoked to act on the text range. See Online Section V for details and examples of using the Textrange object.

Shared properties and methods from the list at the start of this chapter are: offsetLeft, offsetTop, getBoundingClientRect( ), getClientRects( ), and scrollIntoView( ). Note that the TexTRange object and all associated facilities are available only in the Windows version of Internet Explorer.


Object Model Reference

 objectRef.createTextRange( ) selectionObjectRef.createRange( ) 


Object-Specific Properties

boundingHeight
boundingLeft
boundingTop
boundingWidth
htmlText
text

Object-Specific Methods

collapse( )
compareEndPoints( )
duplicate( )
execCommand( )
expand( )
findText( )
getBookmark( )
inRange( )
isEqual( )
move( )
moveEnd( )
moveStart( )
moveToBookmark( )
moveToElementText( )
moveToPoint( )
parentElement( )
pasteHTML( )
queryCommandEnabled( )
queryCommandIndeterm( )
queryCommandState( )
queryCommandSupported( )
queryCommandText( )
queryCommandValue( )
select( )
setEndPoint( )

Return the pixel measure of the imaginary space occupied by the Textrange object. Although you do not see a Textrange object in the document (unless a script selects it), the area of a Textrange object is identical to the area that a selection highlight would occupy. These values cinch up to measure only as wide or tall as the widest and tallest part of the range. You would arrive at these same values by performing arithmetic on values returned from the getBoundingClientRect( ) method.


Example

 var rangeWidth = document.forms[0].myTextArea.createTextRange( ).boundingWidth; 


Value

Integer.


Default

None.


Return the pixel distance between the top or left of the browser window or frame and the top or left edges of the imaginary space occupied by the Textrange object. Although you do not see a TexTRange object in the document (unless a script selects it), the area of a Textrange object is identical to the area that a selection highlight would occupy. Values for these properties are measured from the fixed window or frame edges and not the top and left of the document, which may scroll out of view. Therefore, as a document scrolls, these values change.


Example

 var rangeOffH = document.forms[0].myTextArea.createTextRange( ).boundingLeft; 


Value

Integer.


Default

None.


Specifies all HTML of the document for a given element when that element is used as the basis for a Textrange object. For example, if you create a Textrange for the body element (document.body.createTextRange( )), the htmlText property contains all HTML content between (but not including) the body element tags.


Example

 var rangeHTML = document.body.createTextRange( ).htmlText; 


Value

String.


Default

None.


Indicates the text contained by the text range. In the case of a TexTRange object of a body element, this consists of only the text that is rendered, but none of the HTML tags behind the scenes.


Example

 var rangeText = document.body.createTextRange( ).text; 


Value

String.


Default

None.


collapse([ start])

Reduces the Textrange object to a length of zero (creating an insertion point) at the beginning or end of the text range before it collapsed.


Returned Value

None.


Parameters


start

Optional Boolean value that controls whether the insertion point goes to the beginning (true) of the original range or the end (false). The default value is true.


compareEndPoints(" type", comparisonRange)

Compares the relative position of the boundary (start and end) points of two ranges (the current range and one that had been previously saved to a variable). The first parameter defines which boundary points in each range you wish to compare. If the result of the comparison is that the first point is earlier in the range than the other point, the returned value is -1. If the result shows both points to be in the same location, the returned value is 0. If the result shows the first point to be later in the range than the other point, the returned value is 1. For example, if you have saved the first range to a variable r1 and created a new range as r2, you can see the physical relationship between the end of r2 and the start of r1:

 r1.compareEndPoints("EndToStart", r2) 

If r1 ends where r2 starts (the insertion point between two characters), the returned value is 0.


Returned Value

-1, 0, or 1.


Parameters


type

One of the following constants (as a string): StartToEnd | StartToStart | EndToStart | EndToEnd.


comparisonRange

A TexTRange object created earlier and saved to a variable.


Creates a new Textrange object with the same values as the current range. The new object is an independent object (the old and new do not equal each other), but their values are initially identical (until you start modifying one range or the other).


Returned Value

Textrange object.


Parameters

None.


execCommand(" commandName"[, UIFlag[, value]])

Executes the named command on the current TexTRange object. Many commands work best when the Textrange object is an insertion point. See Appendix D for a list of commands.


Returned Value

Boolean value: TRue if command is successful; false if unsuccessful.


Parameters


commandName

A case-insensitive string value of the command name. See Appendix D.


UIFlag

Optional Boolean value: TRue to display any user interface triggered by the command (if any); false to prevent such display.


value

A parameter value for the command.


expand(" unit")

Expands the current text range (including a collapsed range) to encompass the textual unit passed as a parameter. For example, if someone selects some characters from a document, you can create the range and expand it to encompass the entire sentence in which the selection takes place:

 var rng = document.selection.createRange( ); rng.expand("sentence"); 

If the starting range extends across multiple units, the expand( ) method expands the range outward to the next nearest unit.


Returned Value

Boolean value: true if method is successful; false if unsuccessful.


Parameters


unit

A case-insensitive string value of the desired unit: character | word | sentence | textedit. The textedit value expands the range to the entire original range.


findText(" string"[, searchScope][, flags])

Searches the current TexTRange object for a match of a string passed as the required first parameter. By default, matching is done on a case-insensitive basis. If there is a match, the Textrange object repositions its start and endpoints to surround the found text. To continue searching in the document, you must reposition the start point of the text range to the end of the found string (with collapse( )).

Optional parameters let you limit the scope of the search within the range to a desired number of characters after the range's start point, or dictate additional matching requirements, such as partial or whole words.


Returned Value

Boolean value: true if a match is found; false if unsuccessful.


Parameters


string

A case-insensitive string to be searched.


searchScope

Integer for the number of characters to search relative to the range's start point. A positive number searches forward; a negative number searches backward, to text earlier in the document than the start point of the text range.


flags

Integer for search detail codes: 0 (match partial words); 1 (match backwards); 2 (match whole words only); 4 (match case).


getBookmark( ) moveToBookmark( bookmarkString)

These two methods work together as a way to temporarily save a text range specification and restore it when needed. The getBookmark( ) method returns an opaque string (containing binary data that is of no value to human users). Once that value is stored in a variable, the range can be modified as needed for the script. Some time later, the bookmarked text range can be restored with the moveToBookmark( ) method:

 var rangeMark = myRange.getBookmark( ); ... myRange.moveToBookmark(rangeMark); 


Returned Value

Boolean value: TRue if the operation is successful; false if unsuccessful.


Parameters


bookmarkString

An opaque string returned by the getBookmark( ) method.


inRange( comparisonRange)

Determines whether the comparison range is within or equal to the physical range of the current text range.


Returned Value

Boolean value: true if the comparison range is in or equal to the current range; false if not.


Parameters


comparisonRange

Textrange object created earlier and saved to a variable.


isEqual( comparisonRange)

Determines whether the comparison range is identical to the current text range.


Returned Value

Boolean value: true if the comparison range is equal to the current range; false if not.


Parameters


comparisonRange

A TexTRange object created earlier and saved to a variable.


move(" unit"[, count])

Collapses the current text range to an insertion point at the end of the current range and moves it forward or backward from the current position by one or more units.


Returned Value

Integer of the number of units moved.


Parameters


unit

A case-insensitive string value of the desired unit: character | word | sentence | textedit. The textedit value moves the insertion pointer to the start or end of the entire original range.


count

An optional integer of the number of units to move the insertion pointer. Positive values move the pointer forward; negative values move the pointer backward. Default value is 1.


moveEnd(" unit"[, count]) moveStart(" unit"[, count])

Moves only the end or start point (respectively) of the current text range by one or more units. An optional parameter lets you specify both the number of units and direction. To shift the start point of a text range toward the beginning of the original range, be sure to specify a negative value. When moving the endpoint forward by word units, be aware that a word ends with a whitespace character (including a period). Therefore, if a findText( ) method sets the range to a found string that does not end in a space, the first moveEnd("word") method moves the ending point to the spot past the space after the found string rather than to the following word.


Returned Value

Integer of the number of units moved.


Parameters


unit

A case-insensitive string value of the desired unit: character | word | sentence | textedit. The textedit value moves the insertion pointer to the start or end of the entire original range.


count

An optional integer of the number of units to move the insertion pointer. Positive values move the pointer forward; negative values move the pointer backward. Default value is 1.


See getBookmark( ).


moveToElementText( elementObject)

Moves the current Textrange object's start and endpoints to encase the specified HTML element object. The resulting text range includes the HTML for the element, as well.


Returned Value

None.


Parameters


elementObject

A scripted reference to the object. This can be in the form of a direct reference (document.getElementById("elementID") or a variable containing the same kind of value.


moveToPoint( x, y)

Collapses the text range to an insertion pointer and sets its location to the spot indicated by the horizontal and vertical coordinates in the browser window or frame. This is as if the user had clicked on a spot in the window to define an insertion point. Use methods such as expand( ) to enlarge the text range to include a character, word, sentence, or entire text range.


Returned Value

None.


Parameters


x

Horizontal coordinate of the insertion point in pixels relative to the left edge of the window or frame.


y

Vertical coordinate of the insertion point in pixels relative to the top edge of the window or frame.


Returns an object reference to the next outermost element that fully contains the Textrange object.


Returned Value

Element object reference.


Parameters

None.


pasteHTML(" HTMLText")

Replaces the current text range with the HTML content supplied as a parameter string. Typically, this method is used on a zero-length text range object acting as an insertion pointer. All tags are rendered as if they were part of the original source code.


Returned Value

None.


Parameters


HTMLText

Document source code to be inserted into the document.


queryCommandEnabled(" commandName")

Indicates whether the command can be invoked in light of the current state of the document or selection.


Returned Value

Boolean value: TRue if enabled; false if not.


Parameters


commandName

A case-insensitive string value of the command name. See Appendix D.


queryCommandIndeterm(" commandName")

Indicates whether the command is in an indeterminate state.


Returned Value

Boolean value: true | false.


Parameters


commandName

A case-insensitive string value of the command name. See Appendix D.


queryCommandState(" commandName")

Determines the current state of the named command.


Returned Value

true if the command has been completed; false if the command has not completed; null if the state cannot be accurately determined.


Parameters


commandName

A case-insensitive string value of the command name. See Appendix D.


queryCommandSupported(" commandName")

Determines whether the named command is supported by the document object.


Returned Value

Boolean value: true | false.


Parameters


commandName

A case-insensitive string value of the command name. See Appendix D.


queryCommandText(" commandName")

Returns text associated with the command.


Returned Value

String.


Parameters


commandName

A case-insensitive string value of the command name. See Appendix D.


queryCommandValue(" commandName")

Returns the value associated with the command, such as the name font of the selection.


Returned Value

Depends on the command.


Parameters


commandName

A case-insensitive string value of the command name. See Appendix D.


Selects all the text that is included in the current Textrange object. This method brings some visual confirmation to users that a script knows about a particular block of text. For example, if you were scripting a search with the findText( ) method, you would then use the scrollIntoView( ) and select( ) methods on that range to show the user where the matching text is.


Returned Value

None.


Parameters

None.


setEndPoint(" type", comparisonRange)

Sets the endpoint of the current TexTRange object to the endpoint of another range that had previously been preserved as a variable reference.


Returned Value

None.


Parameters


type

One of the following constants (as a string): StartToEnd | StartToStart | EndToStart | EndToEnd.


comparisonRange

A TexTRange object created earlier and saved to a variable.


A Textrectangle object contains the coordinates of the four edges of an invisible box that surrounds a string of body text. Two methods of all element objects and the Textrange object produce information about two different kinds of text rectangles. The getClientRects( ) method returns a collection of line-by-line text rectangles; the getBoundingClientRect( ) method returns a single Textrectangle object that has coordinates that encompass all line-by-line rectangles.

Invoking either of these methods gets the rectangles' values instantaneously. Resizing the window or altering the content of the target object may change the actual rectangles, but the Textrangle objects obtained earlier do not keep pace with the changes (since the content of each line's rectangle is likely to change). Therefore, obtain Textrectangle values immediately before you need to process them in other script statements.


Object Model Reference

 elementOrTextRangeReference.getBoundingClientRect( ) elementOrTextRangeReference.getClientRects( )[i] 


Object-Specific Properties

bottom
left
top
right

Object-Specific Methods

None.


Object-Specific Events

None.


Return integer pixel values for the browser window coordinates of the rectangle edges. Note that these values are not relative to the page. Therefore, values change as the text holder scrolls.


Example

 var rightMostEdge = document.getElementById("myP").getBoundingClientRect( ).right; 


Value

Integer pixel measures


Default

None.


See tbody.


See td.


See tbody.


The title object reflects the title element. If you encounter problems referencing the element object by its id attribute, use the tag access methods, such as document.getElementsByTagName("title")[0].


HTML Equivalent

<title>


Object Model Reference

 [window.]document.getElementById("elementID") 


Object-Specific Properties

text


Object-Specific Methods

None.


Object-Specific Events

None.


Specifies the text content of the element. For the title element, this is the text between the start and end tags that also appears in the browser window's title bar (usually along with some identification of the browser brand) or tab (when in tabbed browsing). Changes you make to this property do not appear in the source code you view from the browser. Nor does the change appear in the title bar of IE for Windows.


Example

 document.getElementsByTagName("title")[0].text = "Welcome, Dave!"; 


Value

String.


Default

None.


See directories.


The tr object reflects the tr element.


HTML Equivalent

<tr>


Object Model Reference

 [window.]document.getElementById("elementID") [window.]document.getElementById("tableID").rows[i] 


Object-Specific Properties

align
bgColor
borderColor
borderColorDark
borderColorLight
cells[]
ch
chOff
height
rowIndex
sectionRowIndex
vAlign

Object-Specific Methods

deleteCell( )
insertCell( )

Object-Specific Events

None.


Defines the horizontal alignment of content within all cells of the row.


Example

 document.getElementById("myTR").align = "center"; 


Value

Any of the three horizontal alignment constants: center | left | right.


Default

left


Specifies the background color of the table cells in the current row. This color setting is not reflected in the style sheet backgroundColor property. Even if the bgcolor attribute or bgColor property is set with a plain-language color name, the returned value is always a hexadecimal triplet.


Example

 document.getElementById("myTR").bgColor = "yellow"; 


Value

A hexadecimal triplet or plain-language color name. See Appendix A for acceptable plain-language color names.


Default

Varies with browser and operating system.


Specifies the color of the element's border. Internet Explorer applies the color to all four lines that make up the interior border of a cell. Therefore, colors of adjacent cells do not collide.


Example

 document.getElementById("myTR").borderColor = "salmon"; 


Value

A hexadecimal triplet or plain-language color name. A setting of empty is interpreted as "#000000" (black). See Appendix A for acceptable plain-language color names.


Default

Varies with operating system.


The 3D effect of table borders in Internet Explorer is created by careful positioning of light and dark lines around the page's background or default color. You can independently control the colors used for the dark and light lines by assigning values to the borderColorDark (left and top edges of the cell) and borderColorLight (right and bottom edges) properties.

Typically, you should assign complementary colors to the pair of properties. There is also no rule that says you must assign a dark color to borderColorDark. The attributes merely control a well-defined set of lines so you can predict which lines of the border change with each attribute.


Example

 document.getElementById("myTR").borderColorDark = "blue"; document.getElementById("myTR").borderColorLight = "cornflowerblue"; 


Value

A hexadecimal triplet or plain-language color name. A setting of empty is interpreted as "#000000" (black). See Appendix A for acceptable plain-language color names.


Default

Varies with operating system.


Returns a collection of TD or th elements nested inside the table row. Items in the collection are in source code order.


Example

 var allRowCells = document.getElementById("myTR").cells; 


Value

Reference to a cells collection object.


Default

Array of zero length.


Defines the text character used as an alignment point for text cells of the row. This property is normally of value only for the align attribute set to "char". In practice, even though the table section element object has this property, the browser does not respond to values assigned to it.


Example

 document.getElementById("myTR").ch = "."; 


Value

Single character string.


Default

None.


Defines the offset point at which the character specified by the char attribute is to appear within a cell. In practice, even though the table secton element object has this property, the browser does not respond to values assigned to it.


Example

 document.getElementById("myTR").chOff = "80%"; 


Value

String value of the number of pixels or percentage (within the cell).


Default

None.


Specifies the pixel or percentage height of the row. To change the height of a row dynamically, adjust the element's style.height value rather than the height property.


Value

String value of the number of pixels or percentage (within the row).


Default

None.


Returns a zero-based integer representing the position of the current row among all other tr elements in the entire table. The count is based on the source code order of the tr elements.


Example

 var whichRow = document.getElementById("myTR").rowIndex; 


Value

Integer.


Default

None.


Returns a zero-based integer representing the position of the current row among all other tr elements in the row grouping. A row grouping can be one of the following elements: thead, tbody, tfoot. The count is based on the source code order of the tr elements.


Example

 var whichRow = document.getElementById("myTR").sectionRowIndex; 


Value

Integer.


Default

None.


Indicates the manner of vertical alignment of text within the cells of the current row.


Example

 document.getElementById("myTR").vAlign = "baseline"; 


Value

Case-insensitive constant (as a string): baseline | bottom | middle | top.


Default

middle


deleteCell( index)

Removes a td or th element nested within the current TR element. The integer parameter points to the zero-based item in the row's cells collection.


Returned Value

None.


Parameters


index

Zero-based integer corresponding to the numbered td element in source code order (nested within the current element).


insertCell( index)

Inserts a td element nested within the current tr element. The integer parameter points to the zero-based index in the cells collection where the new cell should go, but in IE you can also use the shortcut value of -1 to append the cell to the end of the collection. Adding the cell inserts an empty element, to which you add content via the various document tree modification techniques. Unfortunately, scripting the addition of table rows and cells in IE for the Macintosh (including Version 5.1) is very broken, yielding elephantine row and cell dimensions. For nonnested tables, you might be able to get away with regular document tree node creation and insertion instead of the table section object convenience methods.


Returned Value

Reference to the newly inserted cell.


Parameters


index

Zero-based integer corresponding to a row of the cells collection before which the new cell is to be inserted.


The treeWalker object is a live, hierarchical list of nodes that meet criteria defined by the document.createTreeWalker( ) method. The list assumes the same parent-descendant hierarchy for its items as the nodes to which its items point. The createTreeWalker( ) method describes the node where the list begins and which nodes (or classes of nodes) are exempt from the list by way of filtering.

The treeWalker object maintains a kind of pointer inside the list (so that your scripts don't have to). Methods of this object let scripts access the next or previous node (or sibling, child, or parent node) in the list, while moving the pointer in the direction indicated by the method you chose. If scripts modify the document tree after the treeWalker is created, changes to the document tree are automatically reflected in the sequence of nodes in the TReeWalker.

While fully usable in an HTML document, the TReeWalker can be even more valuable in an XML data document. For example, the W3C DOM does not provide a quick way to access all elements that have a particular attribute name (something that the XPATH standard can do easily on the server). But you can define a TReeWalker to point only to nodes that have the desired attribute, and quickly access those nodes sequentially (i.e., without having to script more laborious looping through all nodes in search of the desired elements). As an example, the following filter function allows only those nodes that contain the author attribute to be a member of a TReeWalker object:

 function authorAttrFilter(node) {     if (node.hasAttribute("author")) {         return NodeFilter.FILTER_ACCEPT;     }     return NodeFilter.FILTER_SKIP; } 

A reference to this function becomes one of the parameters to a createTreeWalker( ) method that also limits the list to element nodes:

 var authorsOnly = document.createTreeWalker(document, NodeFilter.SHOW_ELEMENT, authorAttrFilter, false); 

You can then invoke TReeWalker object methods to obtain a reference to one of the nodes in the list. When you invoke the method, the TReeWalker object applies the filter to candidates relative to the current position of the internal pointer in the direction indicated by the method. The next document tree node to meet the method and filter criteria is returned. Once you have that node reference, you can access any DOM node property or method to work with the node, independent of the items in the treeWalker list.


Object Model Reference

 TreeWalkerReference 


Object-Specific Properties

currentNode
expandEntityReference
filter
root
whatToShow

Object-Specific Methods

firstChild( )
lastChild( )
nextNode( )
nextSibling( )
parentNode( )
previousNode( )
previousSibling( )

Object-Specific Events

None.


Returns a reference to the node where the treeWalker's pointer is positioned. But more importantly, you can also assign a document tree node reference to this property to manually set a new position for the pointer. If the assigned node would normally be filtered out of the list, the next method invocation is performed from the position as if the assigned node were not filtered out of the list.


Example

 myTreeWalker.currentNode = document.getElementById("main"); 


Value

Reference to a document tree node.


Default

First node of the document.


These four properties reflect the parameter values passed to the document.createTreeWalker( ) method when the object was created.


These methods return references to nodes within the hierarchy of items in the treeWalker object. The parent-descendant relationships between nodes are identical to those of the nodes within the document tree. As you invoke any one of these methods, the treeWalker's internal pointer moves to a position adjacent to the node's spot within the TReeWalker list. If there is no node meeting the desired reference, the method returns null. This means that you need to verify the existence of the node before reading any property of the node:

 if (myTreeWalker.nextSibling( )) {     var theTag = myTreeWalker.currentNode.tagName; } 

If you reference a property of a null reference directly (mytreeWalker.nextSibling( ).tagName, for example), a reference error results.


Returned Value

Reference to a document tree node.


Parameters

None.


Move the internal NodeIterator pointer one position forward (nextNode( )) or backward (previousNode( )), while returning a reference to the node through which the pointer passed en route. These two methods operate as if the hierarchy were flattened (in the manner of a NodeIterator object).


Returned Value

Reference to a node in the document tree.


Parameters

None.


See b.


See b.


The W3C DOM UIEvent object is an abstract object that contains the properties and methods shared by every instance of a W3C DOM focus-related event. This object inherits characteristics from the W3C DOM Event object. The properties and method of this object are blended into the directly scripted event object. See the discussion of the event object earlier in this chapter for specific property and method support for this object and how these items are inherited by more specific event types.


The ul object reflects the ul element.


HTML Equivalent

<ul>


Object Model Reference

 [window.]document.getElementById("elementID") 


Object-Specific Properties

compact
type

Object-Specific Methods

None.


Object-Specific Events

None.


When set to true, the compact property should instruct the browser to render items in the list in a more compact format. This property has no effect in mainstream browsers.


Example

 document.getElementById("myUL").compact = true; 


Value

Boolean value: TRue | false.


Default

false


Specifies the manner in which the leading item markers in the list are displayed.


Example

 document.getElementById("myUL").type = "square"; 


Value

Any one of the constant values (as a string): circle | disc | square. Additional choices available through style sheets


Default

disc


The userProfile object reflects numerous pieces of information stored in the browser's user profile for the current user. This object has four methods that:

  • Let you queue requests for individual fields of the profile (items such as name, mailing address, phone numbers, and so on)

  • Display the request dialog that lets users see what you're asking for and disallow specific items or the whole thing

  • Grab the information

  • Clear the request queue

Once the information is retrieved (with the user's permission), it can be slipped into form elements (visible or hidden) for submission to the server. Compatibility listings here indicate support in IE 4 through 6 for Windows only. While IE for Macintosh accepts the method calls without error, there is no functionality attached to those methods. Further details on the user profile are available from Microsoft at http://msdn.microsoft.com/workshop/management/profile/profile_assistant.asp.


Example

 navigator.userProfile.addReadRequest("vcard.displayname"); navigator.userProfile.doReadRequest("3", "MegaCorp Customer Service"); var custName = navigator.userProfile.getAttribute("vcard.displayname"); navigator.userProfile.clearRequest( ); if (custName) {     ... } 


Object Model Reference

 navigator.userProfile 


Object-Specific Properties

None.


Object-Specific Methods

addReadRequest( )
clearRequest( )
doReadRequest( )
getAttribute( )

Object-Specific Events

None.


addReadRequest(" attributeName")

Adds a request to inspect a particular user profile attribute to a queue that must be executed separately (via the doReadRequest( ) and getAttribute( ) methods). Items added to the queue are displayed to the user to select which item(s) can be submitted to a server. For multiple attributes, use multiple invocations of the addReadRequest( ) method.


Returned Value

Boolean value: true (if successful) | false (if unsuccessful).


Parameters


attributeName

One of the following case-insensitive attribute names as a string:

vCard.Business.City
vCard.Business.Country
vCard.Business.Fax
vCard.Business.Phone
vCard.Business.State
vCard.Business.StreetAddress
vCard.Business.URL
vCard.Business.Zipcode
vCard.Cellular
vCard.Company
vCard.Department
vCard.DisplayName
vCard.Email
vCard.FirstName
vCard.Gender
vCard.Home.City
vCard.Home.Country
vCard.Home.Fax
vCard.Home.Phone
vCard.Home.State
vCard.Home.StreetAddress
vCard.Home.Zipcode
vCard.Homepage
vCard.JobTitle
vCard.LastName
vCard.MiddleName
vCard.Notes
vCard.Office
vCard.Pager

Empties the queue of attribute names to be retrieved. Use this after your script has successfully retrieved the required information. This prepares the queue for the next list.


Returned Value

None.


Parameters

None.


doReadRequest( usageCode[, " friendlyName"[, " domain"[, " path"[, " expiration"]]]])

Based on the items in the queue, this method inspects the browser to see whether the user has given permission to inspect these attributes in the past. If not (for some or all), the method displays a dialog box (the Profile Assistant window) that lets users turn off the items that should not be exposed to the server. Parameters provide information for the dialog and for maintenance of the permission (similar to the ways that cookies are managed). Only one doReadRequest( ) method is required, regardless of the number of attributes in the queue.


Returned Value

In Windows, the method returns no value, regardless of how the user responds to the Profile Assistant dialog box. On the Macintosh (which does not support this object fully), the method does not display the Profile Assistant dialog box and returns false.


Parameters


usageCode

One of the following code integers that display human-readable messages defined by the Internet Privacy Working Group, as shown in the following table.

Code

Meaning

0

Used for system administration.

1

Used for research and/or product development.

2

Used for completion and support of current transaction.

3

Used to customize the content and design of a site.

4

Used to improve the content of the site, including advertisements.

5

Used for notifying visitors about updates to the site.

6

Used for contacting visitors for marketing of services or products.

7

Used for linking other collected information.

8

Used by site for other purposes.

9

Disclosed to others for customization or improvement of the content and design of the site.

10

Disclosed to others who may contact you for marketing of services and/or products.

11

Disclosed to others who may contact you for marketing of services and/or products, but you have the opportunity to ask a site not to do this.

12

Disclosed to others for any other purpose.



friendlyName

An optional string containing an identifiable name (and URL) that the user recognizes as the source of the request. This may be a corporate identity.


domain

An optional string containing the domain of the server making the request. If an expiration date is set, this information is stored with the requested attributes to prevent future requests from this domain from interrupting the user with the Profile Assistant dialog box.


path

An optional string containing the path of the server document making the request. If an expiration date is set, this information is stored with the requested attributes to prevent future requests from this domain from interrupting the user with the Profile Assistant dialog box.


expiration

An optional string containing the date on which the user's permissions settings expire. Not recognized in Internet Explorer 4.


getAttribute(" attributeName")

Returns the value of the attribute, provided the user has given permission to do so. If that permission was denied, the method returns null. Use one getAttribute( ) method for each attribute value being retrieved.


Returned Value

String value or null.


Parameters


attributeName

One of the vCard attribute names listed in the addReadRequest( ) method description.


In Web Forms 2.0, each form control capable of receiving user entry has a validity property whose value is an instance of the ValidityState object. This object contains nine Boolean properties, eight of which may be set to true if the corresponding validity test fails. An input, textarea, and select element (again only the Web Forms 2.0 environment) offers enough supplemental attributes to let a page author preset value types, upper and lower limits, text patterns, and even if user entry is required before the form may be submitted. For example, if a text input element is set up to receive a number within a particular range, the validity.typeMismatch property will be set to TRue if the user enters a letter; if the user enters a number but it is higher than the expected range, the validity.rangeOverflow property is set to true.

All of this comes into play when the instance of the ValidityState object goes to set the valid propertythe gatekeeper to whether the element passes validation. If any of the specific validation error properties is false, then the valid property is also false. In other words, the validation tests must have all "green lights" (i.e., the individual test properties are false) before the valid property is set to TRue.

The following example demonstrates one way to bring validity tests together with an output element object affiliated with a time-oriented input element, which displays a plain-language error message to the user:

 <script type="text/javascript"> // <![CDATA[ function validateField(evt) {    var form = evt.target.form;    var errField = form.elements[evt.target.name + "Error"];    if (evt.target.validity.typeMismatch) {       errField.value = 'You must enter a time (hh:mm).';    } else if (evt.target.validity.stepMismatch) {       errField.value = 'Appointments must begin at 0, 15, 30, or 45 past the hour.';    } else if (evt.target.validity.rangeUnderflow) {       errField.value = 'The earliest appointment is 9:00 am.';    } else if (evt.target.validity.rangeOverflow) {       errField.value = 'The last appointment is 5:00 pm.';    } else if (evt.target.validity.valueMissing) {       errField.value = 'You must enter a time.';    } else {       errField.value = '';    }    evt.preventDefault( ); // ]]> } </script> ... <form action="..." method="get" > <p><label>Desired appointment time:     <input type="time" name="apptTime" min="09:00" max="17:00" value="09:00" step="900"            required="required" onforminput="validateField(event)" /> </label> <output name="apptTimeError" /> </p> <p> <input type="submit" /> </p> </form> 


Object Model Reference

 [window.]document.getElementById("elementID") 


Object-Specific Properties

customError
patternMismatch
rangeOverflow
rangeUnderflow
stepMismatch
tooLong
typeMismatch
valid
valueMissing

Object-Specific Methods

None.


If true, the control was marked invalid by script intervention.


Value

Boolean value: TRue | false.


Default

false


If true, the input value does not match the regular expression pattern assigned to it. An empty field results in this property being false.


Value

Boolean value: true | false.


Default

false


If TRue, the input value (number, time, date, or file) exceeds the limits set by the max and min attributes, respectively.


Value

Boolean value: TRue | false.


Default

false


If true, the input value does not meet the value increment parameters established by the control's step attribute.


Value

Boolean value: TRue | false.


Default

false


If true, the input value exceeds the character length established by the control's maxlength attribute.


Value

Boolean value: true | false.


Default

false


If TRue, the input value is not of the value type expected by the control (based on the control's type attribute, or a file input element's accept attribute).


Value

Boolean value: TRue | false.


Default

false


If true, all other properties of the object are false, indicating that all controls have passed validation.


Value

Boolean value: TRue | false.


Default

false


If true, the input value is empty, and the element's required attribute has been set.


Value

Boolean value: true | false.


Default

false


See abbr.


The W3C DOM ViewCSS object is an abstract object that feeds its getComputedStyle( ) method to the document.defaultView object. This provides the actual rendered style sheet properties for a given element node.


Object Model Reference

 [window.]document.defaultView 


Object-Specific Properties

None.


Object-Specific Methods

getComputedStyle( )


Object-Specific Events

None.


getComputedStyle( elementNodeReference, " pseudoElementName")

Returns a style object (specifically, a CSSStyleDeclaration object in the W3C DOM terminology) showing the net cascade of style settings that affect the element passed as the first parameter. To retrieve a particular style attribute value (including a value inherited from the default browser style sheet), use the getPropertyValue( ) method of the style object returned from this method:

 var compStyle = getComputedStyle(document.getElementById("myP"), ""); var pBGColor = compStyle.getPropertyValue("background-color"); 

See the style object for additional details.


Returned Value

style (CSSStyleDeclaration) object reference.


Parameters


elementNodeReference

Reference to an element node in the document tree that becomes the selection.


pseudoElementName

String name of a pseudo-element (e.g., :first-line) or an empty string.


The wbr object reflects the wbr element.


HTML Equivalent

<wbr>


Object Model Reference

 [window.]document.getElementById("elementID") 


Object-Specific Properties

None.


Object-Specific Methods

None.


Object-Specific Events

None.


The window object represents the browser window or frame in which document content is displayed. The window object plays a vital role in scripting when scripts must communicate with document objects located in other frames or subwindows. Managing multiple windows can be tricky business because of the transient nature of cross-window references. Strict interpretation of HTML and XHTML standards frowns upon multiple windows, and many confused users may agree.

Although the W3C DOM Level 2 does not provide in-depth specifications for the window object (a window, after all, is outside the scope of document markup), it nevertheless indicates possible future hooks through what it calls "view" objects. Thus, the Netscape 6 document.defaultView property returns the document's window; the Netscape 6 window object also takes on the method of the ViewCSS object to gain the DOM's getComputedStyle( ) method.

The window object has been scriptable since the beginning and bears a considerable legacy of properties and methods. Many of these features are browser-specific, so observe compatibility ratings carefully before adopting a particular object feature.


Object Model Reference

 window self top parent 


Object Properties

clientInformation
clipboardData
closed
Components
content
controllers
crypto
defaultStatus
dialogArguments
dialogHeight
dialogLeft
dialogTop
dialogWidth
directories
document
event
external
frameElement
frames[]
fullScreen
history
innerHeight
innerWidth
length
location
locationbar
menubar
name
navigator
netscape
offscreenBuffering
opener
outerHeight
outerWidth
pageXOffset
pageYOffset
parent
personalbar
pkcs11
prompter
returnValue
screen
screenLeft
screenTop
screenX
screenY
scrollbars
scrollMaxX
scrollMaxY
scrollX
scrollY
self
sidebar
status
statusbar
toolbar
top
window

Object Methods

addEventListener( )
alert( )
attachEvent( )
back( )
blur( )
captureEvents( )
clearInterval( )
clearTimeout( )
close( )
confirm( )
createPopup( )
detachEvent( )
disableExternalCapture( )
dispatchEvent( )
dump( )
enableExternalCapture( )
execScript( )
find( )
focus( )
forward( )
GeckoActiveXObject( )
getComputedStyle( )
getSelection( )
home( )
moveBy( )
moveTo( )
navigate( )
open( )
openDialog( )
print( )
prompt( )
releaseEvents( )
removeEventListener( )
resizeBy( )
resizeTo( )
routeEvent( )
scroll( )
scrollBy( )
scrollByLines( )
scrollByPages( )
scrollTo( )
setInterval( )
setTimeout( )
showHelp( )
showModalDialog( )
showModelessDialog( )
sizeToContent( )
stop( )

Object-Specific Events

Event

IE/Windows

Mozilla

Safari

Opera

DOM

afterprint

·

beforeprint

·

beforeunload

·

·

blur

·

·

·

·

dragdrop

·

error

·

·

·

·

focus

·

·

·

·

help

·

load

·

·

·

·

move

·

resize

·

·

·

·

scroll

·

·

·

·

unload

·

·

·

·



Returns the navigator object. The navigator object is named after a specific browser brand; the clientInformation property is a nondenominational way of accessing important environment variables that have historically been available through properties and methods of the navigator object (discussed separately earlier in this chapter as its own object).


Example

 if (parseInt(window.clientInformation.appVersion) >= 4) {     // process code for IE 4 or later } 


Value

The navigator object.


Default

The navigator object.


Returns the clipboardData object, discussed separately earlier in this chapter as its own object. The object (accessible as a property of a window or frame object) is a temporary container that scripts in IE 5 and later for Windows can use to transfer text data, particularly during script-controlled operations that simulate cutting, copying, and pasting, or that control dragging.


Example

 var rng = document.selection.createRange( ); clipboardData.setData("Text",rng.text); 


Value

The clipboardData object.


Default

The clipboardData object.


This is the Boolean value that says whether the referenced window is closed. A value of true means the window is no longer available for referencing its objects or script components. This is used most often to check whether a user has closed a subwindow generated by the window.open( ) method.


Example

 if (!newWindow.closed) {     newWindow.document.close( ); } 


Value

Boolean value: true | false.


Default

None.


These properties are associated with the proprietary Mozilla xpconnect ("cross-platform" connect) services. These services allow scripts that have the correct security clearance to work with XPCOM (decidedly not MS COM) objects to extend the functionality of the application that uses the Mozilla engine (such as the Netscape 6 browser). Access to these services requires enabling security privileges (typically via signed scripts), as follows:

 netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect"); // your xpconnect access code here netscape.security.PrivilegeManager.revertPrivilege("UniversalXPConnect"); 

For more details on this mechanism, visit http://www.mozilla.org/scriptable/.


Return references to objects associated with Mozilla public-key cryptography internals. For more details on this subject, visit http://www.mozilla.org/projects/security/.


Specifies the default message displayed in the browser window's status bar when no browser loading activity is occurring. To temporarily change the message (during mouse rollovers, for example), set the window's status property. Most scriptable browsers and versions have difficulty managing the setting of the defaultStatus property. Expect odd behavior.


Example

 window.defaultStatus = "Make it a great day!"; 


Value

Any string value.


Default

None.


This is the string or other data type passed as extra arguments to a modal dialog window created with the window.showModalDialog( ) or (in IE 5 and later for Windows only) window.showModelessDialog( ) methods. This property is best accessed by a script in the document displayed in the dialog window in order to retrieve whatever data is passed to the new window as arguments. It is up to your script to parse the data if you include more than one argument nugget separated by whatever argument delimiter you choose.


Example

 // in dialog window var allArgs = window.dialogArguments; var firstArg = allArgs.substring(0, allArgs.indexOf(";")); 


Value

String, number, array, or object.


Default

None.


Specify the height and width values of a modal dialog window created with the showModalDialog( ) and showModelessDialog( ) methods. Although Internet Explorer does not balk at modifying these properties (in a script running in the modal dialog window), the changed values are generally not reflected in a resized dialog window. Initial values are set as parameters to the dialog-opening methods.


Example

 var outerWidth = window.dialogWidth; 


Value

String, including the unit value (e.g., 520px).


Default

None.


Indicate the offset distance of the left and top edges of a modal dialog window (created with the showModalDialog( ) and showModelessDialog( ) methods) relative to the top-left corner of the video screen. Although Internet Explorer does not balk at modifying these properties (in a script running in the modal dialog window), the changed values are generally not reflected in a repositioned dialog window. Initial values are set as parameters to the dialog methods.


Example

 var outerLeft = window.dialogLeft; 


Value

String, including the unit value (e.g., 80px).


Default

None.


Return references to the Navigator browser window feature (the directories property is new for Mozilla). See the discussion of the directories (et al.) objects earlier in this chapter for how to control the visibility of these window features with signed scripts.


Example

 netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserWrite") window.statusbar.visible = "false"; netscape.security.PrivilegeManager.revertPrivilege("UniversalBrowserWrite") 


Value

Respective object references.


Default

None.


Returns a reference to the document object contained by the window. In browsers that offer W3C DOM document tree support, this property points more specifically to the root HTMLDocument node for the document tree loaded in the window. The W3C DOM even describes this property as a member of one of its View objects (analogous to a browser window). This is the property that lets scripts references to document methods and content begin with the word document.


Example

 var oneElem = document.getElementById("myP"); 


Value

Reference to the root document object.


Default

Reference to the root document object.


Internet Explorer's event model generates an event object for each user or system event. This event object is a property of the window object. Opera implements a hybrid event mechanism (IE and W3C DOM). The window.event property returns an event object that has both IE and W3C DOM characteristics (e.g., sourceElement and target properties). For details about the IE event object, see Online Section VI and the listing of the event object in this chapter.


Example

 if (event.altKey) {     // handle case of Alt key down } 


Value

event object reference.


Default

None.


Returns a reference to the external object, which provides access to lower-level functionality of the browser engine (security permissions willing). See the discussion of the external object earlier in this chapter.


Example

 external.AddFavorite("http://www.dannyg.com", "Danny Home Page"); 


Value

external object reference.


Default

external object reference.


If the current window is a member of a frameset or is an iframe, the frameElement property returns a reference to the frame or iframe element object (distinct from the frame-as-window object). Security restrictions, however, can impede script access to this property.


Example

 var frameID = window.frameElement.id; 


Value

frame or iframe object reference; or null.


Default

null.


Returns a collection (array) of window objects that are implemented as frames or iframes in the current window. For a frameset's parent or top window, the array contains references to first-generation frame windows. Index values can be zero-based integers (in source code order) or the identifier assigned to the name attribute of the frame element.


Example

 parent.frames[1].myFunc( ); 


Value

Array of frame (window) object references.


Default

Array of length zero.


Always returns Boolean false, even if the browser is set to Full Screen mode via the View menu in Windows.


Value

Boolean value: true | false.


Default

false


Contains the history object for the current window or frame. For details, see the discussion of the history object.


Example

 if (self.history.length > 4) {     ... } 


Value

history object reference.


Default

Current history object.


Specify the pixel measure of the height and width of the content region of a browser window or frame. This area is where the document content appears, exclusive of all window "chrome." For comparable values in IE, see the body element object.


Example

 window.innerWidth = 600; window.innerHeight = 400; 


Value

Integer.


Default

None.


Specifies the number of frames (if any) nested within the current window. This value is the same as that returned by window.frames.length. When no frames are defined for the window, the value is zero.


Example

 if (window.length > 0) {     ... } 


Value

Integer.


Default

0


Returns a location object containing URL details of the document currently loaded in the window or frame. To navigate to another page, you assign a URL to the location.href property (or see the navigate( ) method for an IE-only alternative). See the location object.


Example

 top.location.href = "index.html"; 


Value

A full or relative URL as a string.


Default

Current location object.


See directories.


See directories.


This is the identifier associated with a frame or subwindow for use as the value assigned to target attributes or as script references to the frame/subwindow. For a frame, the value is usually assigned via the name attribute of the frame tag, but it can be modified by a script if necessary. The name of a subwindow is assigned as a parameter to the window.open( ) method. The primary browser window does not have a name by default, but you can assign one via script if you need a subwindow to target a link or form back to the main window.


Example

 if (parent.frames[1].name == "main") {     ... } 


Value

Case-sensitive identifier that follows the rules of identifier naming: it may contain no whitespace, cannot begin with a numeral, and should avoid punctuation except for the underscore character.


Default

None.


Returns a reference to the navigator object. Since the window reference is optional, syntax without the window reference works on all scriptable versions of Internet Explorer and Navigator. See the navigator object.


Example

 var theBrowser = navigator.appName; 


Value

navigator object reference.


Default

navigator object.


Returns a reference to the netscape object, which offers limited script access to the inner workings of the application through signed scripts and the user's explicit permission. For example, it is through the netscape object that JavaScript can access the PrivilegeManager.


Example

 netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserWrite"); 


Value

netscape object reference.


Default

netscape object.


Indicates whether the browser should use offscreen buffering to improve path animation performance. Although the property is implemented in IE 5 for Macintosh, it is unclear that it offers any functionality. Recent versions of IE for Windows connect this property to the DirectX ActiveX control. When the document loads, the property is set to auto. After that, a script may turn buffering on and off by assigning a Boolean value to this property.


Example

 window.offscreenBuffering = "true"; 


Value

Boolean value: true | false.


Default

auto


This is an object reference to the window (or frame) that used a window.open( ) method to generate the current window. This property allows subwindows to assemble references to objects, variables, and functions in the originating window. To access document objects in the creating window, a reference can begin with opener and work its way through the regular document object hierarchy from there, as shown in the left side of the following example statement. The relationship between the opening window and the opened window is not strictly parent-child. The term "parent" has other connotations in scripted window and frame references. IE's dialog windows (the showModalDialog( ) and showModelessDialog( ) windows) do not support this property. Values between the main and dialog windows must be passed at creation time and via the dialog window's returnValue property upon closing.


Example

 opener.document.forms[0].importedData.value = document.forms[0].entry.value; 


Value

window object reference.


Default

None.


Specify the pixel measure of the height and width of the browser window or frame, including (for the top window) all tool bars, scoll bars, and other visible window "chrome." IE offers no equivalent properties.


Example

 window.outerWidth = 80; window.outerHeight = 600; 


Value

Integer.


Default

None.


Specify the pixel measure of the amount of the page's content that has been scrolled upward and/or to the left. For example, if a document has been scrolled so that the topmost 100 pixels of the document (the "page") are not visible because the window is scrolled, the pageYOffset value for the window is 100. When a document is not scrolled, both values are zero.


Example

 var vertScroll = self.pageYOffset; 


Value

Integer.


Default

0


Returns a reference to the parent window object whose document defined the frameset in which the current frame is specified. Use parent in building a reference from one child frame to variables or methods in the parent document or to variables, methods, and objects in another child frame. For example, if a script in one child frame must reference the content of a text input form element in the other child frame (named "content"), the reference would be:

 parent.content.document.forms[0].entryField.value 

For more deeply nested frames, you can access the parent of a parent with syntax such as: parent.parent.frameName.


Example

 parent.frames[1].document.forms[0].companyName.value = "MegaCorp"; 


Value

window object reference.


Default

Current window object reference.


See directories.


See crypto.


See Components.


A value to be returned to the main window when an IE dialog window (generated by showModalDialog( ) method only) closes. The value assigned to this property in a script running in the dialog window becomes the value returned by the showModalDialog( ) method in the main window. For example, the document in the modal dialog window may have a statement that sets the returnValue property with information from the dialog:

 window.returnValue = window.document.forms[0].userName.value; 

The dialog is created in the main document with a statement like the following:

 var userName = showModalDialog("userNamePrompt.html"); 

Whatever value is assigned to returnValue in the dialog is then assigned to the userName variable when the dialog box closes and script execution continues.


Value

Any scriptable data type.


Default

None.


Returns a reference to the screen object. Since the window reference is optional, syntax without the window reference works on all scriptable browsers.


Example

 var howHigh = screen.availHeight; 


Value

screen object reference.


Default

screen object.


Return pixel coordinates of the top-left corner of the browser content area relative to the top-left corner of the screen. A maximized IE browser window returns a screenLeft value of 0, but the screenTop value varies with the complement of toolbars the user chooses to display. Use window.moveTo( ) to change the window position.


Example

 var fromTheTop = window.screenTop; 


Value

Integer.


Default

User-dependent


Return pixel coordinates of the top-left corner of the entire browser window (including "chrome") relative to the top-left corner of the screen. A browser window maximized under Windows returns screenX and screenY values of -4 because the chrome extends slightly beyond the screen display. You can adjust the window location through these properties or the window.moveTo( ) method.


Example

 var fromTheTop = window.screenY; 


Value

Integer.


Default

User-dependent.


See directories.


Return the number of pixels along the horizontal (scrollMaxX) and vertical (scrollMaxY) axes that the current window's content can be scrolled. If there is no scrollbar along an axis, its corresponding value is zero because the window cannot be scrolled in that direction. You can use these properties to determine the total rendered height and width of a scrolled document by adding the window's innerWidth and innerHeight values to the corresponding maximum scroll properties.


Example

 var docHeight = window.scrollMaxY + window.innerHeight; 


Value

Integer.


Default

0


Return the pixel distance the window is scrolled along the horizontal (scrollX) and vertical (scrollY) axes. To determine these values in IE, you must take into account compatibility mode settings in IE 6 (see the DOCTYPE element in Chapter 1). In quirks mode and in IE for Macintosh, use the document.body.scrollLeft and document.body.scrollTop properties. In IE 6 standards compatibility mode (where document.compatMode == "CSS1Compat"), use document.body.parentNode.scrollLeft and document.body.parentNode.scrollTop to get the scroll values of the html element.


Example

 var scrolledDown = window.scrollY; 


Value

Integer.


Default

0


This is a reference to the current window or frame. This property is synonymous with window, but is sometimes used to improve clarity in a complex script that refers to many windows or frames. Never use the reference window.self to refer to the current window or frame because some browser versions get confused with the reference.


Example

 self.focus( ); 


Value

window object reference.


Default

Current window.


See Components.


Specifies the text of the status bar of the browser window. Setting the status bar to some message is recommended only for temporary messages, such as for mouse rollovers atop images. To prevent link spoofing (where the visible text of a link indicates a trustworthy site, but the HRef of the link points to a Bad Guy's site), the trend in modern browsers is to not allow modifying the status bar when rolling the mouse atop links.

Double or single quotes in the message must be escaped (\'). Many users don't notice incidental text in the status bar, so avoid putting mission-critical information there. Temporary messages conflict with browser-driven use of the status bar for loading progress and other purposes. To set the default status bar message (when all is at rest), see the defaultStatus property.


Example

 <...onmouseover="window.status='Table of Contents';return true" onmouseout = "window.status = '';return true"> 


Value

String.


Default

Empty string.


See directories.


See directories.


This is an object reference to the browser window. Script statements from inside nested frames can refer to the browser window properties and methods or to variables or functions stored in the document loaded in the topmost position. Do not begin a reference with window.top, just top. To replace a frameset with a new document that occupies the entire browser window, assign a URL to the top.location.href property.


Example

 top.location.href = "tableOfContents.html"; 


Value

window object reference.


Default

Browser window.


This is an object reference to the browser window.


Example

 if (window == top) {     // load a frameset     location.href = "mainFrameset.html"; } 


Value

window object reference.


Default

Browser window.


addEventListener(" eventType", listenerFunction, useCapture)

Although the window object as we know it is not officially part of the W3C DOM, mainstream W3C DOM browsers implement this W3C DOM event model method for the window object. See the addEventListener( ) method discussion among the shared methods described earlier in this chapter.


alert(" message")

Displays an alert dialog box with a message of your choice. Script execution halts while the dialog box appears. A single button lets the user close the dialog. The title bar of the window (and the "JavaScript Alert" legend in earlier browser versions) cannot be altered by script.


Returned Value

None.


Parameters


message

Any string.


attachEvent(" eventName", functionReference)

This IE event model method, shared among all element objects, is also a member of the window object. See the attachEvent( ) method discussion among the shared methods described earlier in this chapter.


Navigates one step backward through the history list of the window or frame. You may prefer the cross-browser history.back( ) method.


Returned Value

None.


Parameters

None.


Removes focus from the window and fires a blur event (in IE). No other element necessarily receives focus as a result, but if another browser window is open at the time, the current window moves to the rear of the stack (except in Opera, whose display does not change).


Returned Value

None.


Parameters

None.


captureEvents( eventTypeList)

Instructs the browser to grab events of a specific type before they reach their intended target objects. The object invoking this method must then have event handlers defined for the given event types to process the event. Although this method is part of the Navigator 4 event model, it is supported in Mozilla, Safari, and Opera, creating the equivalent of a W3C DOM capture-mode event listener for the document object. Continue to use this method if you must support Navigator 4, but migrate new code to the W3C DOM event listener syntax as described in Online Section VI. Mozilla's documentation now calls this method obsolete.


Returned Value

None.


Parameters


eventTypeList

A comma-separated list of case-sensitive event types as derived from the available Event object constants, such as Event.CLICK or Event.MOUSEMOVE.


clearInterval( intervalID)

Turns off the interval looping action referenced by the intervalID parameter. See window.setInterval( ) for how to initiate such a loop.


Returned Value

None.


Parameters


intervalID

An integer created as the return value of a setInterval( ) method.


clearTimeout( timeoutID)

Turns off the timeout delay counter referenced by the timeoutID parameter. See window.setTimeout( ) for how to initiate such a delay.


Returned Value

None.


Parameters


timeoutID

An integer created as the return value of a setTimeout( ) method.


Closes the current window. A script in a subwindow cannot close the main window without receiving the user's explicit permission from a security dialog box. Mozilla and Safari prevent a window from closing itself, but, like all browsers, a main window can close a subwindow when a script in the main window previously opened the subwindow via the window.open( ) method.


Returned Value

None.


Parameters

None.


confirm(" message")

Displays a dialog box with a message and two clickable buttons. Script execution halts while the dialog box appears. One button indicates a Cancel operation; the other button indicates the user's approval (OK or Yes). The text of the buttons is not scriptable. The message should ask a question to which either button would be a logical reply. A click of the Cancel button returns a value of false; a click of the OK button returns a value of true.

Because this method returns a Boolean value, you can use this method inside a condition expression:

 if (confirm("Reset the entire form?")) {     document.forms[0].reset( ); } 


Returned Value

Boolean value: TRue | false.


Parameters


message

Any string, usually in the form of a question.


Opens a blank popup rectangular space that can be populated with HTML content, yet the space can extend across frame boundaries and even window borders. Scripts must assign content (not an external URL) to the popup object returned by the method. See the popup object for more details and an example of usage.


Returned Value

popup object reference.


Parameters

None.


detachEvent(" eventName", functionReference)

This IE event model method, shared among all element objects, is also a member of the window object. See the detachEvent( ) method discussion among the shared methods described earlier in this chapter.


With signed scripts and the user's permission, a script can capture events in other windows or frames that come from domains other than the one that served the document with event-capturing scripts. Navigator 4 only.


Returned Value

None.


Parameters

None.


dispatchEvent( eventObjectReference)

Although the window object is not officially part of the W3C DOM, Mozilla and Opera implement this W3C DOM event model method for the window object. See the dispatchEvent( ) method discussion among the shared methods described earlier in this chapter.


dump( message)

Write's the string passed as a parameter to the console or other device configured to be STDOUT. When this method was first implemented, scripters had to enable the method from the browser's configuration preferences. In more recent versions, however, the preference key is no longer among preferences accessible via the about:config URI.


Returned Value

None.


Parameters


message

String of a message to be sent to STDOUT.


execScript( expressionList [, language])

Evaluates one or more script expressions in any scripting language embedded in the browser. Expressions must be contained within a single string; multiple expressions are delimited with semicolons:

 window.execScript("var x = 3; alert(x * 3)") 

The default script language is JavaScript. If you need to see results of the script execution, provide for the display of resulting data in the script expressions, as shown in the example. The execScript( ) method itself returns no value.


Returned Value

None.


Parameters


expressionList

String value of one or more semicolon-delimited script expressions.


language

String value for a scripting language: JavaScript | JScript | VBS | VBScript.


find(" searchString"[, matchCase[, searchUpward]])

Searches the document body text for a string and selects the first matching string. Optionally, you can specify whether the search should be case-sensitive or should search upward in the document. With the found text selected in Navigator 4, you can then use the document.getSelection( ) method to grab a copy of the found text. You don't, however, have nearly the dynamic content abilities afforded by Internet Explorer 4's TexTRange object (for Win32).


Returned Value

Boolean value: true if a match was found; false if not.


Parameters


searchString

String for which to search the document.


matchCase

Boolean value: true to allow only exact, case-sensitive matches; false (default) to use case-insensitive search.


searchUpward

Boolean value: true to search from the current selection position upward through the document; false (default) to search forward from the current selection position.


Brings the window to the front of all regular browser windows and fires the onFocus event (in IE). If another window had focus at the time, that other window receives an onBlur event.


Returned Value

None.


Parameters

None.


Navigates one step forward through the history list of the window or frame. If the forward history has no entries, no action takes place.


Returned Value

None.


Parameters

None.


new GeckoActiveXObject(" programID")

A Mozilla constructor function specifically designed to allow the browser to open the Windows Media Player ActiveX control (and no other ActiveX controls). For implementation details, visit http://developer.mozilla.org/en/docs/Windows_Media_in_Netscape.


Returned Value

Reference to the player for further script control.


Parameters


programID

Identifier of the desired Windows Media Player control.


getComputedStyle( elementNodeReference, " pseudoElementName")

Returns a style object (specifically, a CSSStyleDeclaration object in the W3C DOM terminology) showing the net cascade of style settings that affect the element passed as the first parameter. To retrieve a particular style attribute value (including a value inherited from the default browser style sheet), use the getPropertyValue( ) method of the style object returned from this method:

 var compStyle = getComputedStyle(document.getElementById("myP"), ""); var pBGColor = compStyle.getPropertyValue("background-color"); 

See the style object for additional details. Although Mozilla and Opera allow access to this method via the window object, the W3C DOM prefers access through document.defaultView.getComputedStyle( ).


Returned Value

style (CSSStyleDeclaration) object reference.


Parameters


elementNodeReference

Reference to an element node in the document tree that becomes the selection.


pseudoElementName

String name of a pseudo-element (e.g., :first-line) or an empty string.


Returns a selection object in Mozilla and Opera, which can then be turned into a W3C DOM Range object. This method takes the place of the old document.getSelection( ) method, which is deprecated in Mozilla. Safari returns only the selected text. The corresponding IE operation is the document.selection property. See the selection object for details on working with a selection.


Returned Value

selection object reference.


Parameters

None.


Navigates to the URL designated as the home page for the browser. This is the same as the user clicking on the Home button.


Returned Value

None.


Parameters

None.


moveBy( deltaX, deltaY)

This is a convenience method that shifts the location of the window by specified pixel amounts along both axes. To shift along only one axis, set the other value to zero. Positive values for deltaX shift the window to the right; negative values to the left. Positive values for deltaY shift the window downward; negative values upward.


Returned Value

None.


Parameters


deltaX

Positive or negative pixel count of the change in horizontal direction of the window.


deltaY

Positive or negative pixel count of the change in vertical direction of the window.


moveTo( x, y)

This is a convenience method that shifts the location of the current window to a specific coordinate point. The moveTo( ) method uses the screen coordinate system.


Returned Value

None.


Parameters


x

Positive or negative pixel count relative to the top of the screen.


y

Positive or negative pixel count relative to the left edge of the screen.


navigate( URL)

Loads a new document into the window or frame. This is the IE-specific way of assigning a value to the window.location.href property.


Returned Value

None.


Parameters


URL

A complete or relative URL as a string.


open(" URL", " windowName"[, " windowFeatures"])


open(" URL", " windowName"[, " windowFeatures"][, replaceFlag])

Opens a new window (without closing the original one). You can specify a URL to load into the new window or set that parameter to an empty string to allow scripts to document.write( ) into that new window. The windowName parameter lets you assign a name that can be used by target attributes of link and form elements. This name is not to be used in script references as frame names are. Instead, a script reference to a subwindow must be to the window object returned by the window.open( ) method. Therefore, if your scripts must communicate with a window opened in this manner, it is best to save the returned value as a global variable so that future statements can use it.

A potential problem with subwindows is that they can be buried under the main window if the user clicks on the main window (or a script gives it focus). Any script that opens a subwindow should also include a focus( ) method for the subwindow to make sure it comes to the front in case it is already open. Subsequent invocations of the window.open( ) method in which the windowName parameter is the same as an earlier call automatically address the previously opened window, even if it is underneath the main window (and thus without bringing the window to the front).

The optional third parameter gives you control over various physical attributes of the subwindow. The windowFeatures parameter is a single string consisting of a comma-delimited list (without spaces between items) of attribute/value pairs:

 newWindow = window.open("someDoc.html","subWind", "status,menubar,height=400,width=300"); newWindow.focus( ); 

By default, all window attributes are turned on and the subwindow opens to the same size that the browser would use to open a new window from the File menu. But if your script specifies even one attribute, all settings are turned off. Therefore, use the windowFeatures parameter to specify those features that you want turned on.

If you encounter problems referencing a subwindow immediately after it is created, the problem is most likely a timing issue (affecting IE for Windows more than others). Script statements seem to want to reference the window before it exists completely. To work around the problem, place the code that works with the subwindow in a separate function, and invoke that function via the setTimeout( ) method, usually with no more than 50 milliseconds needed.

Managing multiple windows through scripts can be difficult. Security restrictions across domains frequently foil the best intentions. Most browsers have pop-up window blocking engaged, which may thwart your effort to open a separate window triggered by the load and unload events. In Opera, the new window is restricted to live within the main application window, behaving very differently from other browsers. Users aren't always fond of windows appearing and hiding on their own. If your audience uses newer browsers, consider simulating windows with positioned elements.


Returned Value

Window object reference.


Parameters


URL

A complete or relative URL as a string. If an empty string, no document loads into the window.


windowName

An identifier for the window to be used by target attributes. This is different from the title attribute of the document that loads into the window.


windowFeatures

A string of comma-delimited features to be turned on in the new window. Do not put spaces after the comma delimiters. The list of possible features is long, but a number of them are specific to Navigator 4 or later and require signed scripts because they are potentially a privacy and security concern to unsuspecting users. The features are listed as follows. To turn on a window feature, simply include its case-insensitive name in the comma-separated list. Only attributes specifying dimensions require values be assigned.

Attribute

IE

Mozilla

Safari

Opera

Description

alwaysLowered

n/a

<1.7

n/a

n/a

Always behind all other browser windows. Signed script required.

alwaysRaised

n/a

<1.7

n/a

n/a

Always in front of all other browser windows. Signed script required.

channelMode

4

n/a

n/a

n/a

Show in theater mode with channel band.

chrome

n/a

1.7

n/a

n/a

Displays content with no chrome, user interface features or keyboard commands. Signed script required.

close

n/a

all

n/a

n/a

For dialog type, set to no to remove close box. Signed script required.

copyhistory

3

all

n/a

n/a

Copy history listing from opening window to new window.

dependent

n/a

all

n/a

n/a

Subwindow closes if the window that opened it closes.

dialog

n/a

1.2

n/a

n/a

Window controls for minimize and maximize hidden.

directories

3

all

n/a

n/a

Display directory buttons.

fullscreen

4

n/a

n/a

n/a

Display no titlebar or menus

height

3

all

all

7

Window height in pixels.

hotkeys

n/a

all

n/a

n/a

Disables menu keyboard shortcuts (except Quit and Security Info).

innerHeight

n/a

all

n/a

n/a

Content region height. Signed script required for very small measures.

innerWidth

n/a

all

n/a

n/a

Content region width. Signed script required for very small measures.

left

4

all

all

n/a

Offset of window's left edge from left edge of screen.

location

3

all

all

n/a

Display Location (or Address) text field.

menubar

3

all

n/a

n/a

Display menubar (a menubar is always visible on Mac).

minimizable

n/a

1.2

n/a

n/a

For dialog type, includes minimize control.

modal

n/a

1.2

n/a

n/a

Open window as a modal. Signed script required.

outerHeight

n/a

all

n/a

n/a

Total window height. Signed script required for very small measures.

outerWidth

n/a

all

n/a

n/a

Total window width. Signed script required for very small measures.

personalbar

n/a

all

n/a

n/a

Mozilla-specific alternate to the directories attribute.

resizable

3

all

all

n/a

Allow window resizing (always allowed on Mac).

screenX

n/a

all

n/a

n/a

Offset of window's left edge from left edge of screen. Signed script required to move window offscreen.

screenY

n/a

all

n/a

n/a

Offset of window's top edge from top edge of screen. Signed script required to move window offscreen.

scrollbars

3

all

all

n/a

Display scrollbars if document is too large for window.

status

3

all

n/a

n/a

Display status bar.

titlebar

n/a

all

n/a

n/a

Displays titlebar. Set this value to no to hide the titlebar. Signed script required.

toolbar

3

all

n/a

n/a

Display toolbar (with Back, Forward, and other buttons).

top

4

all

all

7

Offset of window's top edge from top edge of screen.

width

3

all

all

n/a

Window width in pixels.

z-lock

n/a

all

n/a

n/a

New window is fixed below browser windows. Signed script required.



replaceFlag

Boolean value (for IE only) that controls the effect of the new window's URL on the global history of the browser. Set to true to replace the current page with the new window's URL (so that the current page won't be accessed through the Back button); set to false to add the new window's URL to the history, as normal.


openDialog(" URL", " windowName"[, " windowFeatures"][, arg1[, arg2[, ...]]])

For use in XUL extensions only (due to security reasons), this method is a variation on the window.open( ) method, offering slightly different ways of handling window features as well as allowing the passage of one or more arguments to the new window (similar to the IE showModalDialog( ) method). Arguments are accessible in the document loaded into the subwindow via the window.arguments property.


Returned Value

Window object reference.


Parameters


URL

A complete or relative URL as a string. If an empty string, no document loads into the window.


windowName

An identifier for the window to be used by target attributes. This is different from the title attribute of the document that loads into the window.


windowFeatures

A string of comma-delimited features to be turned on in the new window. See window.open( ) for details. An additional feature, all, displays (all=yes) or hides (all=no) window features except chrome, dialog, and modal (although each of these may be controlled independently).


arg1, arg2

JavaScript values of any type. Scripts in the subwindow access the values as items in the window.arguments array.


Starts the printing process for the window or frame. A user must still confirm the print dialog box to send the document to the printer. This method is the same as clicking the browser's Print button or selecting Print from the File menu.


Returned Value

None.


Parameters

None.


prompt(" message", " defaultReply")

Displays a dialog box with a message, a one-line text entry field, and two clickable buttons. Script execution halts while the dialog box appears. The message should urge the user to enter a specific kind of answer. One button indicates a Cancel operation; the other button indicates the user's approval of the text entered into the field (OK or Yes). The text of the buttons is not scriptable. A click of the Cancel button returns a value of null; a click of the OK button returns a string of whatever is in the text entry field at the time (including the possibility of an empty string). It is up to your scripts to test for the type of response (if any) supplied by the user.


Returned Value

When clicking the OK button, a string of the text entry field; when clicking Cancel, null.


Parameters


message

Any string.


defaultReply

Any string that suggests an answer. Always supply a value, even if an empty string.


releaseEvents( eventTypeList)

The opposite of window.captureEvents( ), this method turns off event capture at the window level for one or more specific events named in the parameter list. Although this method is part of the Navigator 4 event model, it is supported in Mozilla, Safari, and Opera, creating the equivalent of a W3C DOM capture-mode event listener for the document object. Continue to use this method if you must support Navigator 4, but migrate new code to the W3C DOM event listener syntax as described in Online Section VI. Mozilla's documentation now calls this method obsolete.


Returned Value

None.


Parameters


eventTypeList

A comma-separated list of case-sensitive event types as derived from the available Event object constants, such as Event.CLICK or Event.MOUSEMOVE.


removeEventListener(" eventType", listenerFunction, useCapture)

Although the window object as we know it is not officially part of the W3C DOM, mainstream W3C DOM browsers implement this W3C DOM event model method for the window object. See the removeEventListener( ) method discussion among the shared methods described earlier in this chapter.


resizeBy( deltaX, deltaY)

This is a convenience method that shifts the width and height of the window by specified pixel amounts. To adjust along only one axis, set the other value to zero. Positive values for deltaX make the window wider; negative values make the window narrower. Positive values for deltaY make the window taller; negative values make the window shorter. The top and left edges remain fixed; only the right and bottom edges are moved.


Returned Value

None.


Parameters


deltaX

Positive or negative pixel count of the change in horizontal dimension of the window.


deltaY

Positive or negative pixel count of the change in vertical dimension of the window.


resizeTo( x, y)

This is a convenience method that adjusts the height and width of the window to specific pixel sizes. The top and left edges of the window remain fixed, while the bottom and right edges move in response to this method.


Returned Value

None.


Parameters


x

Width in pixels of the window.


y

Height in pixels of the window.


routeEvent( event)

Used inside an event handler function, this method directs Navigator 4 (only) to let the event pass to its intended target object.


Returned Value

None.


Parameters


event

A Navigator 4 event object.


scroll( x, y)

Sets the scrolled position of the document inside the current window or frame. To return the document to its unscrolled position, set both parameters to zero.


Returned Value

None.


Parameters


x

Horizontal measure of scrolling within the window.


y

Vertical measure of scrolling within the window.


scrollBy( deltaX, deltaY)

Scrolls the document in the window by specified pixel amounts along both axes. To adjust along only one axis, set the other value to zero. Positive values for deltaX scroll the document to the left (so the user sees content to the right in the document); negative values scroll the document to the right. Positive values for deltaY scroll the document upward (so the user sees content lower in the document); negative values scroll the document downward. Scrolling does not continue past the zero coordinate points.


Returned Value

None.


Parameters


deltaX

Positive or negative pixel count of the change in horizontal scroll position.


deltaY

Positive or negative pixel count of the change in vertical scroll position.


scrollByLines( intervalCount) scrollByPages( intervalCount)

Scroll the document in the window downward (positive value) or upward (negative value) by the increment of lines or pages. The methods perform the same actions as the user clicking on the arrow and "page" regions of the vertical scrollbar, respectively.


Returned Value

None.


Parameters


intervalCount

Positive or negative count of the change in vertical scroll position. Units are governed by the method choice (lines or pages).


scrollTo( x, y)

Scrolls the document in the window to a specific scrolled pixel position.


Returned Value

None.


Parameters


x

Horizontal position in pixels of the window.


y

Vertical position in pixels of the window.


setInterval(" scriptExpression", msecs[, language])


setInterval( functionReference, msecs[, arg1, ..., argN])

Starts a timer that continually invokes the expression every msecs. Other scripts can run in the time between calls to expression. This method is useful for starting animation sequences that must reposition an element along a path at a fixed rate of speed. A repetitive call to an animation function would look like the following:

 intervalID = setInterval("advanceAnimation( )", 500); 

The parameter situation can be confusing. The simplest, most cross-browser approach is to invoke a script function (as a string), with the interval time (in milliseconds) as the second parameter. Any script expression will execute, but the expression is evaluated at the time the setInterval( ) method is invoked. Therefore, if you concatenate variables into this expression, their values must be ready when the setInterval( ) method runs, even though the variables won't be used until some milliseconds later.

IE permits a third parameter to specify a different scripting language in which the expression is to run. Unless it is a VBScript expression, you can omit this parameter. You may also substitute a function reference (not a string) as the first parameter, and pass a comma-delimited list of parameters that go to the function call. These parameters go after the msecs time, and they can be any data types.

This method returns an ID that should be saved as a global variable and be available as the parameter for the clearInterval( ) method to stop the looping timer. Unless you explicitly clear the interval process, it will continue to execute until the page unloads.


Returned Value

Integer acting as an identifier for this repetitive process.


Parameters


scriptExpression

Any script expression as a string, but most commonly a function. The function name with parentheses is placed inside the parameter's quoted string.


functionReference

Nonstring function reference (function name without the parentheses) or anonymous function.


msecs

The time in milliseconds between invocations of the expression or functionReference.


args

An optional comma-delimited list of parameters to be passed to a function used as the functionReference parameter. Navigator only.


language

An optional scripting language specification of the expression parameter (default is JavaScript). IE for Windows only.


setTimeout(" scriptExpression", msecs[, language]) setTimeout( functionReference, msecs[, arg1, ..., argN])

Starts a one-time timer that invokes the scriptExpression or functionReference after a delay of msecs. Other scripts can run while the browser waits to invoke the expression. A statement that sets the timer would look like the following:

 timeoutID = setTimeout("finishWindow( )", 50); 

The parameter situation can be confusing. The simplest, most cross-browser approach is to invoke a script function (as a string), with the interval time (in milliseconds) as the second parameter. Any script expression will execute, but the expression is evaluated at the time the setTimeout( ) method is invoked. Therefore, if you concatenate variables into this expression, their values must be ready when the setTimeout( ) method runs, even though the variables won't be used until some milliseconds later.

IE permits a third parameter to specify a different scripting language in which the expression is to run. Unless it is a VBScript expression, you can omit this parameter. You may also substitute a function reference (not a string) as the first parameter, and pass a comma-delimited list of parameters that go to the function call. These parameters go after the msecs time, and they can be any data types.

This method returns an ID that should be saved as a global variable and be available as the parameter for the clearTimeout( ) method to stop the timer before it expires and invokes the delayed action.

The setTimeout( ) method can be made to behave like the setInterval( ) method in some constructions. If you place a setTimeout( ) method as the last statement of a function and direct the method to invoke the very same function, you can create looping execution with a timed delay between executions. This is how earlier browsers (before the setInterval( ) method was available) scripted repetitive tasks, such as displaying updated digital clock displays in form fields or the status bar.


Returned Value

Integer acting as an identifier.


Parameters


scriptExpression

Any script expression as a string, but most commonly a function. The function name with parentheses is placed inside the parameter's quoted string.


functionReference

Nonstring function reference (function name without the parentheses) or anonymous function.


msecs

The time in milliseconds that the browser waits before invoking the expression.


args

An optional comma-delimited list of parameters to be passed to a function used as the functionReference parameter. Navigator only.


language

An optional scripting language specification of the expression parameter (default is JavaScript). IE for Windows only.


showHelp(" URL")

Displays a WinHelp window with the .hlp document specified with the URL parameter.


Returned Value

None.


Parameters


URL

A complete or relative URL to a WinHelp formatted file as a string.


showModalDialog(" URL"[, arguments[, " features"]])

Displays a special window that remains atop all browser windows until the user explicitly closes the dialog window. This kind of window is different from the browser windows generated with the window.open( ) method. A modal dialog has no scriptable relationship with its opening window once the dialog window is opened. All values necessary for displaying content must be in the HTML document that loads into the window or be passed as parameters. The modal dialog may then have a script set its returnValue property, which becomes the value returned to the original script statement that opened the modal dialog box as the returned value of the showModalDialog( ) method.

You can pass arguments to the modal dialog by creating a data structure that best suits the data. For a single value, a string will do. For multiple values, you can create a string with a unique delimiter between values, or create an array and specify the array as the second parameter for the showModalDialog( ) method. A script in the document loaded into the modal dialog can then examine the window.dialogArguments property and parse the arguments as needed for its scripting purposes. See the dialogArguments property for an example.

The third optional parameter lets you set physical characteristics of the dialog window. These characteristics are specified in a CSS-style syntax. Dimensions for dialogWidth, dialogHeight, dialogLeft, and dialogTop should be specified in pixels. An example of a call to a modal dialog is as follows:

 var answer = window.showModalDialog("subDoc.html",argsVariable, "dialogWidth:300px; dialogHeight:200px; center:yes"); 

IE/Macintosh requires that dialog dimensions be at least 201 pixels along both axes.

Modal dialogs can present problems for scripts if the window loads a frameset. A script in one of the frames will likely not be able to reference the parent or top window to gain access to either the window's close( ) method or content in another frame.


Returned Value

The value (if any) assigned to the window.returnValue property in the document loaded into the modal dialog window.


Parameters


URL

A complete or relative URL as a string.


arguments

Data as a number, string, or array to be passed to the scripts in the document loaded into the modal dialog.


features

A string of semicolon-delimited style attributes and values to set the physical characteristics of the modal dialog. Available attributes are as shown in the following table.

Feature

Value

Description

center

yes | no | 1 | 0 | on | off

Center the dialog

dialogHeight

Length/units

Outer height of dialog

dialogLeft

Integer

Left pixel offset (overrides center)

dialogTop

Integer

Top pixel offset (overrides center)

dialogWidth

Length/units

Outer width of dialog

edge

raised | sunken

Transition style between border and content area

help

yes | no | 1 | 0 | on | off

Display help icon in titlebar

resizable

yes | no | 1 | 0 | on | off

Dialog is resizable

status

yes | no | 1 | 0 | on | off

Display status bar



showModelessDialog(" URL"[, arguments[, " features"]])

Displays a special window that remains atop all browser windows, yet allows the user to interact with other open windows and their content. Other than browser versions that support it, this method has the same parameters and characteristics as the showModalDialog( ) method. See that method for details.


Lets the browser determine the optimum window size to display the window's content. Suitable for subwindows that display a limited amount of information.


Returned Value

None.


Parameters

None.


Halts the download of external data of any kind. This method is the same as clicking the browser's Stop button.


Returned Value

None.


Parameters

None.


The xml object reflects the Microsoft proprietary xml element, creating a so-called XML data island inside an HTML document. This functionality has largely been replaced by the XMLHttpRequest object.


HTML Equivalent

<xml>


Object Model Reference

 [window.]document.getElementById("elementID") 


Object-Specific Properties

src
XMLDocument

Object-Specific Methods

None.


Object-Specific Events

None.


Contains the URL of the external XML document loaded into the data island. To load a new document after the fact, assign a new URL to this property.


Example

 document.getElementById("xmlData").src = "xml/latestResults.xml"; 


Value

Relative or complete URL string.


Default

None.


This is a reference to the Microsoft XML document object. This object resembles the W3C DOM core document object in many ways, but Microsoft provides a different syntax to read and write data from the object. See http://msdn.microsoft.com/xml/reference/xmldom/start.asp for details.


Example

 var xmlDoc = document.getElementById("XMLData").XMLDocument; 


Value

Reference to an MS XML document object.


Default

None.


The XMLHttpRequest object allows background communication between the currently loaded Web page and a server, without disturbing the current page. In typical usage, the server responds to a request or post of data from the browser and returns an XML document, which the instance of this object stores as one of its properties. Upon successful receipt of the XML document (as revealed by other properties), the browser's scripts can parse the XML data (using W3C DOM document tree properties and methods), usually to extract data for revising part of the current Web page. See Online Section VII for implementation details.

All browsers other than IE implement the XMLHttpRequest exclusively as a native scriptable object. IE 5 through 6 implemented the object as an ActiveX control, but IE 7 includes a native XMLHttpRequest object so that the same syntax instance creation syntax for other browsers (invoking the XMLHttpRequest( ) constructor function) now works for IE.

Beginning with version 1.8, Mozilla browsers added some properties, methods, and events that may find their way into other browsers in the future.


Object Model Reference

 new XMLHttpRequest( ) 


Object Properties

channel
multipart
readyState
responseBody
responseText
responseXML
status
statusText

Object Methods

abort( )
addEventListener( )
dispatchEvent( )
getAllResponseHeaders( )
geTResponseHeader( )
open( )
overrideMimeType( )
removeEventListener( )
send( )
setRequestHeader( )

Object Events

Event

IE/Windows

Mozilla

Safari

Opera

DOM

error

·

load

·

progress

·

readystatechange

·

·

·

·



Intended for XUL add-ons (and therefore requiring elevated access privileges), the channel property returns a reference to the communications channel that the XMLHttpRequest object will use for its communication with a server. You can view an example of this property in use at: http://developer.mozilla.org/en/docs/Changing_the_Priority_of_HTTP_Requests.


Value

Reference to an internal communications channel.


Default

Channel of the current XMLHttpRequest object.


Mozilla 1.8 and later allows multiple XML documents to be retrieved with a single request. To prepare the XMLHttpRequest object for this kind of transaction, set the multipart property to true. The server's first response must have a MIME type of multipart/x-mixed-replace. The XMLHttpRequest object will fire a load event after each part is received. Subsequent documents within the multipart stream are placed into the response variables one at a time.


Value

Boolean value: true | false.


Default

false


Returns an integer code corresponding to the current state of the object.


Value

Integer value with the following meanings:

Value

Meaning

0

Uninitialized (the open( ) method has not yet been invoked)

1

Loading (the send( ) method has not yet been invoked)

2

Loaded (the send( ) method has been invoked, and header and status properties are ready for reading)

3

Interactive (the transfer is in progress, partial data available)

4

Complete (all transfer operations are finished)



Default

0


Returns the body of the response in a form Microsoft calls "an array of unsigned bytes." The data is not a JavaScript value type, and therefore of little or no value to web page authors.


Value

Byte array.


Default

None.


Returns the received data in string form.


Value

String.


Default

None.


Returns the received data in the form of an XML document object. You can use DOM node tree parsing techniques (including E4X capabilities in Mozilla, as described in Chapter 5) to extract data as needed for display in the web page or further calculations.


Value

Document object.


Default

None.


Returns an integer that is the response code received from the server. Typical response codes are 200 (for "OK") and 404 (for "Not Found"). A value of 200 means that the server has sent the content from the URL passed as a parameter to the get( ) method. This property is one way to test for successful completion of a transaction.


Value

Integer.


Default

0


Returns the text portion of the status code returned from the server, such as OK and Not Found. If you use the status property in your code, and you receive a number you don't understand, read the statusText property to get a more plain-language description of the problem.


Value

String.


Default

Empty string.


Invoked after the send( ) method, the abort( ) method cancels the current request. The status property is set to zero.


Returned Value

None.


Parameters

None.


Mozilla offers the DOM-standard way of managing events bound to the XMLHttpRequest object, partly because there are more possible events to bind (load, error, and (starting in 1.8) progress) than only the readystatechange implemented in all supporting browsers. Of special interest to this object, you must invoke addEventListener( ) only after the get( ) method because the latter method removes all pending event listeners. See the descriptions of these three methods among the shared items at the beginning of this chapter.


Returns the complete set of headers received from the server. A header consists of several name/value pairs (in the form name: value), each of which is delimited by carriage return and linefeed characters. Here is an example:

 ETag: "633bfe1-439-3d7a7301" Content-Length: 1081 Keep-Alive: timeout=15, max=98 Content-Type: application/xml Last-Modified: Sat, 07 Sep 2002 21:43:29 GMT 

Note that there is a CR/LF sequence after the final name/value pair.


Returned Value

String.


Parameters

Empty string.


getResponseHeader(" headerName")

Returns only the value of a specific header field whose name matches the value passed as a parameter to the method.


Returned Value

String.


Parameters


headerName

String consisting of the name of a particular header name/value pair. Do not include the colon delimiter of the name/value pair.


open(" method", " URI"[, asyncFlag[, " username"[, " password"]]])

Sets key parameters of the request in preparation of the actual request (which occurs via the send( ) method).


Returned Value

None.


Parameters


method

The HTTP method to be used as a string. Use GET for a typical data request; or POST for submitting lengthy data and SOAP commands.


URI

The Uniform Resource Identifier of the remote data or service, as a string.


asyncFlag

Boolean value that directs the request to be made synchronously (false) or asynchronously (TRue). A synchronous request puts your scripts in peril of locking up if there is a server or network malfunction. Use an asynchronous, and let the readystatechange or load events trigger scripts that act on the received content. The default is TRue.


username

A string containing a user name, if required for authentication. But be careful when including sensitive information in a script that could be viewed by others.


password

A string containing a password, if required for authentication. But be careful when including sensitive information in a script that could be viewed by others.


overrideMimeType(" MIMEType")

Invoke between the get( ) and send( ) methods to force the object to apply the specified MIME type to the data received from the server. This may be necessary when the server is not configured to identify its output as an XML content type (e.g., text/xml).


Returned Value

None.


Parameters


MIMEType

The desired content type, as a string. For the XMLHttpRequest object to load data into the responseXML property, the data must be received as a valid XML content type, such as text/xml, or overridden with this method to reach the same end.


send( data)

Transmits data to the server through specifications established in the previous open( ) method.


Returned Value

None.


Parameters


data

Data sent with the request can be in one of two forms for all supporting browsers and one extra form for IE. The two forms accepted by both are either a string or a DOM document object (e.g., a document generated via the document.implementation.createDocument( ) method). The latter is internally serialized (made into a string) before transmission. IE also allows byte arrays to be specified as the data. Data does not contain header information, which is set via the setRequestHeader( ) method.


setRequestHeader(" headerLabel", " value")

Invoked between the open( ) and send( ) methods, this method lets your script assign one or more header name/value pairs to the data that is about to be sent.


Returned Value

None.


Parameters


headerLabel

Name portion of the name/value pair for the header, as a string.


value

Value portion of the name/value pair for the header, as a string.


The XMLSerializer object transforms an XML document or node object into a string value consisting of all the markup. Browsers use this object internally for tasks such as converting XML content into a string that is sent as data via the XMLHttpRequest.send( ) method. But the object is available to your scripts, if needed for other tasks. Mozilla exposes the serializeToStream( ) method of the object, but one of the method's parameters is a data type (output stream) not available to client-side scripts associated with web pages.


Object Model Reference

 new XMLSerializer( ) 


Object Properties

None.


Object Methods

serializeToString( )

Object-Specific Events

None.


serializeToString( DOMNode)

Returns a string consisting of the markup comprising the DOM node passed as a parameter. This node can be either an entire document (nodeType of 9) or other node type, including a document fragment. The exception is Safari prior to 2.0.2, which worked only on complete document nodes.


Returned Value

String.


Parameters


DOMNode

An XML node object of any type (see above for Safari exception).


See pre.




Dynamic HTML. The Definitive Reference
Dynamic HTML: The Definitive Reference
ISBN: 0596527403
EAN: 2147483647
Year: 2004
Pages: 120
Authors: Danny Goodman

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net