Client-Side JavaScript Reference: Chapter 25 - JavaScript: The Definitive Guide

by David Flanagan

This part of the book is a reference section that documents the classes, methods, properties, and event handlers defined in client-side JavaScript. This introduction and the sample reference page found at the beginning of Part III, “Core JavaScript Reference” explain how to use and get the most out of this reference section. Take the time to read this material carefully, and you will find it easier to locate and use the information you need!

JavaScript: The Definitive Guide book cover

This excerpt is from JavaScript: The Definitive Guide. The indispensable reference for JavaScript programmers since 1996, JavaScript: The Definitive Guide, 5th Edition is completely revised and expanded to cover JavaScript as it is used in today's Web 2.0 applications.

buy button

This reference section is arranged alphabetically. The reference pages for the methods and properties of classes are alphabetized by their full names, which include the names of the classes that define them. For example, if you want to read about the submit( ) method of the Form class, you would look under "Form.submit," not just "submit."

Most client-side JavaScript properties do not have reference pages of their own (all methods and event handlers do have their own reference pages, however). Instead, simple properties are completely documented in the reference page for the class that defines them. For example, you can read about the images[] property of the HTMLDocument class in the HTMLDocument reference page. Nontrivial properties that require substantial explanation do have reference pages of their own, and you'll find a cross-reference to these pages within the reference page of the class or interface that defines the properties. For example, when you look up the cookie property in the HTMLDocument reference page, you'll find a short description of the property and a reference to more information under HTMLDocument.cookie.

Client-side JavaScript has a number of global properties and functions, such as window, history, and alert( ). In client-side JavaScript, a Window object serves as the global object, and the "global" properties and functions of client-side JavaScript are actually properties of the Window class. Therefore, global properties and functions are documented in the Window reference page or under names such as Window.alert( ).

Once you've found the reference page you're looking for, you shouldn't have much difficulty finding the information you need. Still, you'll be able to make better use of this reference section if you understand how the reference pages are written and organized. Part III, “Core JavaScript Reference” begins with an a sample reference page titled "Sample Entry." That entry explains the structure of each reference page and tells how to find the information you need within a reference page.

Name

Anchor: the target of a hypertext link — DOM Level 0: Node → Element → HTMLElement → Anchor

Properties

Stringname

Contains the name of an Anchor object. The value of this property is set by the name attribute of the <a> tag.

Methods

focus( )

Scrolls the document so the location of the anchor is visible.

HTML Syntax

An Anchor object is created by any standard HTML <a> tag that contains a name attribute:

<a name="name">  // Links may refer to this anchor by this name
    ...

</a>

Description

An anchor is a named location within an HTML document. Anchors are created with an <a> tag that has a name attribute specified. The Document object has an anchors[] array property that contains Anchor objects that represent each of the anchors in the document. Anchor objects can be referenced by index or by name within this array.

You can make a browser display the location of an anchor by setting the hash property of the Location object to a # character followed by the name of the anchor or by simply calling the focus( ) method of the Anchor object itself.

Note that the <a> tag used to create anchors is also used to create hypertext links. Although hypertext links are often called anchors in HTML parlance, they are represented in JavaScript with the Link object, not with the Anchor object.

Example

// Scroll the document so the anchor named "_bottom_" is visible
document.anchors['_bottom_'].focus( );

See Also

Document, Link, Location


Name

Anchor.focus( ): scroll to make the anchor location visible — DOM Level 0:

Synopsis

void focus( );

Description

This method scrolls the document so the location of the Anchor object is visible.


Name

Applet: an applet embedded in a web page — DOM Level 0:

Synopsis

document.applets[i]

document.appletName

Properties

The Applet object has properties that mirror the HTML attributes of the <applet> tag (see HTMLElement for details). It also has properties corresponding to the public fields of the Java applet it represents.

Methods

The methods of an Applet object are the same as the public methods of the Java applet it represents.

Description

The Applet object represents a Java applet embedded in an HTML document. The Applet objects of a document may be obtained through the applets[] collection of the Document object.

The properties of the Applet object represent the public fields of the applet, and the methods of the Applet object represent the public methods of the applet. Remember that Java is a strongly typed language. This means that each field of an applet has been declared to have a specific data type, and setting it to a value of some other type causes a runtime error. The same is true of applet methods: each argument has a specific type, and arguments cannot be omitted as they can be in JavaScript. See Chapter 23, Scripting Java Applets and Flash Movies for further details.


Name

Attr: an attribute of a document element — DOM Level 1 Core: Node → Attr

Properties

readonly String name

The name of the attribute.

readonly Element ownerElement [DOM Level 2]

The Element object that contains this attribute, or null if the Attr object is not currently associated with any Element.

readonly boolean specified

true if the attribute is explicitly specified in the document source or set by a script; false if the attribute is not explicitly specified but a default value is specified in the document's DTD.

String value

The value of the attribute. When reading this property, the attribute value is returned as a string. When you set this property to a string, it automatically creates a Text node that contains the same text and makes that Text node the sole child of the Attr object.

Description

An Attr object represents an attribute of an Element node. Attr objects are associated with Element nodes but are not directly part of the document tree (and have a null parentNode property). You can obtain an Attr object through the attributes property of the Node interface or by calling the getAttributeNode( ) or getAttributeNodeNS( ) methods of the Element interface.

The value of an attribute is represented by the descendant nodes of an Attr node. In HTML documents, an Attr node always has a single Text node child, and the value property provides a shortcut for reading and writing the value of this child node.

The XML grammar allows XML documents to have attributes that consist of Text nodes and EntityReference nodes, which is why an attribute value cannot be fully represented by a string. In practice, however, web browsers expand any entity references in XML attribute values and do not implement the EntityReference interface (which is not documented in this book). Therefore, in client-side JavaScript, the value property is all that is needed to read and write attribute values.

Since attribute values can be completely represented by strings, it is not usually necessary to use the Attr interface at all. In most cases, the easiest way to work with attributes is with the Element.getAttribute( ) and Element.setAttribute( ) methods. These methods use strings for attribute values and avoid the use of Attr nodes altogether.

See Also

Element


Name

Button: see Input


Name

Canvas: an HTML element for scripted drawing — Firefox 1.5, Safari 1.3, Opera 9: Node → Element → HTMLElement → Canvas

Properties

String height

The height of the canvas. As with an image, this may be specified as an integer pixel value or percentage of the window height. When this value is changed, any drawing that has been done in the canvas is erased. The default value is 300.

String width

The width of the canvas. As with an image, this may be specified as an integer pixel value or percentage of the window width. When this value is changed, any drawing that has been done in the canvas is erased. The default value is 300.

Methods

getContext( )

Returns a CanvasRenderingContext2D object with which to draw on the canvas. You must pass the string "2d" to this method to specify that you want to do two-dimensional drawing.

Description

The Canvas object represents an HTML canvas element. It has no behavior of its own but defines an API that supports scripted client-side drawing operations. You may specify the width and height directly on this object, but most of its functionality is available via the CanvasRenderingContext2D object. This is obtained by calling the getContext( ) method of the Canvas object and passing the literal string "2d" as the sole argument.

The <canvas> tag was introduced in Safari 1.3 and, at this writing, is also supported in Firefox 1.5 and Opera 9. The <canvas> tag, and its API, can be simulated in IE with the ExplorerCanvas open source project at http://excanvas.sourceforge.net/.

See Also

CanvasRenderingContext2D; Chapter 22, Scripted Client-Side Graphics


Name

Canvas.getContext( ): return a context for drawing on the canvas

Synopsis

CanvasRenderingContext2D getContext(StringcontextID)

Arguments

contextID

This argument specifies the type of drawing you want to do with the canvas. Currently the only valid value is "2d", which specifies two-dimensional drawing and causes this method to return a context object that exports a 2-D drawing API.

Returns

A CanvasRenderingContext2D object with which you can draw into the Canvas element.

Description

Returns a context representing the type of context to use in drawing. The intent is to provide different contexts for different drawing types (2-D, 3-D). Currently, the only one supported is "2d", which returns a CanvasRenderingContext2D object that implements most of the methods used by a canvas.

See Also

CanvasRenderingContext2D


Name

CanvasGradient: a color gradient for use in a canvas — Firefox 1.5, Safari 1.3, Opera 9: Object → CanvasGradient

Methods

addColorStop( )

Specifies a color and position for the gradient.

Description

A CanvasGradient object represents a color gradient that may be assigned to both the strokeStyle and fillStyle properties of a CanvasRenderingContext2D object. The createLinearGradient( ) and createRadialGradient( ) methods of CanvasRenderingContext2D both return CanvasGradient objects.

Once you have created a CanvasGradient object, use addColorStop( ) to specify what colors should appear at what positions within the gradient. Between the positions you specify, colors are interpolated to create a smooth gradient or fade. Transparent black stops are created implicitly at the start and end points of the gradient.

See Also

CanvasRenderingContext2D.createLinearGradient( )
CanvasRenderingContext2D.createRadialGradient( )

Name

CanvasGradient.addColorStop( ): add a change of color at some point in the gradient

Synopsis

void addColorStop(floatoffset, String color)

Arguments

offset

A floating-point value in the range 0.0 to 1.0 that represents a fraction between the start and end points of the gradient. An offset of 0 corresponds to the start point, and an offset of 1 corresponds to the end point.

color

Specifies the color to be displayed at the specified offset, as a CSS color string. Colors at other points along the gradient are interpolated based on this and any other color stops.

Description

addColorStop( ) provides the mechanism for describing color changes in a gradient. This method may be called one or more times to change the color at particular percentages between the gradient's start and end points.

If this method is never called on a gradient, the gradient is transparent. At least one color stop must be specified to produce a visible color gradient.


Name

CanvasPattern: an image-based pattern for use in a Canvas — Firefox 1.5, Safari 1.3, Opera 9: Object → CanvasPattern

Description

A CanvasPattern object is returned by the createPattern( ) method of a CanvasRenderingContext2D object. A CanvasPattern object may be used as the value of the strokeStyle and fillStyle properties of a CanvasRenderingContext2D object.

A CanvasPattern object has no properties or methods of its own. See CanvasRenderingContext2D.createPattern( ) for details on how to create one.

See Also

CanvasRenderingContext2D.createPattern( )


Name

CanvasRenderingContext2D: the object used for drawing on a canvas — Firefox 1.5, Safari 1.3, Opera 9: Object → CanvasRenderingContext2D

Properties

readonly Canvas canvas

The Canvas element upon which this context will draw.

Object fillStyle

The current color, pattern, or gradient used for filling paths. This property may be set to a string or to a CanvasGradient or CanvasPattern object. When set to a string, it is parsed as a CSS color value and used for solid fills. When set to a CanvasGradient or CanvasPattern object, fills are done using the specified gradient or pattern. See CanvasRenderingContext2D.createLinearGradient( ), CanvasRenderingContext2D.createRadialGradient( ), and CanvasRenderingContext2D.createPattern( ).

float globalAlpha

Specifies the opacity of content drawn on the canvas. The range of values is between 0.0 (fully transparent) and 1.0 (no additional transparency). The default value for this property is 1.0.

String globalCompositeOperation

Specifies how colors being drawn are combined (or "composited") with colors already on the canvas. See the individual reference entry for this property for possible values.

String lineCap

Specifies how the ends of lines are rendered. Legal values are "butt", "round", and "square". The default is "butt". See the individual reference page for this property for further details.

String lineJoin

Specifies how two lines are joined. Legal values are "round", "bevel", and "miter". The default is "miter". See the individual reference page for this property for further details.

float lineWidth

Specifies the line width for stroking (line drawing) operations. The default is 1.0, and this property must be greater than 0.0. Wide lines are centered over the path, with half of the line width on each side.

float miterLimit

When the lineJoin property is "miter", this property specifies the maximum ratio of miter length to line width. See the individual reference page for this property for further details.

float shadowBlur

Specifies how much feathering shadows should have. The default is 0. Shadows are supported by Safari but not by Firefox 1.5 or Opera 9.

String shadowColor

Specifies the color of shadows as a CSS or web style string and may include an alpha component for transparency. The default is black. Shadows are supported by Safari but not by Firefox 1.5 or Opera 9.

float shadowOffsetX, shadowOffsetY

Specify the horizontal and vertical offset of the shadows. Larger values make the shadowed object appear to float higher above the background. The default is 0. Shadows are supported by Safari, but not by Firefox 1.5 or Opera 9.

Object strokeStyle

Specifies the color, pattern, or gradient used for stroking (drawing) paths. This property may be a string, or a CanvasGradient or a CanvasPattern object. If it is a string, it is parsed as a CSS color value and the stroking is done with the resulting solid color. If the value of this property is a CanvasGradient or a CanvasPattern object, stroking is done with a gradient or pattern. See CanvasRenderingContext2D.createLinearGradient( ), CanvasRenderingContext2D.createRadialGradient( ), and CanvasRenderingContext2D.createPattern( ).

Methods

arc( )

Adds an arc to the current subpath of a canvas, using a center point and radius.

arcTo( )

Adds an arc to the current subpath, using tangent points and a radius.

beginPath( )

Starts a new path (or a collection of subpaths) in a canvas.

bezierCurveTo( )

Adds a cubic Bézier curve to the current subpath.

clearRect( )

Erases the pixels in a rectangular area of a canvas.

clip( )

Uses the current path as the clipping region for subsequent drawing operations.

closePath( )

Closes the current subpath if it's open.

createLinearGradient( )

Returns a CanvasGradient object that represents a linear color gradient.

createPattern( )

Returns a CanvasPattern object that represents a tiled image.

createRadialGradient( )

Returns a CanvasGradient object that represents a radial color gradient.

drawImage( )

Draws an image.

fill( )

Paints or fills the interior of the current path with the color, gradient, or pattern specified by the fillStyle property.

fillRect( )

Paints or fills a rectangle.

lineTo( )

Adds a straight line segment to the current subpath.

moveTo( )

Sets the current position and begins a new subpath.

quadraticCurveTo( )

Adds a quadratic Bézier curve to the current subpath.

rect( )

Add a rectangle subpath to the current path.

restore( )

Resets the canvas to the graphics state most recently saved.

rotate( )

Rotates the canvas.

save( )

Saves the properties, clipping region, and transformation matrix of the CanvasRenderingContext2D object.

scale( )

Scales the user coordinate system of the canvas.

stroke( )

Draws, or strokes, a line following the current path. The line is drawn according to the lineWidth, lineJoin, lineCap, and strokeStyle properties, among others.

strokeRect( )

Draws (but does not fill) a rectangle.

translate( )

Translates the user coordinate system of the canvas.

Description

The CanvasRenderingContext2D object provides a set of graphics functions to draw on a canvas. While text support is unfortunately omitted, the functions available are quite rich. They fall into a number of categories.

Drawing rectangles

You can outline and fill rectangles with strokeRect( ) and fillRect( ). In addition, you can clear the area defined by a rectangle with clearRect( ).

Drawing images

In the Canvas API, images are specified using Image objects that represent HTML <img> elements or offscreen images created with the Image( ) constructor. (See the Image reference page for details.) A canvas object can also be used as an image source.

You can draw an image into a canvas with the drawImage( ) method, which, in its most general form, allows an arbitrary rectangular region of the source image to be scaled and rendered into the canvas.

Creating and rendering paths

A powerful feature of the canvas is its ability to build shapes up from basic drawing operations, then either draw their outlines (stroke them) or paint their contents (fill them). The operations accumulated are collectively referred to as the current path. A canvas maintains a single current path.

In order to build a connected shape out of multiple segments, a joining point is needed between drawing operations. For this purpose, the canvas maintains a current position. The canvas drawing operations implicitly use this as their start point and update it to what is typically their end point. You can think of this like drawing with a pen on paper: when finishing a particular line or curve, the current position is where the pen rested after completing the operation.

You can create a sequence of disconnected shapes in the current path that will be rendered together with the same drawing parameters. To separate shapes, use the moveTo( ) method; this moves the current position to a new location without adding a connecting line. When you do this, you create a new subpath, which is the canvas term used for a collection of operations that are connected.

Once the path is formed to your liking, you can draw its outline with stroke( ), paint its contents with fill( ), or do both.

The available shape operations are lineTo( ) for drawing straight lines, rect( ) for drawing rectangles, arc( ) or arcTo( ) for drawing partial circles, and bezierCurveTo( ) or quadraticCurveTo( ) for drawing curves.

In addition to stroking and filling, you can also use the current path to specify the clipping region the canvas uses when rendering. Pixels inside this region are displayed; those outside are not. The clipping region is cumulative; calling clip( ) intersects the current path with the current clipping region to yield a new region. Unfortunately, there is no direct method for resetting the clipping region to the extent of the canvas; to do so, you must save and restore the entire graphics state of the canvas (described later in this entry).

If the segments in any of the subpaths do not form a closed shape, fill( ) and clip( ) operations implicitly close them for you by adding a virtual (not visible with a stroke) line segment from the start to the end of the subpath. Optionally, you can call closePath( ) to explicitly add this line segment.

Colors, gradients, and patterns

When filling or stroking paths, you can specify how the lines or painted area are rendered using the fillStyle and strokeStyle properties. Both accept CSS-style color strings, as well as CanvasGradient and CanvasPattern objects that describe gradients and patterns. To create a gradient, use the createLinearGradient( ) or createRadialGradient( ) methods. To create a pattern, use createPattern( ).

To specify an opaque color using CSS notation, use a string of the form "#RRGGBB", where RR, GG, and BB are hexadecimal digits that specify the red, green, and blue components of the color as values between 00 and FF. For example, bright red is "#FF0000". To specify a partially transparent color, use a string of the form "rgba(R,G,B,A)". In this form, R, G, and B specify the red, green, and blue components of the color as decimal integers between 0 and 255, and A specifies the alpha (opacity) component as a floating-point value between 0.0 (fully transparent) and 1.0 (fully opaque). For example, half-transparent bright red is "rgba(255,0,0,0.5)".

Line width, line caps and line joins

Canvas offers several options for tailoring how lines appear. You can specify the width of the line with the lineWidth property, how the end points of lines are drawn with the lineCap property, and how lines are joined using the lineJoin property.

Coordinate space and transformations

By default, the coordinate space for a canvas has its origin at (0,0) in the upper-left corner of the canvas, with x values increasing to the right and y values increasing down. A single unit in this coordinate space normally translates to a single pixel.

You can, however, transform the coordinate space, causing any coordinates or extents you specify in drawing operations to be shifted, scaled, or rotated. This is done with the translate( ), scale( ), and rotate( ) methods, which affect the transformation matrix of the canvas. Because the coordinate space can be transformed like this, the coordinates you pass to methods such as lineTo( ) may not be measured in pixels. For this reason, the Canvas API uses floating-point numbers instead of integers.

Transformations are processed in reverse of the order in which they are specified. So, for example, a call to scale( ) followed by a call to translate( ) causes the coordinate system first to be translated, then scaled.

Compositing

Commonly, shapes are drawn on top of one another, with the new shape obscuring any shapes that were previously drawn below it. This is the default behavior in a canvas. However, you can perform many interesting operations by specifying different values for the globalCompositeOperation property. These range from XORing to lightening or darkening shaped regions; see CanvasRenderingContext2D.globalCompositeOperation for all the possible options.

Shadows

The Canvas API includes properties that can automatically add a drop shadow to any shape you draw. At the time of this writing, Safari is the only browser that implements this API, however. The color of the shadow may be specified with shadowColor, and its offset changed using shadowOffsetX and shadowOffsetY. In addition, the amount of feathering applied to the shadow's edge may be set with shadowBlur.

Saving graphics state

The save( ) and restore( ) methods allow you to save and restore the state of a CanvasRenderingContext2D object. save( ) pushes the current state onto a stack, and restore( ) pops the most recently saved state off the top of the stack and sets the current drawing state based on those stored values.

All properties of the CanvasRenderingContext2D object (except for the canvas property, which is a constant) are part of the saved state. The transformation matrix and clipping region are also part of the state, but the current path and current point are not.

See Also

Canvas


Name

CanvasRenderingContext2D.arc( ): add an arc to the current subpath of a canvas, using a center point and radius

Synopsis

void arc(floatx, float y, float radius, float startAngle, endAngle,
boolean counterclockwise)

Arguments

x, y

The coordinates of the center of the circle describing the arc.

radius

The radius of the circle describing the arc.

startAngle, endAngle

The angles that specify the start and end points of the arc along the circle. These angles are measured in radians. The three o'clock position along the positive X axis is an angle of 0, and angles increase in the clockwise direction.

counterclockwise

Whether the arc is traversed counterclockwise (true) or clockwise (false) along the circle's circumference.

Description

The first five arguments to this method describe specify a start point and an end point on the circumference of a circle. Invoking this method adds a straight line between the current point and the start point to the current subpath. Next it adds the arc along the circumference of the circle between the start and end points to the subpath. The final argument specifies the direction in which the circle should be traversed to connect the start and end points. This method leaves the current point set to the end point of the arc.

See Also

CanvasRenderingContext2D.arcTo( )
CanvasRenderingContext2D.beginPath( )
CanvasRenderingContext2D.closePath( )

Name

CanvasRenderingContext2D.arcTo( ): add an arc of a circle to the current subpath, using tangent points and a radius

Synopsis

void arcTo(floatx1, float y1, float x2, float y2, float radius)

Arguments

x1, y1

The coordinates of point P1.

x2, y2

The coordinates of point P2.

radius

The radius of the circle that defines the arc.

Description

This method adds an arc to the current subpath but describes that arc much differently than the arc( ) method does. The arc that is added to the path is a portion of a circle with the specified radius. The arc has one point tangent to the line from the current position to P1 and one point that is tangent to the line from P1 to P2. The arc begins and ends at these two tangent points and is drawn in the direction that connects those two points with the shortest arc.

In many common uses, the arc begins at the current position and ends at P2, but this is not always the case. If the current position is not the same as the starting point of the arc, this method adds a straight line from the current position to the start position of the arc. This method always leaves the current position set to the end point of the arc.

Example

You could draw the upper-right corner of a rectangle, giving it a rounded corner with code like the following:

c.moveTo(10,10);                 // start at upper left
c.lineTo(90, 10)                 // horizontal line to start of round corner
c.arcTo(100, 10, 100, 20, 10);   // rounded corner
c.lineTo(100, 100);              // vertical line down to lower right

Bugs

This method is not implemented in Firefox 1.5.

See Also

CanvasRenderingContext2D.arc( )


Name

CanvasRenderingContext2D.beginPath( ): start a new collection of subpaths in a canvas

Synopsis

void beginPath( )

Description

beginPath( ) discards any currently defined path and begins a new one. It sets the current point to (0,0).

When the context for a canvas is first created, beginPath( ) is implicitly called.

See Also

CanvasRenderingContext2D.closePath( )
CanvasRenderingContext2D.fill( )
CanvasRenderingContext2D.stroke( )
Chapter 22, Scripted Client-Side Graphics

Name

CanvasRenderingContext2D.bezierCurveTo( ): add a cubic Bézier curve to the current subpath

Synopsis

void bezierCurveTo(floatcpX1, float cpY1, float cpX2, float cpY2, float x,
float y)

Arguments

cpX1, cpX2

The coordinates of the control point associated with the curve's start point (the current position).

cpX2, cpY2

The coordinates of the control point associated with the curve's end point.

x, y

The coordinates of the curve's end point.

Description

bezierCurveTo( ) adds a cubic Bézier curve to the current subpath of a canvas. The start point of the curve is the current point of the canvas, and the end point is (x,y). The two Bezier control points (cpX1, cpY1) and (cpX2, cpY2) define the shape of the curve. When this method returns, the current position is (x,y).

See Also

CanvasRenderingContext2D.quadraticCurveTo( )


Name

CanvasRenderingContext2D.clearRect( ): erase a rectangular area of a canvas

Synopsis

void clearRect(floatx, float y,
              float width, float height)

Arguments

x, y

The coordinates of the upper-left corner of the rectangle.

width, height

The dimensions of the rectangle.

Description

clearRect( ) erases the specified rectangle, filling it with a transparent color.


Name

CanvasRenderingContext2D.clip( ): set the clipping path of a canvas

Synopsis

void clip( )

Description

This method clips the current path using the current clipping path and then uses the clipped path as the new clipping path. Note that there is no way to enlarge the clipping path. If you want a temporary clipping path, you should first call save( ) in order to use restore( ) to restore the original clipping path. The default clipping path for a canvas is the canvas rectangle itself.

This method resets the current path so that it is empty.


Name

CanvasRenderingContext2D.closePath( ): closes an open subpath

Synopsis

void closePath( )

Description

If the current subpath of the canvas is open, closePath( ) closes it by adding a line connecting the current point to the subpath's starting point. If the subpath is already closed, this method does nothing. Once a subpath is closed, no more lines or curves can be added to it. To continue adding to the path, you must begin a new subpath with a call to moveTo( ).

You do not need to call closePath( ) before stroking or filling a path. Paths are implicitly closed when filled (and also when you call clip( )).

See Also

CanvasRenderingContext2D.beginPath( )
CanvasRenderingContext2D.moveTo( )
CanvasRenderingContext2D.stroke( )
CanvasRenderingContext2D.fill( )

Name

CanvasRenderingContext2D.createLinearGradient( ): create a linear color gradient

Synopsis

CanvasGradient createLinearGradient(floatxStart, float yStart,
                                    float xEnd, float yEnd)

Arguments

xStart, yStart

The coordinates of the gradient's start point.

xEnd, yEnd

The coordinates of the gradient's end point.

Returns

A CanvasGradient object representing a linear color gradient.

Description

This method creates and returns a new CanvasGradient object that linearly interpolates colors between the specified start point and end point. Note that this method does not specify any colors for the gradient. Use the addColorStop( ) method of the returned object to do that. To stroke lines or fill areas using a gradient, assign a CanvasGradient object to the strokeStyle or fillStyle properties.

See Also

CanvasGradient.addColorStop( ), CanvasRenderingContext2D.createRadialGradient( )


Name

CanvasRenderingContext2D.createPattern( ): create a pattern of tiled images

Synopsis

CanvasPattern createPattern(Imageimage,
                            String repetitionStyle)

Arguments

image

The image to be tiled. This argument is typically an Image object, but you may also use a Canvas element.

repetitionStyle

Specifies how the image is tiled. The possible values are the following:

Value

Meaning

"repeat"

Tile the image in both directions. This is the default.

"repeat-x"

Tile the image in the X dimension only.

"repeat-y"

Tile the image in the Y dimension only.

"no-repeat"

Do not tile the image; use it a single time only.

Returns

A CanvasPattern object representing the pattern.

Description

This method creates and returns a CanvasPattern object that represents the pattern defined by a tiled image. To use a pattern for stroking lines or filling areas, use a CanvasPattern object as the value of the strokeStyle or fillStyle properties.

Bugs

Firefox 1.5 supports only the "repeat" style. Others are ignored.

See Also

CanvasPattern


Name

CanvasRenderingContext2D.createRadialGradient( ): create a radial color gradient

Synopsis

CanvasGradient createRadialGradient(floatxStart, float yStart, float
radiusStart,
                                    float xEnd, float yEnd, float radiusEnd)

Arguments

xStart, yStart

The coordinates of the center of the starting circle.

radiusStart

The radius of the starting circle.

xEnd, yEnd

The coordinates of the center of the ending circle.

radiusEnd

The radius of the ending circle.

Returns

A CanvasGradient object representing a radial color gradient.

Description

This method creates and returns a new CanvasGradient object that radially interpolates colors between the circumferences of the two specified circles. Note that this method does not specify any colors for the gradient. Use the addColorStop( ) method of the returned object to do that. To stroke lines or fill areas using a gradient, assign a CanvasGradient object to the strokeStyle or fillStyle properties.

Radial gradients are rendered by using the color at offset 0 for the circumference of the first circle, the color at offset 1 for the second circle, and interpolated color values (red, green, blue, and alpha) at circles between the two.

See Also

CanvasGradient.addColorStop( ), CanvasRenderingContext2D.createLinearGradient( )


Name

CanvasRenderingContext2D.drawImage( ): draw an image

Synopsis

void drawImage(Imageimage, float x, float y)
void drawImage(Image image, float x, float y,
               float width, float height)
void drawImage(Image image, integer sourceX, integer sourceY,
               integer sourceWidth, integer sourceHeight,
               float destX, float destY,
               float destWidth, float destHeight)

Arguments

image

The image to be drawn. This must be an Image object representing an <img> tag, or an offscreen image or a Canvas object.

x, y

The point at which the upper-left corner of the image is drawn.

width, height

The size at which the image should be drawn. Specifying these arguments causes the image to be scaled.

sourceX, sourceY

The upper-left corner of the region of the image that is to be drawn. These integer arguments are measured in image pixels.

sourceWidth, sourceHeight

The dimensions, in image pixels, of the region of the image that is to be drawn.

destX, destY

The canvas coordinates at which the upper-left corner of the image region is to be drawn

destWidth, destHeight

The canvas dimensions at which the image region should be drawn.

Description

There are three variants of this method. The first copies the entire image to the canvas, placing its upper-left corner at the specified point and mapping each image pixel to one unit in the canvas coordinate system. The second variant also copies the entire image to the canvas but allows you to specify the desired width and height of the image in canvas units. The third variant is fully general: it allows you to specify any rectangular region of the image and copy it, with arbitrary scaling to any position within the canvas.

The images passed to this method must be Image or Canvas objects. An Image object may represent an <img> tag in the document or an offscreen image created with the Image( ) constructor.

See Also

Image


Name

CanvasRenderingContext2D.fill( ): fill the path

Synopsis

void fill( )

Description

fill( ) fills the current path with the color, gradient, or pattern specified by the fillStyle property. Each subpath of the path is filled independently. Any subpaths that are not closed are filled as if the closePath( ) method had been called on them. (Note, however, that this does not actually cause those subpaths to become closed.)

The canvas uses the "non-zero winding rule" to determine which points are inside the path and which are outside. The details of this rule are beyond the scope of this book, but they typically matter only for complex paths that intersect themselves.

Filling a path does not clear the path. You may call stroke( ) after calling fill( ) without redefining the path.

See Also

CanvasRenderingContext2D.fillRect( )


Name

CanvasRenderingContext2D.fillRect( ): fill a rectangle

Synopsis

void fillRect(floatx, float y,
              float width, float height)

Arguments

x, y

The coordinates of the upper-left corner of rectangle.

width, height

The dimensions of the rectangle.

Description

fillRect( ) fills the specified rectangle with the color, gradient, or pattern specified by the fillStyle property.

Current implementations of fillRect( ) also clear the path as if beginPath( ) had been called. This surprising behavior may not be standardized and should not be relied upon.

See Also

CanvasRenderingContext2D.fill( )
CanvasRenderingContext2D.rect( )
CanvasRenderingContext2D.strokeRect( )

Name

CanvasRenderingContext2D.globalCompositeOperation: specifies how colors are combined on the canvas

Synopsis

String globalCompositeOperation

Description

This property specifies how colors being rendered onto the canvas are combined (or "composited") with the colors that already exist in the canvas. The following table lists the possible values and their meanings. The word source in the these values refers to the colors being drawn onto the canvas, and the word destination refers to the existing colors on the canvas. The default is "source-over".

Value

Meaning

"copy"

Draws only the new shape, removing everything else.

"darker"

Where both shapes overlap, the color is determined by subtracting color values.

"destination-atop"

Existing content is kept only where it overlaps the new shape. The new shape is drawn behind the content.

"destination-in"

Existing content is kept where both the new shape and existing canvas content overlap. Everything else is made transparent.

"destination-out"

Existing content is kept where it doesn't overlap the new shape. Everything else is made transparent.

"destination-over"

The new shape is drawn behind existing content.

"lighter"

Where both shapes overlap, the color is determined by adding the two color values.

"source-atop"

The new shape is drawn only where it overlaps existing content.

"source-in"

The new shape is drawn only where both the new shape and existing content overlap. Everything else is made transparent.

"source-out"

The new shape is drawn where it doesn't overlap existing content.

"source-over"

The new shape is drawn on top of existing content. This is the default behavior.

"xor"

Shapes are made transparent where both overlap and drawn normal everywhere else.

Bugs

Firefox 1.5 does not support the values "copy" or "darker".


Name

CanvasRenderingContext2D.lineCap: specifies how the ends of lines are rendered

Synopsis

String lineCap

Description

The lineCap property specifies how lines should be terminated. It matters only when drawing wide lines. Legal values for this property are listed in the following table. The default value is "butt".

Value

Meaning

"butt"

This default value specifies that the line should have no cap. The end of the line is straight and is perpendicular to the direction of the line. The line is not extended beyond its endpoint.

"round"

This value specifies that lines should be capped with a semicircle whose diameter is equal to the width of the line and which extends beyond the end of the line by one half the width of the line.

"square"

This value specifies that lines should be capped with a rectangle. This value is like "butt", but the line is extended by half of its width.

Bugs

Firefox 1.5 does not properly implement the "butt" cap style. Butt caps are rendered as if they were "square" line caps.

See Also

CanvasRenderingContext2D.lineJoin


Name

CanvasRenderingContext2D.lineJoin: specifies how vertices are rendered

Synopsis

String lineJoin

Description

When a path includes vertices where line segments and/or curves meet, the lineJoin property specifies how those vertices are drawn. The effect of this property is apparent only when drawing with wide lines.

The default value of the property is "miter", which specifies that the outside edges of the two line segments are extended until they intersect. When two lines meet at an acute angle, mitered joins can become quite long. The miterLimit property places an upper bound on the length of a miter. Beyond this limit, the miter is beveled off.

The value "round" specifies that the outside edges of the vertex should be joined with a filled arc whose diameter is equal to the width of the line.

The value "bevel" specifies that the outside edges of the vertex should be joined with a filled triangle.

Bugs

Firefox 1.5 does not correctly implement beveled joins and renders them as rounded joins. Also, mitered joins are not displayed correctly when stroked in a partially transparent color.

See Also

CanvasRenderingContext2D.lineCap, CanvasRenderingContext2D.miterLimit


Name

CanvasRenderingContext2D.lineTo( ): add a straight line to the current subpath

Synopsis

void lineTo(floatx, float y)

Arguments

x, y

The coordinates of the end point of the line.

Description

lineTo( ) adds a straight line to the current subpath. The line begins at the current point and ends at (x,y). When this method returns, the current position is (x,y).

See Also

CanvasRenderingContext2D.beginPath( ), CanvasRenderingContext2D.moveTo( )


Name

CanvasRenderingContext2D.miterLimit: maximum-miter-length-to-line-width ratio

Synopsis

float miterLimit

Description

When wide lines are drawn with the lineJoin property set to "miter" and two lines meet at an acute angle, the resulting miter can be quite long. When miters are too long, they become visually jarring. This miterLimit property places an upper bound on the length of the miter. This property expresses a ratio of the miter length to the line width. The default value is 10, which means that a miter should never be longer than 10 times the line width. If a miter reaches this length, it is beveled off. This property has no effect when lineJoin is "round" or "bevel".

Bugs

Firefox 1.5 does not correctly implement this property. When a mitered join exceeds the miterLimit, the join is converted to a rounded join instead.

See Also

CanvasRenderingContext2D.lineJoin


Name

CanvasRenderingContext2D.moveTo( ): sets the current position and begins a new subpath

Synopsis

void moveTo(floatx, float y)

Arguments

x, y

The coordinates of the new current point.

Description

moveTo( ) sets the current position to ( x , y ) and creates a new subpath with this as its first point. If there was a previous subpath and it consisted of just one point, that subpath is removed from the path.

See Also

CanvasRenderingContext2D.beginPath( )


Name

CanvasRenderingContext2D.quadraticCurveTo( ): add a quadratic Bezier curve to the current subpath

Synopsis

void quadraticCurveTo(floatcpX, float cpY,
                      float x, float y)

Arguments

cpX, cpY

The coordinates of the control point.

x, y

The coordinates of the end point of the curve.

Description

This method adds a quadratic Bézier curve segment to the current subpath. The curve starts at the current point and ends at ( x , y ). The control point ( cpX , cpY ) specifies the shape of the curve between these two points. (The mathematics of Bezier curves is beyond the scope of this book, however.) When this method returns, the current position is ( x , y ).

Bugs

Firefox 1.5 implements this method incorrectly.

See Also

CanvasRenderingContext2D.bezierCurveTo( )


Name

CanvasRenderingContext2D.rect( ): add a rectangle subpath to the path

Synopsis

void rect(floatx, float y,
          float width, float height)

Arguments

x, y

The coordinates of the upper-left corner of the rectangle.

width, height

The dimensions of the rectangle.

Description

This method adds a rectangle to the path. This rectangle is in a subpath of its own and is not connected to any other subpaths in the path. When this method returns, the current position is (0,0).

See Also

CanvasRenderingContext2D.fillRect( ), CanvasRenderingContext2D.strokeRect( )


Name

CanvasRenderingContext2D.restore( ): reset drawing state to saved values

Synopsis

void restore( )

Description

This method pops the stack of saved graphics states and restores the values of the CanvasRenderingContext2D properties, the clipping path, and the transformation matrix. See the save( ) method for further information.

Bugs

Firefox 1.5 does not correctly save and restore the strokeStyle property.

See Also

CanvasRenderingContext2D.save( )


Name

CanvasRenderingContext2D.rotate( ): rotate the coordinate system of the canvas

Synopsis

void rotate(floatangle)

Arguments

angle

The amount of rotation, in radians. Positive values result in clockwise rotation, and negative values result in counterclockwise rotation.

Description

This method alters the mapping between canvas coordinates and the pixels of the <canvas> element in the web browser so that any subsequent drawing appears rotated within the canvas by the specified angle. It does not rotate the <canvas> element itself. Note that the angle is specified in radians. To convert degrees to radians, multiply by Math.PI and divide by 180.

See Also

CanvasRenderingContext2D.scale( ), CanvasRenderingContext2D.translate( )


Name

CanvasRenderingContext2D.save( ): save a copy of the current graphics state

Synopsis

void save( )

Description

save( ) pushes a copy of the current graphics state onto a stack of saved graphics states. This allows you to temporarily change the graphics state, and then restore the previous values with a call to restore( ).

The graphics state of a canvas includes all the properties of the CanvasRenderingContext2D object (except for the read-only canvas property). It also includes the transformation matrix that is the result of calls to rotate( ), scale( ), and translate( ). Additionally, it includes the clipping path, which is specified with the clip( ) method. Note, however, that the current path and current position are not part of the graphics state and are not saved by this method.

Bugs

Firefox 1.5 does not save and restore the strokeStyle property.

See Also

CanvasRenderingContext2D.restore( )


Name

CanvasRenderingContext2D.scale( ): scale the user coordinate system of the canvas

Synopsis

void scale(floatsx, float sy)

Arguments

sx, sy

The horizontal and vertical scaling factors.

Description

scale( ) adds a scale transformation to the current transformation matrix of the canvas. Scaling is done with independent horizontal and vertical scaling factors. For example, passing the values 2.0 and 0.5 causes subsequently drawn paths to be twice as wide and half as high as they would otherwise have been. Specifying a negative value for sx causes X coordinates to be flipped across the Y axis, and a negative value of sy causes Y coordinates to be flipped across the X axis.

See Also

CanvasRenderingContext2D.rotate( ), CanvasRenderingContext2D.translate( )


Name

CanvasRenderingContext2D.stroke( ): draw the current path

Synopsis

void stroke( )

Description

The stroke( ) method draws the outline of the current path. The path defines the geometry of the line that is produced, but the visual appearance of that line depends on the strokeStyle, lineWidth, lineCap, lineJoin, and miterLimit properties.

The term stroke refers to a pen or brush stroke. It means "draw the outline of." Contrast this stroke( ) method with fill( ), which fills the interior of a path rather than stroking the outline of the path.

See Also

CanvasRenderingContext2D.fill( )
CanvasRenderingContext2D.lineCap
CanvasRenderingContext2D.lineJoin
CanvasRenderingContext2D.strokeRect( )

Name

CanvasRenderingContext2D.strokeRect( ): draw a rectangle

Synopsis

void strokeRect(floatx, float y,
                float width, float height)

Arguments

x, y

The coordinates of the upper-left corner of the rectangle.

width, height

The dimensions of the rectangle.

Description

This method draws the outline (but does not fill the interior) of a rectangle with the specified position and size. Line color and line width are specified by the strokeStyle and lineWidth properties. The appearance of the rectangle corners are specified by the lineJoin property.

Current implementations of strokeRect( ) clear the path as if beginPath( ) had been called. This surprising behavior may not be standardized and should not be relied upon.

See Also

CanvasRenderingContext2D.fillRect( )
CanvasRenderingContext2D.lineJoin
CanvasRenderingContext2D.rect( )
CanvasRenderingContext2D.stroke( )

Name

CanvasRenderingContext2D.translate( ): translate the user coordinate system of the canvas

Synopsis

void translate(floatdx, float dy)

Arguments

dx, dy

The amounts to translate in the X and Y dimensions.

Description

translate( ) adds horizontal and vertical offsets to the transformation matrix of the canvas. The arguments dx and dy are added to all points in any subsequently defined paths.

See Also

CanvasRenderingContext2D.rotate( ), CanvasRenderingContext2D.scale( )


Name

CDATASection: a CDATA node in an XML document — DOM Level 1 XML: Node → CharacterData → Text → CDATASection

Description

This infrequently used interface represents a CDATA section in an XML document. Programmers working with HTML documents never encounter nodes of this type and do not need to use this interface.

CDATASection is a subinterface of Text and does not define any properties or methods of its own. The textual content of the CDATA section is available through the nodeValue property inherited from Node or through the data property inherited from CharacterData. Although CDATASection nodes can often be treated in the same way as Text nodes, note that the Node.normalize( ) method does not merge adjacent CDATA sections. Create a CDATASection with Document.createCDATASection( ).

See Also

CharacterData, Text


Name

CharacterData: common functionality for Text and Comment nodes — DOM Level 1 Core: Node → CharacterData

Subinterfaces

Comment, Text

Properties

String data

The text contained by this node.

readonly unsigned long length

The number of characters contained by this node.

Methods

appendData( )

Appends the specified string to the text contained by this node.

deleteData( )

Deletes text from this node, starting with the character at the specified offset and continuing for the specified number of characters.

insertData( )

Inserts the specified string into the text of this node at the specified character offset.

replaceData( )

Replaces the characters starting at the specified character offset and continuing for the specified number of characters with the specified string.

substringData( )

Returns a copy of the text starting at the specified character offset and continuing for the specified number of characters.

Description

CharacterData is the superinterface for Text and Comment nodes. Documents never contain CharacterData nodes; they contain only Text and Comment nodes. Since both of these node types have similar functionality, however, that functionality has been defined here so that both Text and Comment can inherit it.

Note that it is not necessary to use the string-manipulation methods defined by this interface. The data property is an ordinary JavaScript string, and you can manipulate it with the + operator for string concatenation and with various String and RegExp methods.

See Also

Comment, Text


Name

CharacterData.appendData( ): append a string to a Text or Comment node — DOM Level 1 Core:

Synopsis

void appendData(Stringarg)
    throws DOMException;

Arguments

arg

The string to be appended to the Text or Comment node.

Throws

This method throws a DOMException with a code of NO_MODIFICATION_ALLOWED_ERR if called on a node that is read-only.

Description

This method appends the string arg to the end of the data property for this node.


Name

CharacterData.deleteData( ): delete characters from a Text or Comment node — DOM Level 1 Core:

Synopsis

void deleteData(unsigned longoffset,
                unsigned long count)
    throws DOMException;

Arguments

offset

The position of the first character to be deleted.

count

The number of characters to be deleted.

Throws

This method may throw a DOMException with one of the following code values:

INDEX_SIZE_ERR

The offset or count argument is negative, or offset is greater than the length of the Text or Comment node.

NO_MODIFICATION_ALLOWED_ERR

The node is read-only and may not be modified.

Description

This method deletes characters from this Text or Comment node, starting with the character at the position offset and continuing for count characters. If offset plus count is greater than the number of characters in the Text or Comment node, all characters from offset to the end of the string are deleted.


Name

CharacterData.insertData( ): insert a string into a Text or Comment node — DOM Level 1 Core:

Synopsis

void insertData(unsigned longoffset,
                String arg)
    throws DOMException;

Arguments

offset

The character position within the Text or Comment node at which the string is to be inserted.

arg

The string to insert.

Throws

This method may throw a DOMException with one of the following code values in the following circumstances:

INDEX_SIZE_ERR

offset is negative or greater than the length of the Text or Comment node.

NO_MODIFICATION_ALLOWED_ERR

The node is read-only and may not be modified.

Description

This method inserts the specified string arg into the text of a Text or Comment node at the specified position offset.


Name

CharacterData.replaceData( ): replace characters of a Text or Comment node with a string — DOM Level 1 Core:

Synopsis

void replaceData(unsigned longoffset,
                 unsigned long count,
                 String arg)
    throws DOMException;

Arguments

offset

The character position within the Text or Comment node at which the replacement is to begin.

count

The number of characters to be replaced.

arg

The string that replaces the characters specified by offset and count.

Throws

This method may throw a DOMException with one of the following code values in the following circumstances:

INDEX_SIZE_ERR

offset is negative or greater than the length of the Text or Comment node, or count is negative.

NO_MODIFICATION_ALLOWED_ERR

The node is read-only and may not be modified.

Description

This method replaces count characters starting at position offset with the contents of the string arg. If the sum of offset and count is greater than the length of the Text or Comment node, all characters from offset on are replaced.

Notice that the insertData( ) and deleteData( ) methods are both special cases of this one.


Name

CharacterData.substringData( ): extract a substring from a Text or Comment node — DOM Level 1 Core:

Synopsis

String substringData(unsigned longoffset,
                     unsigned long count)
    throws DOMException;

Arguments

offset

The position of the first character to be returned.

count

The number of characters in the substring to be returned.

Returns

A string that consists of count characters of the Text or Comment node starting with the character at position offset.

Throws

This method may throw a DOMException with one of the following code values:

INDEX_SIZE_ERR

offset is negative or greater than the length of the Text or Comment node, or count is negative.

DOMSTRING_SIZE_ERR

The specified range of text is too long to fit into a string in the browser's JavaScript implementation.

Description

This method extracts the substring that starts at position offset and continues for count characters from the text of a Text or Comment node. This method is useful only when the amount of text contained by the node is larger than the maximum number of characters that can fit in a string in a browser's JavaScript implementation. In this case, a JavaScript program cannot use the data property of the Text or Comment node directly and must instead work with shorter substrings of the node's text. This situation is unlikely to arise in practice.


Name

Checkbox: see Input


Name

Comment: an HTML or XML comment — DOM Level 1 Core: Node → CharacterData → Comment

Description

A Comment node represents a comment in an HTML or XML document. The content of the comment (i.e., the text between <!-- and -->) is available through the data property inherited from the CharacterData interface or through the nodeValue property inherited from the Node interface. This content may be manipulated using the various methods inherited from CharacterData. Create a comment object with Document.createComment( ).

See Also

CharacterData


Name

CSS2Properties: a set of CSS attributes and their values — DOM Level 2 CSS2: Object → CSS2Properties

Properties

String cssText

The textual representation of a set of style attributes and their values. The text is formated as in a CSS stylesheet, minus the element selector and the curly braces that surround the attributes and values. Setting this property to an illegal value throws a DOMException with a code of SYNTAX_ERR. Attempting to set this property when the CSS2Properties object is read-only throws a DOMException with a code of NO_MODIFICATION_ALLOWED_ERR.

In addition to the cssText property, a CSS2Properties object also has a property corresponding to each CSS attribute that the browser supports. These property names correspond closely to the CSS attribute names, with minor changes required to avoid syntax errors in JavaScript. Multiword attributes that contain hyphens, such as "font-family", are written without hyphens in JavaScript, and each word after the first is capitalized: fontFamily. Also, the "float" attribute conflicts with the reserved word float, so it translates to the property cssFloat.

The CSS2Properties property names corresponding to each attribute defined by the CSS2 specification are listed in the following table. Note, however, that some browsers do not support all CSS attributes and may not implement all of the listed properties. Since the properties correspond directly to CSS attributes, no individual documentation is given for each property. See a CSS reference, such as Cascading Style Sheets: The Definitive Guide by Eric A. Meyer (O'Reilly), for the meaning and legal values of each. All of the properties are strings. Setting any of these properties may throw the same exceptions as setting the cssText property:

azimuth

background

backgroundAttachment

backgroundColor

backgroundImage

backgroundPosition

backgroundRepeat

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

color

content

counterIncrement

counterReset

cssFloat

cue

cueAfter

cueBefore

cursor

direction

display

elevation

emptyCells

font

fontFamily

fontSize

fontSizeAdjust

fontStretch

fontStyle

fontVariant

fontWeight

height

left

letterSpacing

lineHeight

listStyle

listStyleImage

listStylePosition

listStyleType

margin

marginBottom

marginLeft

marginRight

marginTop

markerOffset

marks

maxHeight

maxWidth

minHeight

minWidth

orphans

outline

outlineColor

outlineStyle

outlineWidth

overflow

padding

paddingBottom

paddingLeft

paddingRight

paddingTop

page

pageBreakAfter

pageBreakBefore

pageBreakInside

pause

pauseAfter

pauseBefore

pitch

pitchRange

playDuring

position

quotes

richness

right

size

speak

speakHeader

speakNumeral

speakPunctuation

speechRate

stress

tableLayout

textAlign

textDecoration

textIndent

textShadow

textTransform

top

unicodeBidi

verticalAlign

visibility

voiceFamily

volume

whiteSpace

widows

width

wordSpacing

zIndex

Description

A CSS2Properties object represents a set of CSS style attributes and their values. It defines one JavaScript property for each CSS attribute defined by the CSS2 specification. The style property of an HTMLElement is a read/write CSS2Properties object, as is the style property of a CSSRule object. The return value of Window.getComputedStyle( ), however, is a CSS2Properties object whose properties are read-only.

See Also

CSSRule, HTMLElement, Window.getComputedStyle( ); Chapter 16, Cascading Style Sheets and Dynamic HTML


Name

CSSRule: a rule in a CSS stylesheet — DOM Level 2 CSS, IE 5: Object → CSSRule

Properties

String selectorText

The selector text that specifies the document elements this style rule applies to. Setting this property raises a DOMException with a code of NO_MODIFICATION_ALLOWED_ERR if the rule is read-only or a code of SYNTAX_ERR if the new value does not follow CSS syntax rules.

readonly CSS2Properties style

The style values that should be applied to elements specified by selectorText. Note that while the style property itself is read-only, the properties of the CSS2Properties object to which it refers are read/write.

Description

A CSSRule object represents a rule in a CSS stylesheet: it represents style information to be applied to a specific set of document elements. selectorText is the string representation of the element selector for this rule, and style is a CSS2Properties object that represents the set of style attributes and values to apply to the selected elements.

The DOM Level 2 CSS specification actually defines a somewhat complex hierarchy of CSSRule interfaces to represent different types of rules that can appear in a CSSStyleSheet. The properties listed here are actually defined by the DOM CSSStyleRule interface. Style rules are the most common and most important types of rules in a stylesheet, and the properties listed here are the only ones that can be used portably across browsers. IE does not support the DOM Level 2 specification very well (at least not through IE 7) but does implement a CSSRule object that supports the two properties listed here.

See Also

CSS2Properties, CSSStyleSheet


Name

CSSStyleSheet: a CSS stylesheet — DOM Level 2 CSS, IE 4: Object → CSSStyleSheet

Properties

readonly CSSRule[] cssRules

A read-only, array-like object holding the CSSRule objects that compose the stylesheet. In IE, use the rules property instead. In DOM-compliant implementations, this array includes objects that represent all rules in a stylesheet, including at-rules such as @import directives. Rules of these sorts implement a different interface than that described for CSSRule. These other type of rule objects are not well supported across browsers and are not documented in this book. Be aware, therefore, that you must test any entries in this array to ensure that they define CSSRule properties before you attempt to use those properties.

boolean disabled

If true, the stylesheet is disabled and is not applied to the document. If false, the stylesheet is enabled and is applied to the document.

readonly String href

The URL of a stylesheet that is linked to the document or null for inline stylesheets.

readonly StyleSheet parentStyleSheet

The stylesheet that included this one or null if this stylesheet was included directly in the document.

readonly CSSRule[] rules

The IE equivalent of the DOM-standard cssRules[] array.

readonly String title

The title of the stylesheet, if specified. A title may be specified by the title attribute of a <style> or <link> element that refers to this stylesheet.

readonly String type

The type of this stylesheet, as a MIME type. CSS stylesheets have a type of "text/css".

Methods

addRule( )

IE-specific method to add a CSS rule to a stylesheet.

deleteRule( )

DOM-standard method to delete the rule at the specified position.

insertRule( )

DOM-standard method to insert a new rule into the stylesheet.

removeRule( )

IE-specific method to delete a rule.

Description

This interface represents a CSS stylesheet. It has properties and methods for disabling the stylesheet, and for querying, inserting, and removing style rules. IE implements a slightly different API than the DOM standard. In IE, use the rules[] array instead of cssRules[], and use addRule( ) and removeRule( ) instead of the DOM standard insertRule( ) and deleteRule( ).

The CSSStyleSheet objects that apply to a document are members of the styleSheets[] array of the Document object. The DOM standard also requires (although this is not widely implemented at the time of this writing) that any <style> or <link> element or ProcessingInstruction node that defines or links to a stylesheet should make the CSSStyleSheet object available through a sheet property.

See Also

CSSRule, the styleSheets[] property of the Document object; Chapter 16, Cascading Style Sheets and Dynamic HTML


Name

CSSStyleSheet.addRule( ): IE-specific method to insert a rule into a stylesheet — IE 4:

Synopsis

void addRule(Stringselector,
             String style,
             integer index)

Arguments

selector

The CSS selector for the rule.

style

The styles to be applied to elements that match the selector. This style string is a semicolon-delimited list of attribute:value pairs. It does not begin and end with curly braces.

index

The position in the rules array at which the rule is to be inserted or appended. If this optional argument is omitted, the new rule is appended to the array of rules.

Description

This method inserts (or appends) a new CSS style rule at the specified index of the rules array of this stylesheet. This is an IE-specific alternative to the standard insertRule( ) method. Note that the arguments to this method are different from those to insertRule( ).


Name

CSSStyleSheet.deleteRule( ): delete a rule from a stylesheet — DOM Level 2 CSS:

Synopsis

void deleteRule(unsigned longindex)
    throws DOMException;

Arguments

index

The index within the cssRules array of the rule to be deleted.

Throws

This method throws a DOMException with a code of INDEX_SIZE_ERR if index is negative or greater than or equal to cssRules.length. It throws a DOMException with a code of NO_MODIFICATION_ALLOWED_ERR if this stylesheet is read-only.

Description

This method deletes the rule at the specified index from the cssRules array. This is a DOM-standard method; see CSSStyleSheet.removeRule( ) for an IE-specific alternative.


Name

CSSStyleSheet.insertRule( ): insert a rule into a stylesheet — DOM Level 2 CSS:

Synopsis

unsigned long insertRule(Stringrule,
                         unsigned long index)
    throws DOMException;

Arguments

rule

The complete, parseable text representation of the rule to be added to the stylesheet. For style rules, this includes both the element selector and the style information.

index

The position in the cssRules array at which the rule is to be inserted or appended.

Returns

The value of the index argument.

Throws

This method throws a DOMException with one of the following code values in the following circumstances:

HIERARCHY_REQUEST_ERR

CSS syntax does not allow the specified rule at the specified location.

INDEX_SIZE_ERR

index is negative or greater then cssRules.length.

NO_MODIFICATION_ALLOWED_ERR

The stylesheet is read-only.

SYNTAX_ERR

The specified rule text contains a syntax error.

Description

This method inserts (or appends) a new CSS rule at the specified index of the cssRules array of this stylesheet. This is a DOM-standard method; see CSSStyleSheet.addRule( ) for an IE-specific alternative.


Name

CSSStyleSheet.removeRule( ): IE-specific method to remove a rule from a stylesheet — IE 4:

Synopsis

void removeRule(integerindex)

Arguments

index

The index in the rules[] array of the rule to be removed. If this optional argument is omitted, the first rule in the array is removed.

Description

This method removes the CSS style rule at the specified index of the rules array of this stylesheet. This is an IE-specific alternative to the standard deleteRule( ) method.


Name

Document: an HTML or XML document — DOM Level 1 Core: Node → Document

Subinterfaces

HTMLDocument

Properties

readonly Window defaultView

The web browser Window object (the "view" in DOM terminology) in which this document is displayed.

readonly DocumentType doctype

For XML documents with a <!DOCTYPE< declaration, specifies a DocumentType node that represents the document's DTD. For HTML documents and for XML documents with no <!DOCTYPE>, this property is null.

readonly Element documentElement

A reference to the root element of the document. For HTML documents, this property is always the Element object representing the <html> tag. This root element is also available through the childNodes[] array inherited from Node. See also the body property of HTMLDocument.

readonly DOMImplementation implementation

The DOMImplementation object that represents the implementation that created this document.

readonly CSSStyleSheet[] styleSheets

A collection of objects representing all stylesheets embedded in or linked into a document. In HTML documents, this includes stylesheets defined with <link> and <style> tags.

Methods

addEventListener( )

Adds an event-handler function to the set of event handlers for this document. This is a DOM-standard method supported by all modern browsers except IE.

attachEvent( )

Adds an event-handler function to the set of handlers for this document. This is the IE-specific alternative to addEventListener( ).

createAttribute( )

Creates a new Attr node with the specified name.

createAttributeNS( )

Creates a new Attr node with the specified name and namespace.

createCDATASection( )

Creates a new CDATASection node containing the specified text.

createComment( )

Creates a new Comment node containing the specified string.

createDocumentFragment( )

Creates a new, empty DocumentFragment node.

createElement( )

Creates a new Element node with the specified tag name.

createElementNS( )

Creates a new Element node with the specified tag name and namespace.

createEvent( )

Creates a new synthetic Event object of the named type.

createExpression( )

Creates a new XPathExpression object that represents a compiled XPath query. For an IE-specific alternative, see Node.selectNodes( ).

createProcessingInstruction( )

Creates a new ProcessingInstruction node with the specified target and data string.

createRange( )

Creates a new Range object. This method is technically part of the DocumentRange interface; it is implemented by the Document object only in implementations that support the Range module.

createTextNode( )

Creates a new Text node to represent the specified text.

detachEvent( )

Removes an event-handler function from this document. This is the IE-specific alternative to the standard removeEventListener( ) method.

dispatchEvent( )

Dispatches a synthetic event to this document.

evaluate( )

Evaluates an XPath query against this document. See Node.selectNodes( ) for an IE-specific alternative.

getElementById( )

Returns a descendant Element of this document that has the specified value for its id attribute, or null if no such Element exists in the document.

getElementsByTagName( )

Returns an array (technically a NodeList) of all Element nodes in this document that have the specified tag name. The Element nodes appear in the returned array in the order in which they appear in the document source.

getElementsByTagNameNS( )

Returns an array of all Element nodes that have the specified tag name and namespace.

importNode( )

Makes a copy of a node from some other document that is suitable for insertion into this document.

loadXML( ) [IE only]

Parses a string of XML markup and stores the result in this document object.

removeEventListener( )

Removes an event handler function from the set of handlers for this document. This is a standard DOM method implemented by all modern browsers except IE.

Description

The Document interface is the root node of a document tree. A Document node may have multiple children, but only one of those children may be an Element node: it is the root element of the document. The root element is most easily accessed through the documentElement property. The doctype and implementation properties provide access to the DocumentType object (if any) and the DOMImplementation object for this document.

Most of the methods defined by the Document interface are "factory methods" that create various types of nodes that can be inserted into this document. The notable exceptions are getElementById( ) and getElementsByTagName( ), which are quite useful for finding a specific Element or a set of related Element nodes within the document tree. Other exceptions are event-handler registration methods such as addEventHandler( ). These event-related methods are also defined by the Element interface and are documented in complete detail there.

You most commonly obtain a Document object via the document property of a Window. Document objects are also available through the contentDocument property of Frame and IFrame, and the ownerDocument property of any Node that has been added to a document.

If you are working with XML (including XHTML), you can create new Document objects with the createDocument( ) method of the DOMImplementation:

document.implementation.createDocument(namespaceURL, rootTagName, null);

In IE, you would use code like this instead:

new ActiveXObject("MSXML2.DOMDocument");

See Example 21-1, “Creating an empty XML document” for a cross-platform utility function that creates a new Document object.

It is also possible to load an XML file from the network and parse it into a Document object. See the responseXML property of the XMLHttpRequest object. You can also parse a string of XML markup into a Document object: see DOMParser.parseFromString( ) and the IE-specific Document.loadXML( ). (Example 21-4, “Parsing an XML document” is a cross-platform utility function that uses these methods to parse XML markup.)

See HTMLDocument for additional properties and methods that are specific to HTML documents.

See Also

DOMImplementation, DOMParser, HTMLDocument, Window, XMLHttpRequest; Chapter 15, Scripting Documents


Name

Document.addEventListener( ): see Element.addEventListener( )


Name

Document.attachEvent( ): see Element.attachEvent( )


Name

Document.createAttribute( ): create a new Attr node — DOM Level 1 Core:

Synopsis

Attr createAttribute(Stringname)
    throws DOMException;

Arguments

name

The name for the newly created attribute.

Returns

A newly created Attr node with its nodeName property set to name.

Throws

This method throws a DOMException with a code of INVALID_CHARACTER_ERR if name contains an illegal character.

See Also

Attr, Element.setAttribute( ), Element.setAttributeNode( )


Name

Document.createAttributeNS( ): create an Attr with a name and namespace — DOM Level 2 Core:

Synopsis

Attr createAttributeNS(StringnamespaceURI,
                       String qualifiedName)
    throws DOMException;

Arguments

namespaceURI

The unique identifier of the namespace for the Attr or null for no namespace.

qualifiedName

The qualified name of the attribute, which should include a namespace prefix, a colon, and a local name.

Returns

A newly created Attr node with the specified name and namespace.

Throws

This method may throw a DOMException with one of the following code values in the following circumstances:

INVALID_CHARACTER_ERR

qualifiedName contains an illegal character.

NAMESPACE_ERR

qualifiedName is malformed or there is a mismatch between qualifiedName and namespaceURI.

NOT_SUPPORTED_ERR

The implementation does not support XML documents and therefore does not implement this method.

Description

createAttributeNS( ) is just like createAttribute( ), except that the created Attr node has a name and namespace instead of just a name. This method is useful only with XML documents that use namespaces.


Name

Document.createCDATASection( ): create a new CDATASection node — DOM Level 1 Core:

Synopsis

CDATASection createCDATASection(Stringdata)
    throws DOMException;

Arguments

data

The text of the CDATASection to create.

Returns

A newly created CDATASection node, with the specified data as its contents.

Throws

If the document is an HTML document, this method throws a DOMException with a code of NOT_SUPPORTED_ERR because HTML documents do not allow CDATASection nodes.


Name

Document.createComment( ): create a new Comment node — DOM Level 1 Core:

Synopsis

Comment createComment(Stringdata);

Arguments

data

The text of the Comment node to create.

Returns

A newly created Comment node, with the specified data as its text.


Name

Document.createDocumentFragment( ): create a new, empty DocumentFragment node — DOM Level 1 Core:

Synopsis

DocumentFragment createDocumentFragment( );

Returns

A newly created DocumentFragment node with no children.


Name

Document.createElement( ): create a new Element node — DOM Level 1 Core:

Synopsis

Element createElement(StringtagName)
    throws DOMException;

Arguments

tagName

The tag name of the Element to be created. Since HTML tags are case-insensitive, you may use any capitalization for HTML tag names. XML tag names are case-sensitive.

Returns

A newly created Element node with the specified tag name.

Throws

This method throws a DOMException with a code of INVALID_CHARACTER_ERR if tagName contains an illegal character.


Name

Document.createElementNS( ): create a new Element node using a namespace — DOM Level 2 Core:

Synopsis

Element createElementNS(StringnamespaceURI,
                        String qualifiedName)
      throws DOMException;

Arguments

namespaceURI

The unique identifier for the namespace of the new Element or null for no namespace.

qualifiedName

The qualified name of the new Element. This should include a namespace prefix, a colon, and a local name.

Returns

A newly created Element node, with the specified tag name and namespace.

Throws

This method may throw a DOMException with one of the following code values in the following circumstances:

INVALID_CHARACTER_ERR

qualifiedName contains an illegal character.

NAMESPACE_ERR

qualifiedName is malformed or there is a mismatch between qualifiedName and namespaceURI.

NOT_SUPPORTED_ERR

The implementation does not support XML documents and therefore does not implement this method.

Description

createElementNS( ) is just like createElement( ), except that the created Element node has a name and namespace instead of just a name. This method is useful only with XML documents that use namespaces.


Name

Document.createEvent( ): create an Event object — DOM Level 2 Events:

Synopsis

Event createEvent(StringeventType)
    throws DOMException

Arguments

eventType

The name of the event module for which an Event object is desired. Valid event types are listed in the Description.

Returns

A newly created Event object of the specified type.

Throws

This method throws a DOMException with a code of NOT_SUPPORTED_ERR if the implementation does not support events of the requested type.

Description

This method creates a new event object of the type specified by the eventType argument. Note that the value of this argument should not be the (singular) name of the event interface to be created but instead should be the (plural) name of the DOM module that defines that interface. The following table shows the legal values for eventType and the event interface each value creates:

eventType argument

Event interface

Initialization method

HTMLEvents

Event

initEvent( )

MouseEvents

MouseEvent

initMouseEvent( )

UIEvents

UIEvent

initUIEvent( )

After creating an Event object with this method, you must initialize the object with the initialization method shown in the table. See the appropriate Event interface reference page for details about the initialization method.

This method is actually defined not by the Document interface but by the DOM DocumentEvent interface. If an implementation supports the Events module, the Document object always implements the DocumentEvent interface and supports this method. Note that Internet Explorer does not support the DOM Events module.

See Also

Event, MouseEvent, UIEvent


Name

Document.createExpression( ): create an XPath expression for later evaluation — Firefox 1.0, Safari 2.01, Opera 9:

Synopsis

XPathExpression createExpression(StringxpathText,
                                 Function namespaceURLMapper)
    throws XPathException

Arguments

xpathText

The string representing the XPath expression to compile.

namespaceURLMapper

A function that will map from a namespace prefix to a full namespace URL, or null if no such mapping is required.

Returns

An XPathExpression object.

Throws

This method throws an exception if the xpathText contains a syntax error or if it uses a namespace prefix that cannot be resolved by namespaceURLMapper.

Description

This method takes a string representation of an XPath expression and converts it to a compiled representation, an XPathExpression. In addition to the expression, this method takes a function of the form function(prefix) that resolves a namespace prefix string and returns it as a full namespace URL string.

Internet Explorer does not support this API. See Node.selectNodes( ) for an IE-specific alternative.

See Also

Document.evaluate( ), Node.selectNodes( ), XPathExpression, XPathResult


Name

Document.createProcessingInstruction( ): create a ProcessingInstruction node — DOM Level 1 Core:

Synopsis

ProcessingInstruction createProcessingInstruction(Stringtarget,
                                                  String data)
     throws DOMException;

Arguments

target

The target of the processing instruction.

data

The content text of the processing instruction.

Returns

A newly created ProcessingInstruction node.

Throws

This method may throw a DOMException with one of the following code values in the following circumstances:

INVALID_CHARACTER_ERR

The specified target contains an illegal character.

NOT_SUPPORTED_ERR

This is an HTML document and does not support processing instructions.


Name

Document.createRange( ): create a Range object — DOM Level 2 Range:

Synopsis

Range createRange( );

Returns

A newly created Range object with both boundary points set to the beginning of the document.

Description

This method creates a Range object that can be used to represent a region of this document or of a DocumentFragment associated with this document.

Note that this method is actually defined not by the Document interface but by the DocumentRange interface. If an implementation supports the Range module, the Document object always implements DocumentRange and defines this method. Internet Explorer 6 does not support this module.

See Also

Range


Name

Document.createTextNode( ): create a new Text node — DOM Level 1 Core:

Synopsis

Text createTextNode(Stringdata);

Arguments

data

The content of the Text node.

Returns

A newly created Text node that represents the specified data string.


Name

Document.detachEvent( ): see Element.detachEvent( )


Name

Document.dispatchEvent( ): see Element.dispatchEvent( )


Name

Document.evaluate( ): evaluate an XPath expression — Firefox 1.0, Safari 2.01, Opera 9:

Synopsis

XPathResult evaluate(StringxpathText,
                     Node contextNode,
                     Function namespaceURLMapper,
                     short resultType,
                     XPathResult result)
    throws DOMException, XPathException

Arguments

xpathText

The string representing the XPath expression to evaluate.

contextNode

The node in this document against which the expression is to be evaluated.

namespaceURLMapper

A function that will map from a namespace prefix to a full namespace URL or null if no such mapping is required.

resultType

Specifies the type of object expected as a result, using XPath conversions to coerce the result. Possible values for type are the constants defined by the XPathResult object.

result

An XPathResult object to be reused or null if you want a new XPathResult object to be created.

Returns

A XPathResult object representing the evaluation of the expression against the given context node.

Throws

This method may throw an exception if the xpathText contains a syntax error, if the result of the expression cannot be converted to the desired resultType, if the expression contains namespaces that namespaceURLMapper cannot resolve, or if contextNode is of the wrong type or is not associated with this document.

Description

This method evaluates the specified XPath expression against the given context node and returns an XPathResult object, using type to determine what the result type should be. If you want to evaluate an expression more than once, use Document.createExpression( ) to compile the expression to an XPathExpression object and then use the evaluate( ) method of XPathExpression.

Internet Explorer does not support this API. See Node.selectNodes( ) and Node.selectSingleNode( ) for an IE-specific alternative.

See Also

Document.createExpression( )
Node.selectNodes( )
Node.selectSingleNode( )
XPathExpression
XPathResult

Name

Document.getElementById( ): find an element with the specified unique ID — DOM Level 2 Core:

Synopsis

Element getElementById(StringelementId);

Arguments

elementId

The value of the id attribute of the desired element.

Returns

The Element node that represents the document element with the specified id attribute or null if no such element is found.

Description

This method searches the document for an Element node with an id attribute whose value is elementId and returns that Element. If no such Element is found, it returns null. The value of the id attribute is intended to be unique within a document, and if this method finds more than one Element with the specified elementId, it may return one at random, or it may return null. This is an important and commonly used method because it provides a simple way to obtain the Element object that represents a specific document element. Note that the name of this method ends with "Id", not with "ID"; be careful not to misspell it.

In HTML documents, this method searches for an element based on the value of its id attribute. Use HTMLDocument.getElementsByName( ) to search for HTML elements based on the value of their name attributes.

In XML documents, this method performs its search using any attribute whose type is id, regardless of what the name of that attribute is. If XML attribute types are not known (because, for example, the XML parser ignored or could not locate the document's DTD), this method always returns null. In client-side JavaScript, this method is not usually useful with XML documents. In fact, getElementById( ) was originally defined as a member of the HTMLDocument interface but was then moved to the Document interface in DOM Level 2.

See Also

Document.getElementsByTagName( )
Element.getElementsByTagName( )
HTMLDocument.getElementsByName( )

Name

Document.getElementsByTagName( ): return all Element nodes with the specified name — DOM Level 1 Core:

Synopsis

Element[] getElementsByTagName(Stringtagname);

Arguments

tagname

The tag name of the Element nodes to be returned, or the wildcard string "*" to return all Element nodes in the document regardless of tag name. For HTML documents, tag names are compared in a case-insensitive fashion. (Prior to version 6, IE does not support this wildcard syntax.)

Returns

A read-only array (technically, a NodeList) of all Element nodes in the document tree with the specified tag name. The returned Element nodes are in the same order in which they appear in the document source.

Description

This method returns a NodeList (which you can treat as a read-only array) that contains all Element nodes from the document that have the specified tag name, in the order in which they appear in the document source. The NodeList is "live"—i.e., its contents are automatically updated as necessary if elements with the specified tag name are added to or removed from the document.

HTML documents are case-insensitive, and you can specify tagname using any capitalization; it matches all tags with the same name in the document, regardless of how those tags are capitalized in the document source. XML documents, on the other hand, are case-sensitive, and tagname matches only tags with the same name and exactly the same capitalization in the document source.

Note that the Element interface defines a method by the same name that searches only a subtree of the document. Also, the HTMLDocument interface defines getElementsByName( ), which searches for elements based on the value of their name attributes rather than their tag names.

Example

You can find and iterate through all <h1> tags in a document with code like the following:

var headings = document.getElementsByTagName("h1");
for(var i = 0; i < headings.length; i++) {  // Loop through the returned tags
    var h = headings[i];
    // Now do something with the <h1> element in the h variable
}

See Also

Document.getElementById( )
Element.getElementsByTagName( )
HTMLDocument.getElementsByName( )

Name

Document.getElementsByTagNameNS( ): return all Element nodes with a specified name and namespace — DOM Level 2 Core:

Synopsis

Node[] getElementsByTagNameNS(StringnamespaceURI,
                              String localName);

Arguments

namespaceURI

The unique identifier of the namespace of the desired elements, or "*" to match all namespaces.

localName

The local name of the desired elements, or "*" to match any local name.

Returns

A read-only array (technically, a NodeList) of all Element nodes in the document tree that have the specified namespace and local name.

Description

This method works just like getElementsByTagName( ), except that it searches for elements by namespace and name. It is useful only with XML documents that use namespaces.


Name

Document.importNode( ): copy a node from another document for use in this document — DOM Level 2 Core:

Synopsis

Node importNode(NodeimportedNode,
                boolean deep)
    throws DOMException;

Arguments

importedNode

The node to be imported.

deep

If true, recursively copy all descendants of importedNode as well.

Returns

A copy of importedNode (and possibly all of its descendants) with its ownerDocument set to this document.

Throws

This method throws a DOMException with a code of NOT_SUPPORTED_ERR if importedNode is a Document or DocumentType node, because those types of nodes cannot be imported.

Description

This method is passed a node defined in another document and returns a copy of the node that is suitable for insertion into this document. If deep is true, all descendants of the node are also copied. The original node and its descendants are not modified in any way. The returned copy has its ownerDocument property set to this document but has a parentNode of null because it has not yet been inserted into the document. Event-listener functions registered on the original node or tree are not copied.

When an Element node is imported, only the attributes that are explicitly specified in the source document are imported with it. When an Attr node is imported, its specified property is automatically set to true.

See Also

Node.cloneNode( )


Name

Document.loadXML( ): populate this Document by parsing a string of XML markup — Internet Explorer:

Synopsis

void loadXML(Stringtext)

Arguments

text

The XML markup to parse.

Description

This IE-specific method parses the specified string of XML text and builds a tree of DOM nodes in the current Document object, discarding any nodes that previously existed in the Document.

This method does not exist on Document objects that represent HTML documents. Before calling loadXML( ), you typically create a new, empty Document to hold the parsed content:

var doc = new ActiveXObject("MSXML2.DOMDocument");
doc.loadXML(markup);

See DOMParser.parseFromString( ) for a non-IE alternative.

See Also

DOMParser.parseFromString( )


Name

Document.removeEventListener( ): see Element.removeEventListener( )


Name

DocumentFragment: adjacent nodes and their subtrees — DOM Level 1 Core: Node → DocumentFragment

Description

The DocumentFragment interface represents a portion—or fragment—of a document. More specifically, it is a list of adjacent nodes and all descendants of each, but without any common parent node. DocumentFragment nodes are never part of a document tree, and the inherited parentNode property is always null. DocumentFragment nodes exhibit a special behavior that makes them quite useful, however: when a request is made to insert a DocumentFragment into a document tree, it is not the DocumentFragment node itself that is inserted but it is instead each child of the DocumentFragment. This makes DocumentFragment useful as a temporary placeholder for nodes that you wish to insert, all at once, into a document. DocumentFragment is also particularly useful for implementing document cut, copy, and paste operations, particularly when combined with the Range interface.

You can create a new, empty DocumentFragment with Document.createDocumentFragment( ), or you can use Range.extractContents( ) or Range.cloneContents( ) to obtain a DocumentFragment that contains a fragment of an existing document.

See Also

Range


Name

DocumentType: the DTD of an XML document — DOM Level 1 XML: Node → DocumentType

Properties

readonly String internalSubset [DOM Level 2]

The unparsed text of the internal subset of the DTD (i.e., the portion of the DTD that appears in the document itself rather than in an external file). The delimiting square brackets of the internal subset are not part of the returned value. If there is no internal subset, this property is null.

readonly String name

The name of the document type. This is the identifier that immediately follows <!DOCTYPE> at the start of an XML document, and it is the same as the tag name of the document's root element.

readonly String publicId [DOM Level 2]

The public identifier of the external subset of the DTD, or null if none is specified.

readonly String systemId [DOM Level 2]

The system identifier of the external subset of the DTD, or null if none is specified.

Description

This infrequently used interface represents the DTD of an XML document. Programmers working exclusively with HTML documents never need to use this interface.

Because a DTD is not part of a document's content, DocumentType nodes never appear in the document tree. If an XML document has a DTD, the DocumentType node for that DTD is available through the doctype property of the Document node.

Although the W3C DOM includes an API for accessing the XML entities and notations defined in a DTD, that API is not documented here. Typical web browsers do not parse the DTDs for the documents they load, and client-side JavaScript can not access those entities and notations. For client-side JavaScript programming, this interface represents only the contents of the <!DOCTYPE> tag, not the contents of the DTD file it references.

DocumentType nodes are immutable and may not be modified in any way.

See Also

Document, DOMImplementation.createDocument( ), DOMImplementation.createDocumentType( )


Name

DOMException: signal exceptions or errors for core DOM objects — DOM Level 1 Core: Object → DOMException

Constants

The following constants define the legal values for the code property of a DOMException object. Note that these constants are static properties of DOMException, not properties of individual exception objects:

unsigned short INDEX_SIZE_ERR = 1

Indicates an out-of-bounds error for an array or string index.

unsigned short DOMSTRING_SIZE_ERR = 2

Indicates that a requested text is too big to fit into a string in the current JavaScript implementation.

unsigned short HIERARCHY_REQUEST_ERR = 3

Indicates that an attempt was made to place a node somewhere illegal in the document-tree hierarchy.

unsigned short WRONG_DOCUMENT_ERR = 4

Indicates an attempt to use a node with a document that is different from the document that created the node.

unsigned short INVALID_CHARACTER_ERR = 5

Indicates that an illegal character is used (in an element name, for example).

unsigned short NO_DATA_ALLOWED_ERR = 6

Not currently used.

unsigned short NO_MODIFICATION_ALLOWED_ERR = 7

Indicates that an attempt was made to modify a node that is read-only and does not allow modifications.

unsigned short NOT_FOUND_ERR = 8

Indicates that a node was not found where it was expected.

unsigned short NOT_SUPPORTED_ERR = 9

Indicates that a method or property is not supported in the current DOM implementation.

unsigned short INUSE_ATTRIBUTE_ERR = 10

Indicates that an attempt was made to associate an Attr with an Element when that Attr node was already associated with a different Element node.

unsigned short INVALID_STATE_ERR = 11 [DOM Level 2]

Indicates an attempt to use an object that is not yet, or is no longer, in a state that allows such use.

unsigned short SYNTAX_ERR = 12 [DOM Level 2]

Indicates that a specified string contains a syntax error. Commonly used with CSS property specifications.

unsigned short INVALID_MODIFICATION_ERR = 13 [DOM Level 2]

Indicates an attempt to modify the type of a CSSRule or CSSValue object.

unsigned short NAMESPACE_ERR = 14 [DOM Level 2]

Indicates an error involving element or attribute namespaces.

unsigned short INVALID_ACCESS_ERR = 15 [DOM Level 2]

Indicates an attempt to access an object in a way that is not supported by the implementation.

Properties

unsigned short code

An error code that provides some detail about what caused the exception. The legal values (and their meanings) for this property are defined by the constants just listed.

Description

A DOMException object is thrown when a DOM method or property is used incorrectly or in an inappropriate context. The value of the code property indicates the general type of exception that occurred. Note that a DOMException may be thrown when reading or writing a property of an object as well as when calling a method of an object.

The descriptions of object properties and methods in this reference include a list of exception types they may throw. Note, however, that certain commonly thrown exceptions are omitted from these lists. A DOMException with a code of NO_MODIFICATION_ALLOWED_ERR is thrown any time an attempt is made to modify a read-only node. Thus, most methods and read/write properties of the Node interface (and of its subinterfaces) may throw this exception. Because read-only nodes appear only in XML documents and not in HTML documents, and because it applies so universally to the methods and writable properties of Node objects, the NO_MODIFICATION_ALLOWED_ERR exception is omitted from the descriptions of those methods and properties.

Similarly, many DOM methods and properties that return strings may throw a DOMException with a code of DOMSTRING_SIZE_ERR, which indicates that the text to be returned is too long to be represented as a string value in the underlying JavaScript implementation. Although this type of exception may theoretically be thrown by many properties and methods, it is very rare in practice and is omitted from the descriptions of those methods and properties.

Note that not all exceptions in the DOM are signaled with a DOMException: exceptions involving the DOM Range module cause a RangeException to be thrown.

See Also

RangeException


Name

DOMImplementation: methods independent of any particular document — DOM Level 1 Core: Object → DOMImplementation

Methods

createDocument( )

Creates a new Document object with a root element (the documentElement property of the returned Document object) of the specified type.

createDocumentType( )

Creates a new DocumentType node.

hasFeature( )

Checks whether the current implementation supports a specified version of a named feature.

Description

The DOMImplementation interface is a placeholder for methods that are not specific to any particular Document object but rather are "global" to an implementation of the DOM. You can obtain a reference to the DOMImplementation object through the implementation property of any Document object.


Name

DOMImplementation.createDocument( ): create a new Document and the specified root element — DOM Level 2 Core:

Synopsis

Document createDocument(StringnamespaceURI,
                        String qualifiedName,
                        DocumentType doctype)
    throws DOMException;

Arguments

namespaceURI

The unique identifier of the namespace of the root element to be created for the document, or null for no namespace.

qualifiedName

The name of the root element to be created for this document. If namespaceURI is not null, this name should include a namespace prefix and a colon.

doctype

The DocumentType object for the newly created Document, or null if none is desired.

Returns

A Document object with its documentElement property set to a root Element node of the specified type.

Throws

This method may throw a DOMException with the following code values in the following circumstances:

INVALID_CHARACTER_ERR

qualifiedName contains an illegal character.

NAMESPACE_ERR

qualifiedName is malformed or there is a mismatch between qualifiedName and namespaceURI.

NOT_SUPPORTED_ERR

The current implementation does not support XML documents and has not implemented this method.

WRONG_DOCUMENT_ERR

doctype is already in use for another document or was created by a different DOMImplementation object.

Description

This method creates a new XML Document object and the specified root documentElement object for that document. If the doctype argument is non-null, the ownerDocument property of this DocumentType object is set to the newly created document.

This method is used to create XML documents and may not be supported by HTML-only implementations.

See Also

DOMImplementation.createDocumentType( )


Name

DOMImplementation.createDocumentType( ): create a DocumentType node — DOM Level 2 Core:

Synopsis

DocumentType createDocumentType(StringqualifiedName,
                                String publicId,
                                String systemId)
    throws DOMException;

Arguments

qualifiedName

The name of the document type. If you are using XML namespaces, this may be a qualified name that specifies a namespace prefix and a local name separated by a colon.

publicId

The public identifier of the document type, or null.

systemId

The system identifier of the document type, or null. This argument typically specifies the local filename of a DTD file.

Returns

A new DocumentType object with an ownerDocument property of null.

Throws

This method may throw a DOMException with one of the following code values:

INVALID_CHARACTER_ERR

qualifiedName contains an illegal character.

NAMESPACE_ERR

qualifiedName is malformed.

NOT_SUPPORTED_ERR

The current implementation does not support XML documents and has not implemented this method.

Description

This method creates a new DocumentType node. This method specifies only an external subset of the document type. As of Level 2, the DOM standard does not provide any way to specify an internal subset, and the returned DocumentType does not define any Entity or Notation nodes. This method is useful only with XML documents.


Name

DOMImplementation.hasFeature( ): determine whether the implementation supports a feature — DOM Level 1 Core:

Synopsis

boolean hasFeature(Stringfeature,
                   String version);

Arguments

feature

The name of the feature for which support is being tested. The set of valid feature names for the DOM Level 2 standard is listed in the table in the Description. Feature names are case-insensitive.

version

The feature version number for which support is being tested, or null or the empty string "" if support for any version of the feature is sufficient. In the Level 2 DOM specification, supported version numbers are 1.0 and 2.0.

Returns

true if the implementation completely supports the specified version of the specified feature; false otherwise. If no version number is specified, the method returns true if the implementation completely supports any version of the specified feature.

Description

The W3C DOM standard is modular, and implementations are not required to implement all modules or features of the standard. This method tests whether a DOM implementation supports a named module of the DOM specification. The availability information for each entry in this DOM reference includes the name of the module. Note that although Internet Explorer 5 and 5.5 include partial support for the DOM Level 1 specification, this important method is not supported before IE 6.

The complete set of module names that may be used as the feature argument are shown in the following table:

Feature

Description

Core

Node, Element, Document, Text, and the other fundamental interfaces required by all DOM implementations are implemented. All conforming implementations must support this module.

HTML

HTMLElement, HTMLDocument, and the other HTML-specific interfaces are implemented.

XML

Entity, EntityReference, ProcessingInstruction, Notation, and the other node types that are useful only with XML documents are implemented.

StyleSheets

Simple interfaces describing generic stylesheets are implemented.

CSS

Interfaces that are specific to CSS stylesheets are implemented.

CSS2

The CSS2Properties interface is implemented.

Events

The basic event-handling interfaces are implemented.

UIEvents

The interfaces for user-interface events are implemented.

MouseEvents

The interfaces for mouse events are implemented.

HTMLEvents

The interfaces for HTML events are implemented.

MutationEvents

The interfaces for document mutation events are implemented.

Range

The interfaces for manipulating ranges of a document are implemented.

Traversal

The interfaces for advanced document traversal are implemented.

Views

The interfaces for document views are implemented.

Example

You might use this method in code like the following:

// Check whether the browser supports the DOM Level 2 Range API
if (document.implementation &&
    document.implementation.hasFeature &&
    document.implementation.hasFeature("Range", "2.0")) {
  // If so, use it here...
}
else {
  // If not, fall back on code that doesn't require Range objects
}

See Also

Node.isSupported( )


Name

DOMParser: parses XML markup to create a Document — Firefox 1.0, Safari 2.01, Opera 7.60: Object → DOMParser

Constructor

new DOMParser( )

Methods

parseFromString( )

Parses XML markup and returns a Document.

Description

A DOMParser object parses XML text and returns an XML Document object. To use a DOMParser, instantiate one with the no-argument constructor and then call its parseFromString( ) method:

var doc = (new DOMParser( )).parseFromString(text);

Internet Explorer does not support the DOMParser object. Instead, it supports XML parsing with Document.loadXML( ). Note that the XMLHttpRequest object can also parse XML documents. See the responseXML property of XMLHttpRequest.

See Also

Document.loadXML( ), XMLHttpRequest; Chapter 21, JavaScript and XML


Name

DOMParser.parseFromString( ): parse XML markup

Synopsis

Document parseFromString(Stringtext,
                         String contentType)

Arguments

text

The XML markup to parse.

contentType

The content type of the text. This may be one of "text/xml", "application/xml", or "application/xhtml+xml". Note that "text/html" is not supported.

Returns

A Document object that holds the parsed representation of text. See Document.loadXML( ) for an IE-specific alternative to this method.


Name

Element: an HTML or XML element — DOM Level 1 Core: Node → Element

Subinterfaces

HTMLElement

Properties

readonly String tagName

The tag name of the element. This is the string "P" for an HTML <p> element, for example. For HTML documents, the tag name is returned in uppercase, regardless of its capitalization in the document source. XML documents are case-sensitive, and the tag name is returned exactly as it is written in the document source. This property has the same value as the inherited nodeName property of the Node interface.

Methods

addEventListener( )

Adds an event-handler function to the set of event handlers for this element. This is a DOM-standard method supported by all modern browsers except IE.

attachEvent( )

Adds an event-handler function to the set of handlers for this element. This is the IE-specific alternative to addEventListener( ).

detachEvent( )

Removes an event-handler function from this element. This is the IE-specific alternative to the standard removeEventListener( ) method.

dispatchEvent( )

Dispatches a synthetic event to this node.

getAttribute( )

Returns the value of a named attribute as a string.

getAttributeNS( )

Returns the string value of an attribute specified by local name and namespace URI. Useful only with XML documents that use namespaces.

getAttributeNode( )

Returns the value of a named attribute as an Attr node.

getAttributeNodeNS( )

Returns the Attr value of an attribute specified by local name and namespace URI. Useful only with XML documents that use namespaces.

getElementsByTagName( )

Returns an array (technically, a NodeList) of all descendant Element nodes of this element that have the specified tag name, in the order in which they appear in the document.

getElementsByTagNameNS( )

Like getElementsByTagName( ), except that the element tag name is specified by local name and namespace URI. Useful only with XML documents that use namespaces.

hasAttribute( )

Returns true if this element has an attribute with the specified name, or false otherwise. Note that this method returns true if the named attribute is explicitly specified in the document source or if the document's DTD specifies a default value for the named attribute.

hasAttributeNS( )

Like hasAttribute( ), except that the attribute is specified by a combination of local name and namespace URI. This method is useful only with XML documents that use namespaces.

removeAttribute( )

Deletes the named attribute from this element. Note, however, that this method deletes only attributes that are explicitly specified in the document source for this element. If the DTD specifies a default value for this attribute, that default becomes the new value of the attribute.

removeAttributeNode( )

Removes the specified Attr node from the list of attributes for this element. Note that this works only to remove attributes that are explicitly specified in the document source for this attribute. If the DTD specifies a default value for the removed attribute, a new Attr node is created to represent the default value of the attribute.

removeAttributeNS( )

Like removeAttribute( ), except that the attribute to be removed is specified by a combination of local name and namespace URI. Useful only for XML documents that use namespaces.

removeEventListener( )

Removes an event-handler function from the set of handlers for this element. This is a standard DOM method implemented by all modern browsers except IE, which uses detachEvent( ).

setAttribute( )

Sets the named attribute to the specified string value. If an attribute with that name does not already exist, a new attribute is added to the element.

setAttributeNode( )

Adds the specified Attr node to the list of attributes for this element. If an attribute with the same name already exists, its value is replaced.

setAttributeNodeNS( )

Like setAttributeNode( ), but this method is suitable for use with nodes returned by Document.createAttributeNS( ). Useful only with XML documents that use namespaces.

setAttributeNS( )

Like setAttribute( ), except that the attribute to be set is specified by the combination of a local name and a namespace URI. Useful only with XML documents that use namespaces.

Description

The Element interface represents HTML or XML elements or tags. The tagName property specifies the name of the element. The documentElement property of a Document refers to the root Element object for that document. The body property of the HTMLDocument object is similar: it refers to the <body> element of the document. To locate a specific named element in an HTML document, use Document.getElementById( ) (and give the element a unique name with the id attribute). To locate elements by tag name, use getElementsByTagName( ), which is a method of both Element and Document. In HTML documents, you can also use similar HTMLDocument.getElementsByName( ) to look up elements based on the value of their name attribute. Finally, you can create new Element objects for insertion into a document with Document.createElement( ).

The addEventListener( ) method (and its IE-specific alternative attachEvent( )) provide a way to register event-handler functions for specific types of events on the element. See Chapter 17, Events and Event Handling for complete details. Technically, addEventListener( ), removeEventListener( ), and dispatchEvent( ) are defined by the EventTarget interface of the DOM Level 2 Events specification. Since all Element objects implement EventTarget, the methods are listed here instead.

The various other methods of this interface provide access to the attributes of the element. In HTML documents (and many XML documents), all attributes have simple string values, and you can use the simple methods getAttribute( ) and setAttribute( ) for any attribute manipulation you need to do.

If you are working with XML documents that may contain entity references as part of attribute values, you will have to work with Attr objects and their subtree of nodes. You can get and set the Attr object for an attribute with getAttributeNode( ) and setAttributeNode( ), or you can iterate through the Attr nodes in the attributes[] array of the Node interface. If you are working with an XML document that uses XML namespaces, you need to use the various methods whose names end with "NS".

In the DOM Level 1 specification, the normalize( ) method was part of the Element interface. In the Level 2 specification, normalize( ) is instead part of the Node interface. All Element nodes inherit this method and can still use it.


Name

Element.addEventListener( ): register an event handler — DOM Level 2 Events:

Synopsis

void addEventListener(Stringtype,
                      Function listener,
                      boolean useCapture);

Arguments

type

The type of event for which the event listener is to be invoked. For example, "load", "click", or "mousedown".

listener

The event-listener function that is invoked when an event of the specified type is dispatched to this element. When invoked, this listener function is passed an Event object and is invoked as a method of the element on which it is registered.

useCapture

If true, the specified listener is to be invoked only during the capturing phase of event propagation. The more common value of false means that the listener is not invoked during the capturing phase but instead is invoked when this node is the actual event target or when the event bubbles up to this node from its original target.

Description

This method adds the specified event-listener function to the set of listeners registered on this node to handle events of the specified type. If useCapture is true, the listener is registered as a capturing event listener. If useCapture is false, it is registered as a normal event listener.

addEventListener( ) may be called multiple times to register multiple event handlers for the same type of event on the same node. Note, however, that the DOM makes no guarantees about the order in which multiple event handlers are invoked.

If the same event-listener function is registered twice on the same node with the same type and useCapture arguments, the second registration is simply ignored. If a new event listener is registered on this node while an event is being handled at this node, the new event listener is not invoked for that event.

When a node is duplicated with Node.cloneNode( ) or Document.importNode( ), the event listeners registered for the original node are not copied.

This method is also defined by, and works analogously on, the Document and Window objects.


Name

Element.attachEvent( ): register an event handler — IE 4:

Synopsis

void attachEvent(Stringtype,
                 Function listener);

Arguments

type

The type of event for which the event listener is to be invoked, with a leading "on" prefix. For example, "onload", "onclick", or "onmousedown".

listener

The event listener function that is invoked when an event of the specified type is dispatched to this element. This function is not passed any arguments but can obtain the Event object from the event property of the Window object.

Description

This method is an IE-specific event registration method. It serves the same purpose as the standard addEventListener( ) method (which IE does not support) but is different from that function in several important ways:

  • Since the IE event model does not support event capturing, attachEvent( ) and detachEvent( ) expect only two arguments: the event type and the handler function.

  • The event-handler names passed to the IE methods should include the "on" prefix. For example, use "onclick" with attachEvent( ) instead of "click" for addEventListener( ).

  • Functions registered with attachEvent( ) are invoked with no Event object argument. Instead, they must read the event property of the Window object.

  • Functions registered with attachEvent( ) are invoked as global functions, rather than as methods of the document element on which the event occurred. That is, when an event handler registered with attachEvent( ) executes, the this keyword refers to the Window object, not to the event's target element.

  • attachEvent( ) allows the same event-handler function to be registered more than once. When an event of the specified type occurs, the registered function is invoked as many times as it is registered.

This method is also defined by, and works analogously on, the Document and Window objects.

See Also

Element.addEventListener( ), Event; Chapter 17, Events and Event Handling


Name

Element.detachEvent( ): delete an event listener — IE 4:

Synopsis

void detachEvent(Stringtype,
                 Function listener)

Arguments

type

The type of event for which the event listener is to be deleted, with an "on" prefix. For example: "onclick".

listener

The event-listener function that is to be removed.

Description

This method undoes the event-handler function registration performed by the attachEvent( ) method. It is the IE-specific analog to removeEventListener( ). To remove an event handler function for an element, simply invoke detachEvent with the same arguments you originally passed to attachEvent( ).

This method is also defined by, and works analogously on, the Document and Window objects.


Name

Element.dispatchEvent( ): dispatch a synthetic event to this node — DOM Level 2 Events:

Synopsis

boolean dispatchEvent(Eventevt)
    throws EventException;

Arguments

evt

The Event object to be dispatched.

Returns

false if the preventDefault( ) method of evt is called at any time during the propagation of the event, or true otherwise.

Throws

This method throws an exception if the Event object evt is not initialized, or if its type property is null or the empty string.

Description

This method dispatches a synthetic event created with Document.createEvent( ) and initialized with the initialization method defined by the Event interface or one of its subinterfaces. The node on which this method is called becomes the target of the event, but the event first propagates down the document tree during the capturing phase, and then, if the bubbles property of the event is true, it bubbles up the document tree after being handled at the event target itself.

See Also

Document.createEvent( ), Event.initEvent( ), MouseEvent.initMouseEvent( )


Name

Element.getAttribute( ): return the string value of a named attribute — DOM Level 1 Core:

Synopsis

String getAttribute(Stringname);

Arguments

name

The name of the attribute whose value is to be returned.

Returns

The value of the named attribute as a string. If the attribute is not defined, this method is supposed to return an empty string. Some implementations return null in this case, however.

Description

getAttribute( ) returns the value of a named attribute of an element. Note that the HTMLElement object defines JavaScript properties that match each of the standard HTML attributes, so you need to use this method with HTML documents only if you are querying the value of nonstandard attributes.

In XML documents, attribute values are not available directly as element properties and must be looked up by calling this method. For XML documents that use namespaces, use getAttributeNS( ).

Example

The following code illustrates two different ways of obtaining an attribute value for an HTML <img> element:

// Get all images in the document
var images = document.body.getElementsByTagName("img");
// Get the src attribute of the first one
var src0 = images[0].getAttribute("src");
// Get the src attribute of the second simply by reading the property
var src1 = images[1].src;

See Also

Element.getAttributeNode( ), Element.getAttributeNS( ), Node


Name

Element.getAttributeNode( ): return the Attr node for the named attribute — DOM Level 1 Core:

Synopsis

Attr getAttributeNode(Stringname);

Arguments

name

The name of the desired attribute.

Returns

An Attr node that represents the value of the named attribute, or null if this element has no such attribute.

Description

getAttributeNode( ) returns an Attr node that represents the value of a named attribute. Note that this Attr node can also be obtained through the attributes property inherited from the Node interface.

See Also

Element.getAttribute( ), Element.getAttributeNodeNS( )


Name

Element.getAttributeNodeNS( ): return the Attr node for an attribute with a namespace — DOM Level 2 Core:

Synopsis

Attr getAttributeNodeNS(StringnamespaceURI,
                        String localName);

Arguments

namespaceURI

The URI that uniquely identifies the namespace of this attribute, or null for no namespace.

localName

The identifier that specifies the name of the attribute within its namespace.

Returns

The Attr node that represents the value of the specified attribute, or null if this element has no such attribute.

Description

This method works like getAttributeNode( ), except that the attribute is specified by the combination of a namespace URI and a local name defined within that namespace. This method is useful only with XML documents that use namespaces.

See Also

Element.getAttributeNode( ), Element.getAttributeNS( )


Name

Element.getAttributeNS( ): get the value of an attribute that uses namespaces — DOM Level 2 Core:

Synopsis

String getAttributeNS(StringnamespaceURI,
                      String localName);

Arguments

namespaceURI

The URI that uniquely identifies the namespace of this attribute or null for no namespace.

localName

The identifier that specifies the name of the attribute within its namespace.

Returns

The value of the named attribute, as a string. If the attribute is not defined, this method is supposed to return an empty string, but some implementations return null instead.

Description

This method works just like the getAttribute( ) method, except that the attribute is specified by a combination of namespace URI and local name within that namespace. This method is useful only with XML documents that use namespaces.

See Also

Element.getAttribute( ), Element.getAttributeNodeNS( )


Name

Element.getElementsByTagName( ): find descendant elements with a specified tag name — DOM Level 1 Core:

Synopsis

Element[] getElementsByTagName(Stringname);

Arguments

name

The tag name of the desired elements, or the value "*" to specify that all descendant elements should be returned, regardless of their tag names.

Returns

A read-only array (technically, a NodeList) of Element objects that are descendants of this element and have the specified tag name.

Description

This method traverses all descendants of this element and returns an array (really a NodeList object) of Element nodes representing all document elements with the specified tag name. The elements in the returned array appear in the same order in which they appear in the source document.

Note that the Document interface also has a getElementsByTagName( ) method that works just like this one but that traverses the entire document, rather than just the descendants of a single element. Do not confuse this method with HTMLDocument.getElementsByName( ), which searches for elements based on the value of their name attributes rather than by their tag names.

Example

You can find all <div< tags in a document with code like the following:

var divisions = document.body.getElementsByTagName("div");

And you can find all <p> tags within the first <div> tag with code like this:

var paragraphs = divisions[0].getElementsByTagname("p");

See Also

Document.getElementById( )
Document.getElementsByTagName( )
HTMLDocument.getElementsByName( )

Name

Element.getElementsByTagNameNS( ): return descendant elements with the specified name and namespace — DOM Level 2 Core:

Synopsis

Node[] getElementsByTagNameNS(StringnamespaceURI,
                              String localName);

Arguments

namespaceURI

The URI that uniquely identifies the namespace of the element.

localName

The identifier that specifies the name of the element within its namespace.

Returns

A read-only array (technically, a NodeList) of Element objects that are descendants of this element and have the specified name and namespace.

Description

This method works like getElementsByTagName( ), except that the tag name of the desired elements is specified as a combination of a namespace URI and a local name defined within that namespace. This method is useful only with XML documents that use namespaces.

See Also

Document.getElementsByTagNameNS( ), Element.getElementsByTagName( )


Name

Element.hasAttribute( ): determine whether this element has a specified attribute — DOM Level 2 Core:

Synopsis

boolean hasAttribute(Stringname);

Arguments

name

The name of the desired attribute.

Returns

true if this element has a specified or default value for the named attribute, and false otherwise.

Description

This method determines whether an element has an attribute with the specified name but does not return the value of that attribute. Note that hasAttribute( ) returns true if the named attribute is explicitly specified in the document and also if the named attribute has a default value specified by the internal subset of the document type.

See Also

Element.getAttribute( ), Element.setAttribute( )


Name

Element.hasAttributeNS( ): determine whether this element has a specified attribute — DOM Level 2 Core:

Synopsis

boolean hasAttributeNS(StringnamespaceURI,
                       String localName);

Arguments

namespaceURI

The unique namespace identifier for the attribute, or null for no namespace.

localName

The name of the attribute within the specified namespace.

Returns

true if this element has an explicitly specified value or a default value for the specified attribute; false otherwise.

Description

This method works like hasAttribute( ), except that the attribute to be checked for is specified by namespace and name. This method is useful only with XML documents that use namespaces.

See Also

Element.getAttributeNS( ), Element.hasAttribute( ), Element.setAttributeNS( )


Name

Element.removeAttribute( ): delete a named attribute of an element — DOM Level 1 Core:

Synopsis

void removeAttribute(Stringname);

Arguments

name

The name of the attribute to be deleted.

Throws

This method may throw a DOMException with a code of NO_MODIFICATION_ALLOWED_ERR if this element is read-only and does not allow its attributes to be removed.

Description

removeAttribute( ) deletes a named attribute from this element. If the named attribute has a default value specified by the document type, subsequent calls to getAttribute( ) return that default value. Attempts to remove nonexistent attributes or attributes that are not specified but have a default value are silently ignored.

See Also

Element.getAttribute( ), Element.setAttribute( ), Node


Name

Element.removeAttributeNode( ): remove an Attr node from an element — DOM Level 1 Core:

Synopsis

Attr removeAttributeNode(AttroldAttr)
    throws DOMException;

Arguments

oldAttr

The Attr node to be removed from the element.

Returns

The Attr node that was removed.

Throws

This method may throw a DOMException with the following code values:

NO_MODIFICATION_ALLOWED_ERR

This element is read-only and does not allow attributes to be removed.

NOT_FOUND_ERR

oldAttr is not an attribute of this element.

Description

This method removes (and returns) an Attr node from the set of attributes of an element. If the removed attribute has a default value specified by the DTD, a new Attr is added representing this default value. If is often simpler to use removeAttribute( ) instead of this method.

See Also

Attr, Element.removeAttribute( )


Name

Element.removeAttributeNS( ): delete an attribute specified by name and namespace — DOM Level 2 Core:

Synopsis

void removeAttributeNS(StringnamespaceURI,
                       String localName);

Arguments

namespaceURI

The unique identifier of the namespace of the attribute, or null for no namespace.

localName

The name of the attribute within the specified namespace.

Throws

This method may throw a DOMException with a code of NO_MODIFICATION_ALLOWED_ERR if this element is read-only and does not allow its attributes to be removed.

Description

removeAttributeNS( ) works just like removeAttribute( ), except that the attribute to be removed is specified by name and namespace instead of simply by name. This method is useful only with XML documents that use namespaces.

See Also

Element.getAttributeNS( ), Element.removeAttribute( ), Element.setAttributeNS( )


Name

Element.removeEventListener( ): delete an event listener — DOM Level 2 Events:

Synopsis

void removeEventListener(Stringtype,
                         Function listener,
                         boolean useCapture);

Arguments

type

The type of event for which the event listener is to be deleted.

listener

The event-listener function that is to be removed.

useCapture

true if a capturing event listener is to be removed; false if a normal event listener is to be removed.

Description

This method removes the specified event-listener function. The type and useCapture arguments must be the same as they are in the corresponding call to addEventListener( ). If no event listener is found that matches the specified arguments, this method does nothing.

Once an event-listener function has been removed by this method, it will no longer be invoked for the specified type of event on this node. This is true even if the event listener is removed by another event listener registered for the same type of event on the same node.

This method is also defined by, and works analogously on, the Document and Window objects.


Name

Element.setAttribute( ): create or change an attribute of an element — DOM Level 1 Core:

Synopsis

void setAttribute(Stringname,
                  String value)
    throws DOMException;

Arguments

name

The name of the attribute to be created or modified.

value

The string value of the attribute.

Throws

This method may throw a DOMException with the following code values:

INVALID_CHARACTER_ERR

The name argument contains a character that is not allowed in HTML or XML attribute names.

NO_MODIFICATION_ALLOWED_ERR

This element is read-only and does not allow modifications to its attributes.

Description

This method sets the specified attribute to the specified value. If no attribute by that name already exists, a new one is created.

Note that HTMLElement objects of an HTML document define JavaScript properties that correspond to all standard HTML attributes. Thus, you need to use this method only if you want to set a nonstandard attribute.

Example

// Set the TARGET attribute of all links in a document
var links = document.body.getElementsByTagName("a");
for(var i = 0; i < links.length; i++) {
    links[i].setAttribute("target", "newwindow");
    // Or more easily: links[i].target = "newwindow"
}

See Also

Element.getAttribute( ), Element.removeAttribute( ), Element.setAttributeNode( )


Name

Element.setAttributeNode( ): add a new Attr node to an Element — DOM Level 1 Core:

Synopsis

Attr setAttributeNode(AttrnewAttr)
    throws DOMException;

Arguments

newAttr

The Attr node that represents the attribute to be added or whose value is to be modified.

Returns

The Attr node that was replaced by newAttr, or null if no attribute was replaced.

Throws

This method may throw a DOMException with a code of the following values:

INUSE_ATTRIBUTE_ERR

newAttr is already a member of the attribute set of some other Element node.

NO_MODIFICATION_ALLOWED_ERR

The Element node is read-only and does not allow modifications to its attributes.

WRONG_DOCUMENT_ERR

newAttr has a different ownerDocument property than the Element on which it is being set.

Description

This method adds a new Attr node to the set of attributes of an Element node. If an attribute with the same name already exists for the Element, newAttr replaces that attribute, and the replaced Attr node is returned. If no such attribute already exists, this method defines a new attribute for the Element.

It is usually easier to use setAttribute( ) instead of setAttributeNode( ).

See Also

Attr, Document.createAttribute( ), Element.setAttribute( )


Name

Element.setAttributeNodeNS( ): add a namespace Attr node to an Element — DOM Level 2 Core:

Synopsis

Attr setAttributeNodeNS(AttrnewAttr)
    throws DOMException;

Arguments

newAttr

The Attr node that represents the attribute to be added or whose value is to be modified.

Returns

The Attr node that was replaced by newAttr, or null if no attribute was replaced.

Throws

This method throws exceptions for the same reasons as setAttributeNode( ). It may also throw a DOMException with a code of NOT_SUPPORTED_ERR to signal that the method is not implemented because the current implementation does not support XML documents and namespaces.

Description

This method works just like setAttributeNode( ), except that it is designed for use with Attr nodes that represent attributes specified by namespace and name.

This method is useful only with XML documents that use namespaces. It may be unimplemented (i.e., throw a NOT_SUPPORTED_ERR) on browsers that do not support XML documents.

See Also

Attr, Document.createAttributeNS( ), Element.setAttributeNS( ), Element.setAttributeNode( )


Name

Element.setAttributeNS( ): create or change an attribute with a namespace — DOM Level 2 Core:

Synopsis

void setAttributeNS(StringnamespaceURI,
                    String qualifiedName,
                    String value)
    throws DOMException;

Arguments

namespaceURI

The URI that uniquely identifies the namespace of the attribute to be set or created, or null for no namespace.

qualifiedName

The name of the attribute, specified as an optional namespace prefix and colon followed by the local name within the namespace.

value

The new value of the attribute.

Throws

This method may throw a DOMException with the following code values:

INVALID_CHARACTER_ERR

The qualifiedName argument contains a character that is not allowed in HTML or XML attribute names.

NAMESPACE_ERR

qualifiedName is malformed, or there is a mismatch between the namespace prefix of qualifiedName and the namespaceURI argument.

NO_MODIFICATION_ALLOWED_ERR

This element is read-only and does not allow modifications to its attributes.

NOT_SUPPORTED_ERR

The DOM implementation does not support XML documents.

Description

This method is like setAttribute( ), except that the attribute to be created or set is specified by a namespace URI and a qualified name that consists of a namespace prefix, a colon, and a local name within the namespace.

This method is useful only with XML documents that use namespaces. It may be unimplemented (i.e., throw a NOT_SUPPORTED_ERR) on browsers that do not support XML documents.

See Also

Element.setAttribute( ), Element.setAttributeNode( )


Name

Event: information about an event — DOM Level 2 Events, IE: Object → Event

Subinterfaces

UIEvent

Standard Properties

The following properties are defined by the DOM Level 2 Events standard. See also KeyEvent, MouseEvent, and UIEvent for additional type-specific event properties:

readonly boolean bubbles

true if the event is of a type that bubbles (unless stopPropagation( ) is called); false otherwise.

readonly boolean cancelable

true if the default action associated with the event can be canceled with preventDefault( ); false otherwise.

readonly Object currentTarget

The Element, Document, or Window that is currently handling this event. During capturing and bubbling, this is different from target.

readonly unsigned short eventPhase

The current phase of event propagation. The value is one of the following three constants, which represent the capturing phase, normal event dispatch, and the bubbling phase:

eventPhase Constant

Value

Event.CAPTURING_PHASE

1

Event.AT_TARGET

2

Event.BUBBLING_PHASE

3

readonly Object target

The target node for this event—i.e., the Element, Document, or Window that generated the event.

readonly Date timeStamp

The date and time at which the event occurred (or, technically, at which the Event object was created). Implementations are not required to provide valid time data in this field, and if they do not, the getTime( ) method of this Date object should return 0. See Date in Part III, “Core JavaScript Reference” of this book.

readonly String type

The name of the event that this Event object represents. This is the name under which the event handler was registered, or the name of the event-handler property with the leading "on" removed—for example, "click", "load", or "submit".

IE Properties

Internet Explorer does not (at least as of IE 7) support the standard DOM event model, and IE's Event object defines a completely different set of properties. The IE event model does not define an inheritance hierarchy for different types of events, so all properties relevant to any type of event are listed here:

boolean altKey

Whether the Alt key was held down when the event occurred.

integer button

For mouse events, button specifies which mouse button or buttons were pressed. This value is a bit mask: the 1 bit is set if the left button was pressed, the 2 bit is set if the right button was pressed, and the 4 bit is set if the middle button (of a three-button mouse) was pressed.

boolean cancelBubble

If an event handler wants to stop an event from being propagated up to containing objects, it must set this property to true.

integer clientX, clientY

The coordinates, relative to the web browser page, at which the event occurred.

boolean ctrlKey

Whether the Ctrl key was held down when the event occurred.

Element fromElement

For mouseover and mouseout events, fromElement refers to the object from which the mouse pointer is moving.

integer keyCode

For keypress events, this property specifies the Unicode character code generated by the key that was struck. For keydown and keyup events, it specifies the virtual keycode of the key that was struck. Virtual keycodes may be dependent on the keyboard layout in use.

integer offsetX, offsetY

The coordinates at which the event occurred within the coordinate system of the event's source element (see srcElement).

boolean returnValue

If this property is set, its value takes precedence over the value actually returned by an event handler. Set this property to false to cancel the default action of the source element on which the event occurred.

integer screenX, screenY

Specify the coordinates, relative to the screen, at which the event occurred.

boolean shiftKey

Whether the Shift key was held down when the event occurred.

Object srcElement

A reference to the Window, Document, or Element object that generated the event.

Element toElement

For mouseover and mouseout events, toElement refers to the object into which the mouse pointer is moving.

String type

The type of the event. Its value is the name of the event handler minus the "on" prefix. So when the onclick( ) event handler is invoked, the type property of the Event object is "click".

integer x, y

Specify the X and Y coordinates at which the event occurred relative to the document or the innermost containing element that is dynamically positioned using CSS.

Standard Methods

The following methods are defined by the DOM Level 2 Events specification. In the IE event model, the Event object has no methods:

initEvent( )

Initializes the properties of a newly created Event object.

preventDefault( )

Tells the web browser not to perform the default action associated with this event, if there is one. If the event is not of a type that is cancelable, this method has no effect.

stopPropagation( )

Stops the event from propagating any further through the capturing, target, or bubbling phases of event propagation. After this method is called, any other event handlers for the same event on the same node are called, but the event is not dispatched to any other nodes.

Description

The properties of an Event object provide details about an event, such as the element on which the event occurred. The methods of an Event object can control the propagation of the event. The DOM Level 2 Events standard defines a standard event model, which is implemented by all modern browsers except Internet Explorer, which defines its own, incompatible model. This reference page lists the properties of both the standard Event object and also of the IE Event object. See Chapter 17, Events and Event Handling for further details about the two event models. In particular, however, note that an Event object is passed to event-handler functions in the standard event model but is stored in the event property of the Window object in the IE event model.

In the standard event model, various subinterfaces of Event define additional properties that provide details pertinent to specific types of events. In the IE event model, there is only this one type of Event object, and it is used for events of all types.

See Also

KeyEvent, MouseEvent, UIEvent; Chapter 17, Events and Event Handling


Name

Event.initEvent( ): initialize the properties of a new event — DOM Level 2 Events

Synopsis

void initEvent(StringeventTypeArg,
               boolean canBubbleArg,
               boolean cancelableArg);

Arguments

eventTypeArg

The type of event. This may be one of the predefined event types, such as "load" or "submit", or it may be a custom type of your own choosing. Names that begin with "DOM" are reserved, however.

canBubbleArg

Whether the event will bubble.

cancelableArg

Whether the event can be canceled with preventDefault( ).

Description

This method initializes the type, bubbles, and cancelable properties of a synthetic Event object created by Document.createEvent( ). This method may be called on newly created Event objects only before they have been dispatched with the dispatchEvent( ) method of the Document or Element objects.

See Also

Document.createEvent( ), MouseEvent.initMouseEvent( ), UIEvent.initUIEvent( )


Name

Event.preventDefault( ): cancel default action of an event — DOM Level 2 Events

Synopsis

void preventDefault( );

Description

This method tells the web browser not to perform the default action (if any) associated with this event. For example, if the type property is "submit", any event handler called during any phase of event propagation can prevent form submission by calling this method. Note that if the cancelable property of an Event object is false, either there is no default action or there is a default action that cannot be prevented. In either case, calling this method has no effect.


Name

Event.stopPropagation( ): do not dispatch an event any further — DOM Level 2 Events

Synopsis

void stopPropagation( );

Description

This method stops the propagation of an event and prevents it from being dispatched to any other Document nodes. It may be called during any phase of event propagation. Note that this method does not prevent other event handlers on the same Document node from being called, but it does prevent the event from being dispatched to any other nodes.


Name

ExternalInterface: a bidirectional interface to Flash — ActionScript Object in Flash 8

Static Properties

available

Indicates whether Flash may communicate with JavaScript. This will be false if the security policy for the browser prevents communication.

Static Functions

addCallback( )

Exports an ActionScript method so it can be invoked from JavaScript.

call( )

Invokes a JavaScript function from ActionScript.

Description

ExternalInterface is an ActionScript object defined by the Adobe Flash plug-in in version 8 and later. It defines two static functions for use by ActionScript code in Flash movies. These functions enable communication between JavaScript code in a web browser and ActionScript code in a Flash movie.


Name

ExternalInterface.addCallback( ): expose an ActionScript method for execution from JavaScript — ActionScript function in Flash 8

Synopsis

boolean ExternalInterface.addCallback(Stringname,
                                      Object instance,
                                      Function func)

Arguments

name

The name of the JavaScript function to be defined. Invoking a JavaScript function with this name causes the Flash player to invoke the ActionScript function func as a method of the instance object.

instance

The ActionScript object on which func is to be invoked or null. This argument becomes the value of the this keyword when func is invoked.

func

The ActionScript function that is invoked when the JavaScript function named name is invoked.

Returns

true on success or false on failure.

Description

This static function is used by ActionScript code in a Flash movie to enable JavaScript code in a web browser to invoke ActionScript code. When addCallback( ) is invoked, it defines a top-level JavaScript function called name which, when invoked, calls the ActionScript function func as a method of the ActionScript object instance.

The arguments to the JavaScript function are converted and passed to func, and the return value of func is converted and becomes the return value of the JavaScript function. Arguments and return values can be primitive numbers, strings, boolean values, and objects and arrays that contain primitive values. However, it is not possible, for example, to pass a client-side JavaScript object such as a Window or Document to an ActionScript function. It is also not possible to return a Flash-specific ActionScript object such as a MovieClip to JavaScript.


Name

ExternalInterface.call( ): call a JavaScript function from ActionScript — ActionScript function in Flash 8

Synopsis

Object ExternalInterface.call(Stringname,
                              Object args...)

Arguments

name

The name of the JavaScript function to invoke.

args...

Zero or more arguments to convert and pass to the JavaScript function.

Returns

The return value of the JavaScript function, converted to an ActionScript value.

Description

This static function is used by ActionScript code in a Flash movie to invoke a JavaScript function defined in the web browser in which the Flash movie is embedded. See ExternalInterface.addCallback( ) for a discussion about the conversion of function arguments and return values between ActionScript and JavaScript.


Name

FileUpload: see Input


Name

FlashPlayer: plug-in for Flash movies — Flash 2.0

Methods

GetVariable( )

Returns the value of a variable defined by a Flash movie.

GotoFrame( )

Jumps to the specified frame number in the movie.

IsPlaying( )

Checks whether the movie is playing.

LoadMovie( )

Loads an auxiliary Flash movie and displays it at a specified layer or level of the current movie.

Pan( )

Moves the viewport of the movie.

PercentLoaded( )

Determines how much of the movie has loaded.

Play( )

Begins playing the movie.

Rewind( )

Rewinds the movie to its first frame.

SetVariable( )

Sets a variable defined by a Flash movie.

SetZoomRect( )

Sets the area of the movie displayed by the Flash player.

StopPlay( )

Stops the movie.

TotalFrames( )

Returns the length of the movie, as a number of frames.

Zoom( )

Changes the size of the movie's viewport.

Description

A FlashPlayer object represents a Flash movie embedded in a web page and the instance of the Flash plug-in that is playing that movie. You can obtain a FlashPlayer object using Document.getElementById( ), for example, to get the <embed> or <object> tag that embeds the movie in the web page.

Once you have obtained a FlashPlayer object, you can use the various JavaScript methods it defines to control playback of the movie and to interact with it by setting and querying variables. Note that FlashPlayer methods all begin with a capital letter, which is not a common naming convention in client-side JavaScript.


Name

FlashPlayer.GetVariable( ): return a value defined in a Flash movie — Flash 4

Synopsis

String GetVariable(StringvariableName)

Arguments

variableName

The name of the variable defined in the Flash movie.

Returns

The value of the named variable as a string, or null if no such variable exists.


Name

FlashPlayer.GotoFrame( ): skip to the specified frame of a movie — Flash 2

Synopsis

void GotoFrame(integerframeNumber)

Arguments

frameNumber

The frame number to skip to.

Description

This function skips to the specified frame of the movie, or skips to the last available frame, if the specified frame has not been loaded yet. To avoid this indeterminate behavior, use PercentLoaded( ) to determine how much of the movie is available.


Name

FlashPlayer.IsPlaying( ): check whether a movie is playing — Flash 2

Synopsis

boolean IsPlaying( )

Returns

true if the movie is playing; false otherwise.


Name

FlashPlayer.LoadMovie( ): load an auxiliary movie — Flash 3

Synopsis

void LoadMovie(integerlayer,
               String url)

Arguments

layer

The level or layer within the current movie on which the newly loaded movie is to be displayed.

url

The URL of the movie to load.

Description

This method loads an auxiliary movie from the specified url and displays it at the specified layer within the current movie.


Name

FlashPlayer.Pan( ): move the viewport of the movie — Flash 2

Synopsis

void Pan(integerdx, integer dy,
         integer mode)

Arguments

dx, dy

The horizontal and vertical amounts to pan.

mode

This argument specifies how to interpret the dx and dy values. If this argument is 0, the other arguments are taken as pixels. If this argument is 1, the others are percentages.

Description

The Flash player defines a viewport through which Flash movies are visible. Typically, the size of the viewport and the size of the movie are the same, but this may not be not the case when SetZoomRect( ) or Zoom( ) have been called: those methods can alter the viewport so that only a portion of the movie shows through.

When the viewport is showing only a portion of the movie, this Pan( ) method moves (or "pans") the viewport so that a different portion of the movie shows. This method doesn't allow you to pan beyond the edges of a movie, however.

See Also

FlashPlayer.SetZoomRect( ), FlashPlayer.Zoom( )


Name

FlashPlayer.PercentLoaded( ): determine how much of the movie has loaded — Flash 2

Synopsis

integer PercentLoaded( )

Returns

An integer between 0 and 100 representing the approximate percentage of the movie that has been loaded into the player.


Name

FlashPlayer.Play( ): play a movie — Flash 2

Synopsis

void Play( )

Description

Begins playing the movie.


Name

FlashPlayer.Rewind( ): rewind the movie to its first frame — Flash 2

Synopsis

void Rewind( )

Description

This method rewinds the movie to its first frame.


Name

FlashPlayer.SetVariable( ): set a variable defined by a Flash movie — Flash 4

Synopsis

void SetVariable(Stringname, String value)

Arguments

name

The name of the variable to set.

value

The new value for the named variable. This value must be a string.

Description

This method specifies a value for a named variable defined by the Flash movie.


Name

FlashPlayer.SetZoomRect( ): set the viewport of a movie — Flash 2

Synopsis

void SetZoomRect(integerleft, integer top,
                 integer right, integer bottom)

Arguments

left, top

The coordinates, in twips, of the upper-left corner of the viewport.

right, bottom

The coordinates, in twips, of the lower-right corner of the viewport.

Description

This method defines the movie's viewport—that is, it specifies a subrectangle of the movie to appear in the Flash player. Flash movies are measured in a unit known as the twip. There are 20 twips to a point and 1,440 twips to an inch.

See Also

FlashPlayer.Pan( ), FlashPlayer.Zoom( )


Name

FlashPlayer.StopPlay( ): stop the movie — Flash 2

Synopsis

void StopPlay( )

Description

Stop the movie.


Name

FlashPlayer.TotalFrames( ): return the length of the movie, in frames — Flash 2

Synopsis

integer TotalFrames( )

Description

This method returns the length of the movie in frames.


Name

FlashPlayer.Zoom( ): zoom in or out — Flash 2

Synopsis

void Zoom(integerpercentage)

Arguments

percentage

The percentage by which to scale the viewport, or 0 to restore the viewport to its full size.

Description

This method scales the viewport by a specified percentage. Arguments between 1 and 99 reduce the size of the viewport, which makes objects in the movie appear larger. Arguments greater than 100 enlarge the viewport (but never beyond the size of the movie) and make objects in the movie appear smaller. As a special case, the argument 0 restores the viewport to full size, so that the entire movie is visible.


Name

Form: a <form> in an HTML document — DOM Level 2 HTML: Node → Element → HTMLElement → Form

Properties

readonly HTMLCollection elements

An array (HTMLCollection) of all elements in the form. See Form.elements[].

readonly long length

The number of form elements in the form. This is the same value as elements.length.

In addition to these properties, Form also defines the properties in the following table, which correspond directly to HTML attributes:

Property

Attribute

Description

String acceptCharset

acceptcharset

Character sets the server can accept

String action

action

URL of the form handler

String enctype

enctype

Encoding of the form

String method

method

HTTP method used for form submission

String name

name

Name of the form

String target

target

Frame or window name for form submission results

Methods

reset( )

Resets all form elements to their default values.

submit( )

Submits the form to a web server.

Event Handlers

onreset

Invoked just before the elements of the form are reset.

onsubmit

Invoked just before the form is submitted. This event handler allows form entries to be validated before being submitted.

HTML Syntax

A Form object is created with a standard HTML <form> tag. The form contains input elements created with <input>, <select>, <textarea>, and other tags:

<form
    [ name="form_name" ]       // Used to name the form in JavaScript
    [ target="window_name" ]   // The name of the window for responses
    [ action="url" ]           // The URL to which the form is submitted
    [ method=("get"|"post") ]  // The method of form submission
    [ enctype="encoding" ]     // How the form data is encoded
    [ onreset="handler" ]      // A handler invoked when form is reset
    [ onsubmit="handler" ]     // A handler invoked when form is submitted

>
// Form text and input elements go here
</form>

Description

The Form object represents a <form> element in an HTML document. The elements property is an HTMLCollection that provides convenient access to all elements of the form. The submit( ) and reset( ) methods allow a form to be submitted or reset under program control.

Each form in a document is represented as an element of the Document.forms[] array. Named forms are also represented by the form_name property of their document, where form_name is the name specified by the name attribute of the <form> tag.

The elements of a form (buttons, input fields, checkboxes, and so on) are collected in the Form.elements[] array. Named elements, like named forms, can also be referenced directly by name: the element name is used as a property name of the Form object. Thus, to refer to an Input element named phone within a form named questionnaire, you might use the JavaScript expression:

document.questionnaire.phone

See Also

Input, Select, Textarea; Chapter 18, Forms and Form Elements


Name

Form.elements[]: the input elements of a form — DOM Level 2 HTML

Synopsis

readonly HTMLCollection elements

Description

elements[] is an array-like HTMLCollection of the form elements (such as Input, Select, and Textarea objects) that appear in an HTML form. The elements of the array are in the same order they appear in the HTML source code for the form. Each element has a type property whose string value identifies its type.

Usage

If an item in the elements[] array has been given a name with the name=" name " attribute of its HTML <input> tag, that item's name becomes a property of form, and this property refers to the item. Thus, it is possible to refer to input elements by name instead of by number:

form.name

See Also

Input, HTMLCollection, Select, Textarea


Name

Form.onreset: event handler invoked when a form is reset — DOM Level 0

Synopsis

Function onreset

Description

The onreset property of a Form object specifies an event-handler function that is invoked when the user clicks on a Reset button in the form. Note that this handler is not invoked in response to the Form.reset( ) method. If the onreset handler returns false, the elements of the form are not reset. See Element.addEventListener( ) for another way to register event handlers.

See Also

Element.addEventListener( ), Form.onsubmit, Form.reset( ); Chapter 17, Events and Event Handling


Name

Form.onsubmit: event handler invoked when a form is submitted — DOM Level 0

Synopsis

Function onsubmit

Description

The onsubmit property of a Form object specifies an event-handler function that is invoked when the user submits a form by clicking on its Submit button. Note that this event handler is not invoked when the Form.submit( ) method is called.

If the onsubmit handler returns false, the elements of the form are not submitted. If the handler returns any other value or returns nothing, the form is submitted normally. Because the onsubmit handler can cancel form submission, it is ideal for performing form data validation.

See Element.addEventListener( ) for another way to register event handlers.

See Also

Element.addEventListener( ), Form.onreset, Form.submit( ); Chapter 17, Events and Event Handling


Name

Form.reset( ): reset the elements of a form to their default values — DOM Level 2 HTML

Synopsis

void reset( );

Description

This method resets each element of a form to its default value. The results of calling this method are like the results of a user clicking on a Reset button, except that the onreset event handler of the form is not invoked.

See Also

Form.onreset, Form.submit( )


Name

Form.submit( ): submit form data to a web server — DOM Level 2 HTML

Synopsis

void submit( );

Description

This method submits the values of the form elements to the server specified by the form's action property. It submits a form in the same way that a user's clicking on a Submit button does, except that the onsubmit event handler of the form is not triggered.

See Also

Form.onsubmit, Form.reset( )


Name

Frame: a <frame> in an HTML document — DOM Level 2 HTML: Node → Element → HTMLElement → Frame

Properties

As explained in the Description, HTML frames can be accessed as Frame objects or as Window objects. When accessed as Frame objects, they inherit properties from HTMLElement and define these additional properties:

Document contentDocument

The document that holds the content of the frame.

String src

The URL from which the frame's content was loaded. Setting this property causes the frame to load a new document. This property simply mirrors the src attribute of the HTML <frame> tag: it is not a Location object like Window.location.

In addition to these properties, the Frame object also defines the following properties, which correspond directly to HTML attributes:

Property

Attribute

Description

String frameBorder

frameborder

Set to "0" for borderless frames

String longDesc

longdesc

The URL of a frame description

String marginHeight

marginheight

Top and bottom frame margin, in pixels

String marginWidth

marginwidth

Left and right frame margin, in pixels

String name

name

The name of the frame, for DOM Level 0 lookup and form and link targets

boolean noResize

noresize

If true, user cannot resize frame

String scrolling

scrolling

Frame scroll policy: "auto", "yes", or "no"

Description

Frames have a dual nature and may be represented in client-side JavaScript by either Window or Frame objects. In the traditional Level 0 DOM, each <frame> is treated as an independent window and is represented by a Window object, referenced by name, or as an element of the frames[] array of the containing Window:

// Get a frame as a Window object
var win1 = top.frames[0];     // Index frames[] array by number
var win2 = top.frames['f1'];  // Index frames[] array by name
var win3 = top.f1;            // Get frame as a property of its parent

When frames are looked up this way, the returned object is a Window, and the properties listed in the previous section are not available. Instead, use Window properties, such as document to access the frame's document and location to access the URL of that document.

In the Level 2 DOM, <frame> elements can be looked up by ID or tag name, just as any other document element can be:

// Get a frame as a Frame object
var frame1 = top.document.getElementById('f1');               // by id
var frame2 = top.document.getElementsByTagName('frame')[1];   // by tag name

When frames are looked up using DOM methods like these, the result is a Frame object rather than a Window object, and the properties listed previously are available. Use contentDocument to access the frame's document, and use the src property to query the URL of that document or to make the frame load a new document. To obtain the Window object of a Frame object f, use f.contentDocument.defaultView.

<iframe> elements are very similar to <frame> elements. See the IFrame reference page.

Note that the same-origin policy (see the section called “The Same-Origin Policy”) applies to multiframed documents. Browsers do not allow you to access the content of frames loaded from a different origin than that of the content that includes the script. This is true whether the frame is represented by a Window or a Frame object.


Name

Hidden: see Input


Name

History: the URL history of the browser — JavaScript 1.0: Object → History

Synopsis

window.history
history

Properties

length

This numeric property specifies the number of URLs in the browser's history list. Since there is no way to determine the index of the currently displayed document within this list, knowing the size of this list is not particularly helpful.

Methods

back( )

Goes backward to a previously visited URL.

forward( )

Goes forward to a previously visited URL.

go( )

Goes to a previously visited URL.

Description

The History object was originally designed to represent the browsing history of a window. For privacy reasons, however, the History object no longer allows scripted access to the actual URLs that have been visited. The only functionality that remains is in the use of the back( ), forward( ), and go( ) methods.

Example

The following line performs the same action as clicking a browser's Back button:

history.back( );

The following line performs the same action as clicking the Back button twice:

history.go(-2);

See Also

The history property of the Window object, Location


Name

History.back( ): return to the previous URL — JavaScript 1.0

Synopsis

history.back( )

Description

back( ) causes the window or frame to which the History object belongs to revisit the URL (if any) that was visited immediately before the current one. Calling this method has the same effect as clicking on the browser's Back button. It is also equivalent to:

history.go(-1);

Name

History.forward( ): visit the next URL — JavaScript 1.0

Synopsis

history.forward( )

Description

forward( ) causes the window or frame to which the History object belongs to revisit the URL (if any) that was visited immediately after the current one. Calling this method has the same effect as clicking on the browser's Forward button. It is also equivalent to:

history.go(1);

Note that if the user has not used the Back button or the Go menu to move backward through the history, and if JavaScript has not invoked the History.back( ) or History.go( ) methods, the forward( ) method has no effect because the browser is already at the end of its list of URLs, and there is no URL to go forward to.


Name

History.go( ): revisit a URL — JavaScript 1.0

Synopsis

history.go(relative_position)
history.go(target_string)

Arguments

relative_position

The relative position in the history list of the URL to be visited.

target_string

A URL (or URL fragment) to be visited, if a matching URL exists in the history list.

Description

The first form of the History.go( ) method takes an integer argument and causes the browser to visit the URL that is the specified number of positions away in the history list maintained by the History object. Positive arguments move the browser forward through the list, and negative arguments move it backward. Thus, calling history.go(-1) is equivalent to calling history.back( ) and produces the same effect as clicking on the Back button. Similarly, history.go(3) revisits the same URL that would be visited by calling history.forward( ) three times.

The second form of the History.go( ) takes a string argument and causes the browser to revisit the first (i.e., most recently visited) URL that contains the specified string. This form of the method is not well specified and may work differently on different browsers. For example, Microsoft's documentation specifies that the argument must match the URL of a previously specified site exactly, while old Netscape documentation (Netscape created the History object) says that the argument may be a substring of a previously visited URL.


Name

HTMLCollection: array of HTML elements accessible by position or name — DOM Level 2 HTML: Object → HTMLCollection

Properties

readonly unsigned long length

The number of elements in the collection.

Methods

item( )

Returns the element at the specified position in the collection. You can also simply specify the position within array brackets instead of calling this method explicitly.

namedItem( )

Returns the element from the collection that has the specified value for its id or name attribute, or null if there is no such element. You can also place the element name within array brackets instead of calling this method explicitly.

Description

An HTMLCollection is a collection of HTML elements with methods that allow you to retrieve an element by its position in the collection or by its id or name attribute. In JavaScript, HTMLCollection objects behave like read-only arrays, and you can use JavaScript square-bracket notation to index an HTMLCollection by number or by name instead of calling the item( ) and namedItem( ) methods.

A number of the properties of the HTMLDocument object are HTMLCollection objects and provide convenient access to document elements such as forms, images, and links. The Form.elements property and Select.options property are HTMLCollection objects. The HTMLCollection object also provides a convenient way to traverse the rows of a Table and the cells of a TableRow.

HTMLCollection objects are read-only: you cannot assign new elements to them, even when using JavaScript array notation. They are "live," meaning that if the underlying document changes, those changes are immediately visible through all HTMLCollection objects.

HTMLCollection objects are similar to NodeList objects but may be indexed by name as well as by number.

Example

var c = document.forms;       // This is an HTMLCollection of form elements
var firstform = c[0];         // It can be used like a numeric array
var lastform = c[c.length-1]; // The length property gives the number of elements
var address = c["address"];   // It can be used like an associative array
var address = c.address;      // JavaScript allows this notation, too

See Also

HTMLDocument, NodeList


Name

HTMLCollection.item( ): get an element by position — DOM Level 2 HTML

Synopsis

Node item(unsigned longindex);

Arguments

index

The position of the element to be returned. Elements appear in an HTMLCollection in the same order in which they appear in the document source.

Returns

The element at the specified index, or null if index is less than zero or greater than or equal to the length property.

Description

The item( ) method returns a numbered element from an HTMLCollection. In JavaScript, it is easier to treat the HTMLCollection as an array and to index it using array notation.

Example

var c = document.images;  // This is an HTMLCollection
var img0 = c.item(0);     // You can use the item( ) method this way
var img1 = c[1];          // But this notation is easier and more common

See Also

NodeList.item( )


Name

HTMLCollection.namedItem( ): get an element by name — DOM Level 2 HTML

Synopsis

Node namedItem(Stringname);

Arguments

name

The name of the element to be returned.

Returns

The element in the collection that has the specified value for its id or name attribute, or null if no elements in the HTMLCollection have that name.

Description

This method finds and returns an element from the HTMLCollection that has the specified name. If any element has an id attribute whose value is the specified name, that element is returned. If no such element is found, an element whose name attribute has the specified value is returned. If no such element exists, namedItem( ) returns null.

Note that any HTML element may be given an id attribute, but only certain HTML elements—such as forms, form elements, images, and anchors—may have a name attribute.

In JavaScript, it is easier to treat the HTMLCollection as an associative array and to specify name between square brackets using array notation.

Example

var forms = document.forms;                // An HTMLCollection of forms
var address = forms.namedItem("address");  // Finds <form name="address">
var payment = forms["payment"]  // Simpler syntax: finds <form name="payment">
var login = forms.login;        // Also works: finds <form name="login">

Name

HTMLDocument: the root of an HTML document tree — DOM Level 0: Node → Document → HTMLDocument

Properties

Element[] all [IE 4]

This nonstandard property is an array-like object that provides access to all HTMLElements in the document. The all[] array originated in IE4, and although it has been superseded by methods such as Document.getElementById( ) and Document.getElementsByTagName( ), it is still used in deployed code. See HTMLDocument.all[] for further details.

readonly HTMLCollection anchors

An array (HTMLCollection) of all Anchor objects in the document.

readonly HTMLCollection applets

An array (HTMLCollection) of all Applet objects in a document.

HTMLElement body

A convenience property that refers to the HTMLElement that represents the <body> tag of this document. For documents that define framesets, this property refers to the outermost <frameset> tag instead.

String cookie

Allows cookies to be queried and set for this document. See HTMLDocument.cookie for details.

String domain

The domain name of the server from which the document was loaded, or null if there is none. This property can also be used to ease the same-origin security policy in specific circumstances. See HTMLDocument.domain for details.

readonly HTMLCollection forms

An array (HTMLCollection) of all Form objects in the document.

readonly HTMLCollection images

An array (HTMLCollection) of Image objects in the document. Note that for compatibility with the Level 0 DOM, images defined with an <object> tag instead of the <img> tag are not included in this collection.

readonly String lastModified

Specifies the date and time of the most recent modification to the document. This value comes from the Last-Modified HTTP header that is optionally sent by the web server.

readonly HTMLCollection links

An array (HTMLCollection) of all Link objects in the document.

readonly String referrer

The URL of the document that linked to this document, or null if this document was not accessed through a hyperlink. This property allows client-side JavaScript to access the HTTP referer header. Note the spelling difference, however: the HTTP header has three r's, and the JavaScript property has four r's.

String title

The contents of the <title> tag for this document.

readonly String URL

The URL of the document. This value is often the same as the location.href property of the Window that contains the document. When URL redirection occurs, however, this URL property holds the actual URL of the document, and location.href holds the URL that was requested.

Methods

close( )

Closes a document stream opened with the open( ) method, forcing any buffered output to be displayed.

getElementsByName( )

Returns an array of nodes (a NodeList) of all elements in the document that have a specified value for their name attribute.

open( )

Opens a stream to which new document contents may be written. Note that this method erases any current document content.

write( )

Appends a string of HTML text to an open document.

writeln( )

Appends a string of HTML text followed by a newline character to an open document.

Description

This interface extends Document and defines HTML-specific properties and methods. A number of the properties are HTMLCollection objects (essentially read-only arrays that can be indexed by number or name) that hold references to anchors, forms, links, and other important scriptable elements of the document. These collection properties originated with the Level 0 DOM. They have been superseded by Document.getElementsByTagName( ) but remain in common use because they are so convenient.

The write( ) method is notable: it allows a script to insert dynamically generated content into a document while the document is being loaded and parsed.

Note that in the Level 1 DOM, HTMLDocument defined a very useful method named getElementById( ). In the Level 2 DOM, this method has been moved to the Document interface, and it is now inherited by HTMLDocument rather than defined by it. See Document.getElementById( ) for details.

See Also

Document, Document.getElementById( ), Document.getElementsByTagName( )


Name

HTMLDocument.all[]: all HTML elements in a document — IE 4

Synopsis

document.all[i]

document.all[name]
document.all.tags(tagname)

Description

all[] is a versatile array-like object that provides access to all the HTML elements in a document. The all[] array originated in IE 4 and has been adopted by a number of other browsers. It has been superseded by the standard getElementById( ) and getElementsByTagName( ) methods of the Document interface, and the standard getElementsByName( ) method of the HTMLDocument interface. Despite this, the all[] array is still used in existing code.

all[] contains the elements in source order, and you can extract them directly from the array if you know their exact numeric position within the array. It is more common, however, to use the all[] array to retrieve elements by the value of their name or id HTML attributes. If more than one element has the specified name, using that name as an index into all[] returns an array of elements that share the name.

all.tags( ) is passed a tag name and returns an array of HTML elements of the specified type.

See Also

Document.getElementById( ), Document.getElementsByTagName( ), HTMLElement


Name

HTMLDocument.close( ): close an open document and display it — DOM Level 0

Synopsis

void close( );

Description

This method closes a document stream that was opened with the open( ) method and forces any buffered output to be displayed. If you use the write( ) method to dynamically output a document, you must remember to call this method when you are done to ensure that all your document content is displayed. Once you have called close( ), you should not call write( ) again, as this implicitly calls open( ) to erase the current document and begin a new one.

See Also

HTMLDocument.open( ), HTMLDocument.write( )


Name

HTMLDocument.cookie: the cookie(s) of the document — DOM Level 0

Synopsis

String cookie

Description

cookie is a string property that allows you to read, create, modify, and delete the cookie or cookies that apply to the current document. A cookie is a small amount of named data stored by the web browser. It gives web browsers a "memory" so they can use data input on one page in another page or recall user preferences across web browsing sessions. Cookie data is automatically transmitted between web browser and web server when appropriate so server-side scripts can read and write cookie values. Client-side JavaScript code can also read and write cookies with this property.

The HTMLDocument.cookie property does not behave like a normal read/write property. You may both read and write the value of HTMLDocument.cookie, but the value you read from this property is, in general, not the same as the value you write. For details on the use of this particularly complex property, see Chapter 19, Cookies and Client-Side Persistence.

Usage

Cookies are intended for infrequent storage of small amounts of data. They are not intended as a general-purpose communication or programming mechanism, so use them in moderation. Note that web browsers are not required to retain the value of more than 20 cookies per web server, nor to retain a cookie name/value pair of more than 4 KB in length.


Name

HTMLDocument.domain: the security domain of a document — DOM Level 0

Synopsis

String domain

Description

According to the DOM Level 2 HTML standard, the domain property is simply a read-only string that contains the hostname of the web server from which the document was loaded.

This property has another important use (although this use has not been standardized). The same-origin security policy (described in the section called “The Same-Origin Policy”) prevents a script in one document from reading the content of another document (such as a document displayed in an <iframe>) unless the two documents have the same origin (i.e., were retrieved from the same web server). This can cause problems for large web sites that use multiple servers. For example, a script on the host http://www.oreilly.com might want to read the content of documents from the host search.oreilly.com.

The domain property helps to address this problem. You can set this property but only in a very restricted way: it can be set only to a domain suffix of itself. For example, a script loaded from search.oreilly.com could set its own domain property to "http://oreilly.com". If a script from http://www.oreilly.com is running in another window, and it also sets its domain property to "http://oreilly.com", then each script can read content from the other script's document, even though they did not originate on the same server. Note, that a script from search.oreilly.com cannot set its domain property to "search.oreilly" or to ".com".


Name

HTMLDocument.getElementsByName( ): find elements with the specified name attribute — DOM Level 2 HTML

Synopsis

Element[] getElementsByName(StringelementName);

Arguments

elementName

The desired value for the name attribute.

Returns

A read-only array (technically a NodeList) of Element objects that have a name attribute with the specified value. If no such elements are found, the returned array is empty and has a length of 0.

Description

This method searches an HTML document tree for Element nodes that have a name attribute of the specified value and returns a NodeList (which you can treat as a read-only array) containing all matching elements. If there are no matching elements, a NodeList with length 0 is returned.

Do not confuse this method with the Document.getElementById( ) method, which finds a single Element based on the unique value of an id attribute, or with the Document.getElementsByTagName( ) method, which returns a NodeList of elements with the specified tag name.

See Also

Document.getElementById( ), Document.getElementsByTagName( )


Name

HTMLDocument.open( ): begin a new document, erasing the current one — DOM Level 0

Synopsis

void open( );

Description

This method erases the current HTML document and begins a new one, which may be written to with the write( ) and writeln( ) methods. After calling open( ) to begin a new document and write( ) to specify document content, you must always remember to call close( ) to end the document and force its content to be displayed.

This method should not be called by a script or event handler that is part of the document being overwritten, because the script or handler will itself be overwritten.

Example

var w = window.open("");          // Open a new window
var d = w.document;               // Get its HTMLDocument object
d.open( );                            // Open the document for writing
d.write("<h1>Hello world</h1>");  // Output some HTML to the document
d.close( );                           // End the document and display it

See Also

HTMLDocument.close( ), HTMLDocument.write( )


Name

HTMLDocument.write( ): append HTML text to an open document — DOM Level 0

Synopsis

void write(Stringtext);

Arguments

text

The HTML text to be appended to the document.

Description

This method appends the specified HTML text to the document. According to the DOM standard, this method takes a single string argument. According to common practice, however, the write( ) method may be passed any number of arguments. These arguments are converted to strings and appended, in order, to the document.

Document.write( ) is normally used in one of two ways. First, it can be invoked on the current document within a <script> tag or within a function that is executed while the document is being parsed. In this case, the write( ) method writes its HTML output as if that output appeared literally in the file at the location of the code that invoked the method.

Second, you can use Document.write( ) to dynamically generate new documents in a window, frame, or iframe other than the one in which the calling script is running. If the target document is open, write( ) appends to that document. If the document is not open, write( ) discards the existing document and opens a new (empty) one to which it appends its arguments.

Once a document is open, Document.write( ) can append any amount of output to the end of the document. When a new document has been completely generated by this technique, the document must be closed by calling Document.close( ). Note that although the call to open( ) is optional, the call to close( ) is never optional.

The results of calling Document.write( ) may not be immediately visible in the target document. This is because a web browser may buffer up text to parse and display in larger chunks. Calling Document.close( ) is the only way to explicitly force all buffered output to be "flushed" and displayed.

See Also

HTMLDocument.close( ), HTMLDocument.open( )


Name

HTMLDocument.writeln( ): append HTML text and a newline to an open document — DOM Level 0

Synopsis

void writeln(Stringtext);

Arguments

text

The HTML text to be appended to the document.

Description

This method is like HTMLDocument.write( ), except that it follows the appended text with a newline character, which may be useful when writing the content of a <pre> tag, for example.

See Also

HTMLDocument.write( )


Name

HTMLElement: an element in an HTML document — DOM Level 2 HTML: Node → Element → HTMLElement

Properties

Each element of an HTML document has properties that correspond to the HTML attributes of the element. The properties supported by all HTML tags are listed here. Other properties, specific to certain kinds of HTML tags, are listed in the long table in the following Description section. HTMLElement objects inherit a number of useful standard properties from Node and Element, and also implement several nonstandard properties described here:

String className

The value of the class attribute of the element, which specifies zero or more space-separated CSS class names. Note that this property is not named "class" because that name is a reserved word in JavaScript.

CSS2Properties currentStyle

This IE-specific property represents the cascaded set of all CSS properties that apply to the element. It is an IE-only alternative to Window.getComputedStyle( ).

String dir

The value of the dir attribute of the element, which specifies the text direction for the document.

String id

The value of the id attribute. No two elements within the same document should have the same value for id.

String innerHTML

A read/write string that specifies the HTML text that is contained within the element, not including the opening and closing tags of the element itself. Querying this property returns the content of the element as a string of HTML text. Setting this property to a string of HTML text replaces the content of the element with the parsed representation of the HTML. You cannot set this property while the document is loading (for this ability, see HTMLDocument.write( )). This is a nonstandard property that originated in IE 4. It has been implemented by all modern browsers.

String lang

The value of the lang attribute, which specifies the language code for the element's content.

int offsetHeight, offsetWidth

The height and width, in pixels, of the element and all its content, including the element's CSS padding and border, but not its margin. These are nonstandard but well-supported properties.

int offsetLeft, offsetTop

The X and Y coordinates of the upper-left corner of the CSS border of the element relative to the offsetParent container element. These are nonstandard but well-supported properties.

Element offsetParent

Specifies the container element that defines the coordinate system in which offsetLeft and offsetTop are measured. For most elements, offsetParent is the Document object that contains them. However, if an element has a dynamically positioned container, the dynamically positioned element is the offsetParent. In some browsers, table cells are positioned relative to the row in which they are contained, rather than relative to the containing document. See Chapter 16, Cascading Style Sheets and Dynamic HTML for an example that uses this property portably. This is a nonstandard but well-supported property.

int scrollHeight, scrollWidth

The overall height and width, in pixels, of an element. When an element has scrollbars (because of the CSS overflow attribute, for example) these properties differ from offsetHeight and offsetWidth, which simply report the size of the visible portion of the element. These are non-standard but well-supported properties.

int scrollLeft, scrollTop

The number of pixels that have scrolled off the left edge of the element or off the top edge of the element. These properties are useful only for elements with scrollbars, such as elements with the CSS overflow attribute set to auto. These properties are also defined on the <body> or <html> tag of the document (this is browser-dependent) and specify the amount of scrolling for the document as a whole. Note that these properties do not specify the amount of scrolling in an <iframe> tag. These are non-standard but well-supported properties.

CSS2Properties style

The value of the style attribute that specifies inline CSS styles for this element. Note that the value of this property is not a string. See CSS2Properties for details.

String title

The value of the title attribute of the element. Many browsers display the value of this attribute in a tool tip when the mouse hovers over the element.

Methods

HTMLElement objects inherit the standard methods of Node and Element. Certain types of elements implement tag-specific methods, which are listed in the long table in the Description section and documented in other reference pages such as Form, Input, and Table. Most modern browsers also implement the following nonstandard method as well:

scrollIntoView( )

Scrolls the document so the element is visible at the top or bottom of the window.

Event Handlers

All HTML elements respond to raw mouse and key events and can trigger the event handlers listed here. Some elements, such as links and buttons, perform default actions when these events occur. For elements like these, further details are available on the element-specific reference page; see Input and Link, for example:

onclick

Invoked when the user clicks on the element.

ondblclick

Invoked when the user double-clicks on the element.

onkeydown

Invoked when the user presses a key.

onkeypress

Invoked when the user presses and releases a key.

onkeyup

Invoked when the user releases a key.

onmousedown

Invoked when the user presses a mouse button.

onmousemove

Invoked when the user moves the mouse.

onmouseout

Invoked when the user moves the mouse off the element.

onmouseover

Invoked when the user moves the mouse over an element.

onmouseup

Invoked when the user releases a mouse button.

Description

Each tag in an HTML document is represented by an HTMLElement object. HTMLElement defines properties that represent the attributes shared by all HTML elements. The following HTML tags do not have any properties other than those listed previously and are fully described by the HTMLElement interface:

<abbr>

<acronym>

<address>

<b>

<bdo>

<big>

<center>

<cite>

<code>

<dd>

<dfn>

<dt>

<em>

<i>

<kbd>

<noframes>

<noscript>

<s>

<samp>

<small>

<span>

<strike>

<strong>

<sub>

<sup>

<tt>

<u>

<var>

Most HTML tags define properties other than those explicitly listed previously. The DOM Level 2 HTML specification defines tag-specific interfaces for these tags, so that all standard HTML attributes have a corresponding standard JavaScript property. Typically, a tag named T has a tag-specific interface named HTMLTElement. For example, the <head> tag is represented by the HTMLHeadElement interface. In a few cases, two or more related tags share a single interface, as in the case of the <h1> through <h6> tags, which are all represented by the HTMLHeadingElement interface.

Most of these tag-specific interfaces do nothing more than define a JavaScript property for each attribute of the HTML tag. The JavaScript properties have the same names as the attributes and use lowercase (e.g., id) or, when the attribute name consists of multiple words, mixed case (e.g., longDesc). When an HTML attribute name is a reserved word in Java or JavaScript, the property name is changed slightly. For example, the for attribute of <label> and <script> tags becomes the htmlFor property of the HTMLLabelElement and HTMLScriptElement interfaces because for is a reserved word. The meanings of those properties that correspond directly to HTML attributes are defined by the HTML specification, and documenting each one is beyond the scope of this book.

The following table lists all the HTML tags that have a corresponding subinterface of HTMLElement. For each tag, the table lists the DOM interface name and the names of the properties and methods it defines. All properties are read/write strings unless otherwise specified. For properties that are not read/write strings, the property type is specified in square brackets before the property name. Quite a few tags and attributes are deprecated in HTML 4 and are marked with an * in this table.

Because these interfaces and their properties map so directly to HTML elements and attributes, most interfaces do not have reference pages of their own in this book, and you should consult an HTML reference for details. The exceptions are interfaces that represent tags that are particularly important to client-side JavaScript programmers, such as the <form> and <input> tags. Those tags are documented in this book, under names that do not include the "HTML" prefix or the "Element" suffix. See, for example, the entries for Anchor, Applet, Canvas, Form, Image, Input, Link, Option, Select, Table, and Textarea:

HTML tag

DOM interface, properties, and methods

[*]

all tags

HTMLElement: id, title, lang, dir, className

<a>

HTMLAnchorElement: accessKey, charset, coords, href, hreflang, name, rel, rev, shape, [long] tabIndex, target, type, blur( ), focus( )

<applet>

HTMLAppletElement[*]: align [*], alt [*], archive [*], code [*], codeBase [*], height [*], hspace [*], name [*], object [*], vspace [*], width [*]

<area>

HTMLAreaElement: accessKey, alt, coords, href, [boolean] noHref, shape, [long] tabIndex, target

<base>

HTMLBaseElement: href, target

<basefont>

HTMLBaseFontElement[*]: color [*], face [*], size [*]

<blockquote>, <q>

HTMLQuoteElement: cite

<body>

HTMLBodyElement: aLink [*], background [*], bgColor [*], link [*], text [*], vLink [*]

HTMLBRElement: clear [*]

<button>

HTMLButtonElement: [readonly HTMLFormElement] form, accessKey, [boolean] disabled, name, [long] tabIndex, [readonly] type, value

<caption>

HTMLTableCaptionElement: align [*]

<col>, <colgroup>

HTMLTableColElement: align, ch, chOff, [long] span, vAlign, width

<del>, <ins>

HTMLModElement: cite, dateTime

<dir>

HTMLDirectoryElement[*]: [boolean] compact [*]

<div>

HTMLDivElement: align [*]

<dl>

HTMLDListElement: [boolean] compact [*]

<fieldset>

HTMLFieldSetElement: [readonly HTMLFormElement] form

<font>

HTMLFontElement[*]: color [*], face [*], size [*]

<form>

HTMLFormElement: [readonly HTMLCollection] elements, [readonly long] length, name, acceptCharset, action, enctype, method, target, submit( ), reset( )

<frame>

HTMLFrameElement: frameBorder, longDesc, marginHeight, marginWidth, name, [boolean] noResize, scrolling, src, [readonly Document] contentDocument

<frameset>

HTMLFrameSetElement: cols, rows

<h1>, <h2>, <h3>, <h4>, <h5>, <h6>

HTMLHeadingElement: align [*]

<head>

HTMLHeadElement: profile

<hr>

HTMLHRElement: align [*], [boolean] noShade [*], size [*], width [*]

<html>

HTMLHtmlElement: version [*]

<iframe>

HTMLIFrameElement: align [*], frameBorder, height, longDesc, marginHeight, marginWidth, name, scrolling, src, width, [readonly Document] contentDocument

<img>

HTMLImageElement: align [*], alt, [long] border [*], [long] height, [long] hspace [*], [boolean] isMap, longDesc, name, src, useMap, [long] vspace [*], [long] width

<input>

HTMLInputElement: defaultValue, [boolean] defaultChecked, [readonly HTMLFormElement] form, accept, accessKey, align [*], alt, [boolean] checked, [boolean] disabled, [long] maxLength, name, [boolean] readOnly, size, src, [long] tabIndex, type, useMap, value, blur( ), focus( ), select( ), click( )

<ins>

See <del>

<isindex>

HTMLIsIndexElement[*]: [readonly HTMLFormElement] form, prompt [*]

<label>

HTMLLabelElement: [readonly HTMLFormElement] form, accessKey, htmlFor

<legend>

HTMLLegendElement: [readonly HTMLFormElement] form, accessKey, align [*]

<li>

HTMLLIElement: type [*], [long] value [*]

<link>

HTMLLinkElement: [boolean] disabled, charset, href, hreflang, media, rel, rev, target, type

<map>

HTMLMapElement: [readonly HTMLCollection of HTMLAreaElement] areas, name

<menu>

HTMLMenuElement[*]: [boolean] compact [*]

<meta>

HTMLMetaElement: content, httpEquiv, name, scheme

<object>

HTMLObjectElement: code, align [*], archive, border [*], codeBase, codeType, data, [boolean] declare, height, hspace [*], name, standby, [long] tabIndex, type, useMap, vspace [*], width, [readonly Document] contentDocument

<ol>

HTMLOListElement: [boolean] compact [*], [long] start [*], type [*]

<optgroup>

HTMLOptGroupElement: [boolean] disabled, label

<option>

HTMLOptionElement: [readonly HTMLFormElement] form, [boolean] defaultSelected, [readonly] text, [readonly long] index, [boolean] disabled, label, [boolean] selected, value

<p>

HTMLParagraphElement: align [*]

<param>

HTMLParamElement: name, type, value, valueType

<pre>

HTMLPreElement: [long] width [*]

<q>

See <blockquote>

<script>

HTMLScriptElement: text, html For, event, charset, [boolean] defer, src, type

<select>

HTMLSelectElement: [readonly] type, [long] selectedIndex, value, [readonlylong] length, [readonly HTMLFormElement] form, [readonly HTMLCollection of HTMLOptionElement] options, [boolean] disabled, [boolean] multiple, name, [long] size, [long] tabIndex, add( ), remove( ), blur( ), focus( )

<style>

HTMLStyleElement: [boolean] disabled, media, type

<table>

HTMLTableElement: [HTMLTableCaptionElement] caption, [HTMLTableSectionElement] tHead, [HTMLTableSectionElement] tFoot, [readonly HTMLCollection of HTMLTableRowElement] rows, [readonly HTMLCollection of HTMLTableSectionElement] tBodies, align [*], bgColor [*], border, cellPadding, cellSpacing, frame, rules, summary, width, createTHead( ), deleteTHead( ), createTFoot( ), deleteTFoot( ), createCaption( ), deleteCaption( ), insertRow( ), deleteRow( )

<tbody>, <tfoot>, <thead>

HTMLTableSectionElement: align, ch, chOff, vAlign, [readonly HTMLCollection of HTMLTableRowElement] rows, insertRow( ), deleteRow( )

<td>, <th>

HTMLTableCellElement: [readonly long] cellIndex, abbr, align, axis, bgColor [*], ch, chOff, [long] colSpan, headers, height [*], [boolean] noWrap [*], [long] rowSpan, scope, vAlign, width [*]

<textarea>

HTMLTextAreaElement: defaultValue, [readonly HTMLFormElement] form, accessKey, [long] cols, [boolean] disabled, name, [boolean] readOnly, [long] rows, [long] tabIndex, [readonly] type, value, blur( ), focus( ), select( )

<tfoot>

See <tbody>

<th>

See <td>

<thead>

See <tbody>

<title>

HTMLTitleElement: text

<tr>

HTMLTableRowElement: [readonly long] rowIndex, [readonly long] sectionRowIndex, [readonly HTMLCollection of HTMLTableCellElement] cells, align, bgColor [*], ch, chOff, vAlign, insertCell( ), deleteCell( )

<ul>

HTMLUListElement: [boolean] compact [*], type [*]

[*] Indicates deprecated elements and attributes.

See Also

Anchor, Element, Form, HTMLDocument, Image, Input, Link, Node, Option, Select, Table, TableCell, TableRow, TableSection, Textarea; Chapter 15, Scripting Documents


Name

HTMLElement.onclick: event handler invoked when the user clicks on an element — DOM Level 0

Synopsis

Function onclick

Description

The onclick property of an HTMLElement object specifies an event-handler function that is invoked when the user clicks on the element. Note that onclick is different from onmousedown. A click event does not occur unless a mousedown event and the subsequent mouseup event both occur over the same element.

See Also

Element.addEventListener( ), Event, MouseEvent; Chapter 17, Events and Event Handling


Name

HTMLElement.ondblclick: event handler invoked when the user double-clicks on an element — DOM Level 0

Synopsis

Function ondblclick

Description

The ondblclick property of an HTMLElement object specifies an event-handler function that is invoked when the user double-clicks on the element.

See Also

Element.addEventListener( ), Event, MouseEvent; Chapter 17, Events and Event Handling


Name

HTMLElement.onkeydown: event handler invoked when the user presses a key — DOM Level 0

Synopsis

Function onkeydown

Description

The onkeydown property of an HTMLElement object specifies an event-handler function that is invoked when the user presses a key while the element has keyboard focus. Determing which key or keys were pressed is somewhat browser-dependent. See Chapter 17, Events and Event Handling for details.

The onkeydown handler is usually the prefered handler for function keys, but use onkeypress to respond to regular alphanumeric key presses.

See Also

HTMLElement.onkeypress; Chapter 17, Events and Event Handling


Name

HTMLElement.onkeypress: event handler invoked when the user presses a key — DOM Level 0

Synopsis

Function onkeypress

Description

The onkeypress property of an HTMLElement object specifies an event-handler function that is invoked when the user presses and releases a key while the element has the keyboard focus. A keypress event is generated after a keydown event and before the corresponding keyup event. The keypress and keydown events are similar, although a keypress event is often more useful for alphanumeric keys, and a keydown handler can be more useful for function keys.

Determining which key was pressed and what modifier keys were in effect at the time is somewhat complex and browser-dependent. See Chapter 17, Events and Event Handling for details.

See Also

HTMLElement.onkeydown; Chapter 17, Events and Event Handling


Name

HTMLElement.onkeyup: event handler invoked when the user releases a key — DOM Level 0

Synopsis

Function onkeyup

Description

The onkeyup property of an HTMLElement object specifies an event-handler function that is invoked when the user releases a key while the element has the keyboard focus.

See Also

HTMLElement.onkeydown; Chapter 17, Events and Event Handling


Name

HTMLElement.onmousedown: event handler invoked when the user presses a mouse button — DOM Level 0

Synopsis

Function onmousedown

Description

The onmousedown property of an HTMLElement object specifies an event-handler function that is invoked when the user presses a mouse button over the element.

See Also

Element.addEventListener( ), Event, MouseEvent; Chapter 17, Events and Event Handling


Name

HTMLElement.onmousemove: event handler invoked when the mouse moves within an element — DOM Level 0

Synopsis

Function onmousemove

Description

The onmousemove property of an HTMLElement object specifies an event-handler function that is invoked when the user moves the mouse pointer within the element.

If you define an onmousemove event handler, mouse motion events are generated and reported in huge quantities when the mouse is moved within element. Keep this in mind when writing the function to be invoked by the event handler. If you are interested in tracking mouse drags, register a handler of this type in response to a mousedown event and then deregister it when the mouseup event arrives.

See Also

Element.addEventListener( ), Event, MouseEvent; Chapter 17, Events and Event Handling


Name

HTMLElement.onmouseout: event handler invoked when mouse moves out of an element — DOM Level 0

Synopsis

Function onmouseout

Description

The onmouseout property of an HTMLElement object specifies an event-handler function that is invoked when the user moves the mouse pointer out of the element.

See Also

Element.addEventListener( ), Event, MouseEvent; Chapter 17, Events and Event Handling


Name

HTMLElement.onmouseover: event handler invoked when the mouse moves over an element — DOM Level 0

Synopsis

Function onmouseover

Description

The onmouseover property of an HTMLElement object specifies an event-handler function that is invoked when the user moves the mouse pointer over the element.

See Also

Element.addEventListener( ), Event, MouseEvent; Chapter 17, Events and Event Handling


Name

HTMLElement.onmouseup: event handler invoked when the user releases a mouse button — DOM Level 0

Synopsis

Function onmouseup

Description

The onmouseup property of an HTMLElement object specifies an event-handler function that is invoked when the user releases a mouse button over the element.

See Also

Element.addEventListener( ), Event, MouseEvent; Chapter 17, Events and Event Handling


Name

HTMLElement.scrollIntoView( ): make an element visible — Firefox 1.0, IE 4, Safari 2.02, Opera 8.5

Synopsis

element.scrollIntoView(top)

Arguments

top

An optional boolean argument that specifies whether the element should be scrolled to the top (true) or bottom (false) of the screen. This argument is not supported by all browsers, and elements near the top or bottom of a document cannot usually be scrolled to the opposite edge of the window, so this argument should be considered only a hint.

Description

If an HTML element is not currently visible in the window, this method scrolls the document so that it becomes visible. The top argument is an optional hint about whether the element should be scrolled to the top or bottom of the window. For elements that accept the keyboard focus, such as the Link and Input elements, the focus( ) method implicitly performs this same scroll-into-view operation.

See Also

Anchor.focus( ), Input.focus( ), Link.focus( ), Window.scrollTo( )


Name

IFrame: an <iframe> in an HTML document — DOM Level 2 HTML: Node → Element → HTMLElement → IFrame

Properties

As explained in the following Description, iframe elements can be accessed as IFrame objects or as Window objects. When accessed as IFrame objects, they inherit properties from HTMLElement and define the additional properties below:

Document contentDocument

The document that holds the content of the <iframe>.

String src

The URL from which the iframe's content was loaded. Setting this property causes the iframe to load a new document. This property simply mirrors the src attribute of the HTML <iframe> tag.

In addition to these properties, the IFrame object also defines the following properties, which correspond directly to HTML attributes of the <iframe> tag:

Property

Attribute

Description

deprecated String align

align

Alignment with respect to inline content

String frameBorder

frameborder

Set to "0" for borderless frames

String height

height

Height of the viewport in pixels or percent

String longDesc

longdesc

The URL of a frame description

String marginHeight

marginheight

Top and bottom frame margin, in pixels

String marginWidth

marginwidth

Left and right frame margin, in pixels

String name

name

The name of the frame, for DOM Level 0 lookup and form and link targets

String scrolling

scrolling

Frame scroll policy: "auto", "yes", or "no"

String width

width

Width of the viewport in pixels or percent

Description

Except for small differences in their HTML attributes, <iframe> elements behave very much like <frame> elements in client-side JavaScript. <iframe> elements become part of the frames[] array of the containing window. When accessed through that array, they are represented by Window objects, and the properties listed earlier do not apply.

When an <iframe> element is accessed as a document element by ID or tag name, it is represented by an IFrame object, with the properties shown previously. Use src to query or set the URL of the <iframe>, and use contentDocument to access the contents of the iframe. Be aware, however, that the same-origin policy (see the section called “The Same-Origin Policy”) may prevent access to the contentDocument.


Name

Image: an image in an HTML document — DOM Level 2 HTML: Node → Element → HTMLElement → Image

Constructor

new Image(integerwidth, integer height)

Arguments

width, height

An optionally specified width and height for the image.

Properties

String name

This property specifies the name for the image object. If an <img> tag has a name attribute, you can access the corresponding Image object as a named property of the Document object.

String src

A read/write string that specifies the URL of the image to be displayed by the browser. The initial value of this property is specified by the src attribute of the <img> tag. When you set this property to the URL of a new image, the browser loads and displays that new image. This is useful for updating the graphical appearance of your web pages in response to user actions and can also be used to perform simple animation.

In addition to these properties, Image objects also support the following properties, which simply mirror HTML attributes:

Property

Attribute

Description

deprecated String align

align

Alignment with respect to inline content

String alt

alt

Alternate text when image can't be displayed

deprecated String border

border

Size of image border

long height

height

Image height, in pixels

deprecated long hspace

hspace

Left and right margins, in pixels

boolean isMap

ismap

Whether to use a server-side image map

String longDesc

longdesc

The URI of a long image description

String useMap

usemap

Specifies a client-side image map for the image

deprecated long vspace

vspace

Top and bottom margin, in pixels

long width

width

Image width, in pixels.

Event Handlers

Image inherits event handlers from HTMLElement and defines the following:

onabort

Invoked if page loading is stopped before the image is fully downloaded.

onerror

Invoked if an error occurs while downloading the image.

onload

Invoked when the image successfully finishes loading.

HTML Syntax

The Image object is created with a standard HTML <img> tag. Some <img> attributes have been omitted from the following syntax because they are not commonly used in JavaScript:

<img src="url"              // The image to display
     width="pixels"         // The width of the image
     height="pixels"        // The height of the image
     alt="description"      // Short description of image
     [ onload="handler" ]   // Invoked when image is fully loaded
     [ onerror="handler" ]  // Invoked if error in loading
     [ onabort="handler" ]  // Invoked if user aborts load

>

Description

An Image object represents an image embedded in an HTML document with an <img> tag. The images that appear in a document are collected in the document.images[] array. Images that have name attributes can also be accessed through named properties of the Document object. For example:

document.images[0]     // The first image in the document
document.banner        // An image with name="banner"

The src property of the Image object is the most interesting one. When you set this property, the browser loads and displays the image specified by the new value. This allows visual effects such as image rollovers and animations. See Chapter 22, Scripted Client-Side Graphics for examples.

You can create offscreen Image objects dynamically in your JavaScript code using the Image( ) constructor function. Note that this constructor method does not have an argument to specify the image to be loaded. As with images created from HTML, you tell the browser to load an image by setting the src property of any images you create explicitly. There is no way to display an Image object created in this way; all you can do is force the Image object to download an image by setting the src property. This is useful, however, because it loads an image into the browser's cache; if that same image URL is used later with an actual <img> tag, it will display quickly since it has already been loaded.


Name

Image.onabort: event handler invoked when the user aborts image loading — DOM Level 2 Events

Synopsis

Function onabort

Description

The onabort property of an Image object specifies an event-handler function that is invoked when the user aborts the loading of a page (for example, by clicking the Stop button) before the image has finished loading.


Name

Image.onerror: event handler invoked when an error occurs during image loading — DOM Level 2 Events

Synopsis

Function onerror

Description

The onerror property of an Image object specifies an event-handler function that is invoked when an error occurs during the loading of an image. See also Window.onerror.


Name

Image.onload: event handler invoked when an image finishes loading — DOM Level 2 Events

Synopsis

Function onload

Description

The onload property of an Image object specifies an event-handler function that is invoked when an image loads successfully. See also Window.onload.


Name

Input: an input element in an HTML form — DOM Level 2 HTML: Node → Element → HTMLElement → Input

Properties

String accept

When type is "file", this property is a comma-separated list of MIME types that specify the types of files that may be uploaded. Mirrors the accept attribute.

String accessKey

The keyboard shortcut (which must be a single character) a browser can use to transfer keyboard focus to this input element. Mirrors the accesskey attribute.

deprecated String align

The vertical alignment of this element with respect to the surrounding text, or the left or right float for the element. Mirrors the align attribute.

String alt

Alternate text to be displayed by browsers that cannot render this input element. Particularly useful when type is "image". Mirrors the alt attribute.

boolean checked

When type is "radio" or "checkbox", this property specifies whether the element is "checked" or not. Setting this property changes the visual appearance of the input element. Mirrors the checked attribute.

boolean defaultChecked

When type is "radio" or "checkbox", this property holds the initial value of the checked attribute as it appears in the document source. When the form is reset, the checked property is restored to the value of this property. Changing the value of this property changes the value of the checked property and the current checked state of the element.

String defaultValue

When type is "text", "password", or "file", this property holds the initial value displayed by the element. When the form is reset, the element is restored to this value. Changing the value of this property also changes the value property and the currently displayed value.

boolean disabled

If true, the input element is disabled and is unavailable for user input. Mirrors the disabled attribute.

readonly HTMLFormElement form

The Form object representing the <form> element that contains this input element, or null if the input element is not within a form.

long maxLength

If type is "text" or "password", this property specifies the maximum number of characters that the user is allowed to enter. Note that this is not the same as the size property. Mirrors the maxlength attribute.

String name

The name of the input element, as specified by the name attribute. See the following Description section for further details on form element names.

boolean readOnly

If true and type is "text" or "password", the user is not allowed to enter text into the element. Mirrors the readonly attribute.

unsigned long size

If type is "text" or "password", this property specifies the width of the element in characters. Mirrors the size attribute. See also maxLength.

String src

For input elements with a type of "image", specifies the URL of the image to be displayed. Mirrors the src attribute.

long tabIndex

The position of this input element in the tabbing order. Mirrors the tabindex attribute.

String type

The type of the input element. Mirrors the type attribute. See the Description section for further details on form element types.

String useMap

For elements with a type of "image", this property specifies the name of a <map>element that provides a client-side image map for the element.

String value

The value that is passed to the web server when the form is submitted. For elements with a type of "text", "password", or "file", this property is the editable text contained by the input element. For elements with a type of "button", "submit", or "reset", this is the (noneditable) label that appears in the button. For security reasons, the value property of FileUpload elements may be read-only. Similarly, the value returned by this property for Password elements may not contain the user's actual input.

Methods

blur( )

Takes keyboard focus away from the element.

click( )

If type is "button", "checkbox", "radio", "reset", or "submit", this method simulates a mouse-click on the element.

focus( )

Transfers keyboard focus to this input element.

select( )

If type is "file", "password", or "text", this method selects the text displayed by the element. In many browsers, this means that when the user next enters a character, the selected text is deleted and replaced with the newly typed character.

Event Handlers

onblur

Invoked when the user takes keyboard focus away from the element.

onchange

For text-entry elements, this event handler is invoked when the user changes the displayed text and then "commits" those changes by tabbing or clicking to transfer keyboard focus to another element. This handler does not report keystroke-by-keystroke edits. Toggle button elements of type "checkbox" and "radio" may also fire this event (in addition to the onclick event) when the user toggles them.

onclick

For push button and toggle button elements, this event handler is invoked when the user activates the button with a mouse click or by keyboard traversal.

onfocus

Invoked when the user gives keyboard focus to the element.

Description

An Input object represents an HTML <input> tag that defines a scriptable form input element. The three most important properties of an Input object are type, value, and name. These properties are described in the subsections that follow. See Chapter 18, Forms and Form Elements for more information about HTML forms and form elements.

Input element types

The type attribute of the HTML <input> tag specifies the kind of input element that is to be created. This attribute is available to client-side JavaScript as the type property of the Input object and is useful to determine the type of an unknown form element, for example, when iterating through the elements[] array of a Form object.

The legal values of type are the following:

"button"

The input element is a graphical push button that displays the plain text specified by the value property. The button has no default behavior and must be given an onclick event handler in order to be useful. For buttons that submit or reset a form, use a type of "submit" or "reset". Note that the HTML <button> tag can create buttons that display arbitrary HTML instead of plain text.

"checkbox"

An input element of this type displays a toggle button that the user can check and uncheck. The checked property holds the current state of the button, and the onclick event handler is triggered whenever this value changes (browsers may also trigger the onchange handler). The value property is an internal value for submission to a web server and is not displayed to the user. To associate a label with a checkbox, simply place the label text near the <input> tag, optionally using a <label> tag. Checkbox elements often appear in groups, and the members of a group are sometimes given the same name property and different value properties, for the convenience of the web server to which the form is submitted.

"file"

This type creates a "file upload" element. This element consists of a text input field for entering the name of a file, along with a button that opens a file-selection dialog box for graphical selection of a file. The value property holds the name of the file the user has specified, but when a form containing a file-upload element is submitted, the browser sends the contents of the selected file to the server instead of just sending the filename. (For this to work, the form must use "multipart/form-data" encoding and the POST method.)

For security, the file-upload element does not allow HTML authors or JavaScript programmers to specify a default filename. The HTML value attribute is ignored, and the value property is read-only for this type of element, which means that only the user may enter a filename. When the user selects or edits a filename, a file-upload element triggers the onchange event handler.

"hidden"

An input element of this type is, in fact, hidden. The value property of this invisible form element holds an arbitrary string to be submitted to the web server. Use an element of this type if you want to submit data that the user did not input directly.

"image"

This type of input element is a form submit button that displays an image (specified by the src property) instead of displaying a textual label. The value property is unused. See the element type "submit" for further details.

"password"

This text input field is intended for input of sensitive data, such as passwords. As the user types, her input is masked (with asterisks, for example) to prevent bystanders from reading the input value over her shoulder. Note, however that the user's input is not encrypted in any way: when the form is submitted, it is sent in clear text. As a security precaution, some browsers may prevent JavaScript code from reading the value property. In other respects, a password input element behaves like an element of type "text". It triggers the onchange event handler when the user changes the displayed value.

"radio"

An input element of this type displays a single graphical radio button. A radio button is a button in a group of buttons that represents a set of mutually exclusive choices. When one button is selected, the previously selected button is deselected (as in the mechanical station preset buttons of old car radios). In order for a group of radio buttons to exhibit this mutually exclusive behavior, they must appear in the same <form> and must have the same name. For toggle buttons without mutual exclusion, use a type of "checkbox". Note that the HTML <select> tag can also be used for presenting exclusive or nonexclusive choices (see Select).

The checked property indicates whether a radio button is selected. There is no way to determine which button in a mutually exclusive group of radio buttons is selected: you must examine the checked property of each one. Radio buttons trigger the onclick event handler when selected or deselected.

The value property specifies a value to be submitted to a web server and is not displayed within the form. To specify a label for a radio button, do so externally to the <input> tag, such as with a <label> tag.

"reset"

An input element of this type is like a push button created with type "button" but has a more specialized purpose. When a reset button element is clicked, the values of all input elements in the form that contains it are reset to their default values (specified by the HTML value attribute or the JavaScript defaultValue property).

The value property specifies the text to appear in the button. A reset button triggers the onclick handler before resetting the form, and this handler may cancel the reset by returning false or by using other event cancellation methods described in Chapter 17, Events and Event Handling. See also the Form.reset( ) method and the Form.onreset event handler.

"submit"

An element of this type is a push button that submits the containing <form> when clicked. The value property specifies the text to appear in the button. The onclick event handler is triggered before the form is submitted, and a handler may cancel form submission by returning false. See also the Form.submit( ) method and Form.onsubmit event handler.

"text"

This is the default value of the type property; it creates a single-line text input field. The HTML value attribute specifies the default text to appear in the field, and the JavaScript value property holds the currently displayed text. The onchange event handler is triggered when the user edits the displayed text and then transfers input focus to some other element. Use size to specify the width of the input field and maxLength to specify the maximum number of characters that may be entered. When a form contains only a single input element of type "text", pressing Enter submits the form.

For multiline text input, use the HTML <textarea> tag (see Textarea). For masked text input, set type to "password".

Input element values

The value property of the Input object is a read/write string property that specifies the text that is sent to the web server when the form that contains the input element is submitted.

Depending on the value of the type property, the value property may also hold user-visible text. For input elements of type "text" and "file", this property holds whatever text the user has entered. For elements of type "button", "reset", and "submit", the value property specifies the text that appears in the button. For other element types, such as "checkbox", "radio", and "image", the contents of the value property are not displayed to the user and are used only for form submission purposes.

Input element names

The name property of the Input object is a String that provides a name for the input element. Its value comes from the HTML name attribute. The name of a form element is used for two purposes. First, it is used when the form is submitted. Data for each element in the form is usually submitted in the format:

name=value

where name and value are encoded as necessary for transmission. If a name is not specified for a form element, the data for that element cannot be submitted to a web server.

The second use of the name property is to refer to a form element in JavaScript code. The name of an element becomes a property of the form that contains the element. The value of this property is a reference to the element. For example, if address is a form that contains a text input element with the name zip, address.zip refers to that text input element.

For input elements of type "radio" and "checkbox", it is common to define more than one related object, each of which have the same name property. In this case, data is submitted to the server with this format:

name=value1,value2,...,valuen

Similarly, in JavaScript, each element that shares a name becomes an element of an array with that name. Thus, if four Checkbox objects in the form order share the name options, they are available in JavaScript as elements of the array order.options[].

Related form elements

The HTML <input> tag allows you to create a number of different form elements. But <button>, <select>, and <textarea> tags also create form elements.

See Also

Form, Form.elements[], Option, Select, Textarea; Chapter 18, Forms and Form Elements


Name

Input.blur( ): remove keyboard focus from a form element — DOM Level 2 HTML

Synopsis

void blur( )

Description

The blur() method of a form element removes keyboard focus from that element, triggering any onblur event handlers that were registered on the element. Note that calling blur() does not transfer focus to any other element.


Name

Input.click( ): simulate a mouse click on a form element — DOM Level 2 HTML

Synopsis

void click( )

Description

The click() method of a form element simulates a mouse click on the form element, triggering any onclick event handlers that were registered on the element.


Name

Input.focus( ): give keyboard focus to a form element — DOM Level 2 HTML

Synopsis

void focus( )

Description

The focus( ) method of a form element transfers keyboard focus to that element and triggers any onfocus event handlers that were registered on the element. That is, it makes the element active with respect to keyboard navigation and keyboard input. Thus, if you call focus( ) for an input element of type "text", any text the user subsequently types appears in that text element. Or, if you call focus( ) for an element of type "button", the user can then invoke that button from the keyboard.


Name

Input.onblur: the handler invoked when a form element loses focus — DOM Level 0

Synopsis

Function onblur

Description

The onblur property of an Input object specifies an event-handler function that is invoked when the user or the program transfers keyboard focus away from that input element. Calling blur( ) to remove focus from an element invokes onblur for that element. Note also that calling focus( ) to transfer focus to some other element causes the onblur event handler to be invoked for whichever element currently has the focus.

See Also

Element.addEventListener( ), Window.onblur; Chapter 17, Events and Event Handling


Name

Input.onchange: event handler invoked when a form element's value changes — DOM Level 2 Events

Synopsis

Function onchange

Description

The onchange property of an Input object specifies an event-handler function that is invoked when the user changes the value displayed by a form element. Such a change may be an edit to the text displayed in input elements of type "text", "password", and "file", or the selection or deselection of a toggle button of type "radio" or "checkbox". (Radio and checkbox elements always trigger the onclick handler and may also trigger the onchange handler.) Note that this event handler is invoked only when the user makes such a change; it is not invoked if a JavaScript program changes the value displayed by an element.

Also note that the onchange handler is not invoked every time the user enters or deletes a character in a text-entry form element. onchange is not intended for that type of character-by-character event handling; instead, onchange is invoked when the user's edit is complete. The browser assumes that the edit is complete when keyboard focus is moved from the current element to some other element—for example, when the user clicks on the next element in the form. See HTMLElement.onkeypress for character-by-character event notification.

The onchange event handler is not used by input elements of type "button", "hidden", "image", "reset", and "submit". Elements of those types use the onclick handler instead.

See Also

Element.addEventListener( ), HTMLElement.onkeypress; Chapter 17, Events and Event Handling


Name

Input.onclick: event handler invoked when a form element is clicked — DOM Level 2 Events

Synopsis

Function onclick

Description

The onclick property of an Input object specifies an event-handler function that is invoked when the user activates the input element. This is typically done by clicking the element with the mouse, but the onclick handler is also triggered when the user activates the element using keyboard traversal. The onclick handler is also invoked when the click( ) method is called for the element.

Note that the input elements of type "reset" and "submit" perform a default action when clicked: they reset and submit, respectively, the form that contains them. You can use the onclick event handlers of each element to perform actions in addition to these default actions. You can also prevent these default actions by returning false or by using the other event-cancellation techniques described in Chapter 17, Events and Event Handling. Note that you can do similar things with the onsubmit and onreset event handlers of the Form object itself.

See Also

Element.addEventListener( ); Chapter 17, Events and Event Handling


Name

Input.onfocus: event handler invoked when a form element gains focus — DOM Level 2 Events

Synopsis

Function onfocus

Description

The onfocus property of an Input object specifies an event-handler function that is invoked when the user transfers keyboard focus to that input element. Calling focus( ) to set focus to an element also invokes onfocus for that object.

See Also

Element.addEventListener( ), Window.onfocus; Chapter 17, Events and Event Handling


Name

Input.select( ): select the text in a form element — DOM Level 2 HTML

Synopsis

void select( )

Description

The select( ) method selects the text displayed in an input element of type "text", "password", or "file". The effects of selecting text may vary from platform to platform, but typically: the text is highlighted, it becomes available for cut and paste, and it is deleted if the user types another character.


Name

JavaArray, JavaClass, JavaObject, JavaPackage: see Part III


Name

JSObject: Java representation of a JavaScript object — Java class in Java plug-in

Synopsis

public final class netscape.javascript.JSObject extends Object

Methods

call( )

Invokes a method of the JavaScript object.

eval( )

Evaluates a string of JavaScript code in the context of the JavaScript object.

getMember( )

Gets the value of a property of the JavaScript object.

getSlot( )

Gets the value of an array element of the JavaScript object.

getWindow( )

Gets a "root" JSObject that represents the JavaScript Window object of the web browser.

removeMember( )

Deletes a property from the JavaScript object.

setMember( )

Sets the value of a property of the JavaScript object.

setSlot( )

Sets the value of an array element of the JavaScript object.

toString( )

Invokes the JavaScript toString( ) method of the JavaScript object and returns its result.

Description

JSObject is a Java class, not a JavaScript object; it cannot be used in your JavaScript programs. Instead, the JSObject is used by Java applets that wish to communicate with JavaScript by reading and writing JavaScript properties and array elements, invoking JavaScript methods, and evaluating and executing arbitrary strings of JavaScript code. Obviously, since JSObject is a Java class, you must understand Java programming in order to use it.

Full details on programming with the JSObject can be found in Chapter 23, Scripting Java Applets and Flash Movies.


Name

JSObject.call( ): invoke a method of a JavaScript object — Java method in Java plug-in

Synopsis

public Object call(StringmethodName, Object args[])

Arguments

methodName

The name of the JavaScript method to be invoked.

args[]

An array of Java objects to be passed as arguments to the method.

Returns

A Java object that represents the return value of the JavaScript method.

Description

The call( ) method of the Java JSObject class invokes a named method of the JavaScript object represented by the JSObject. Arguments are passed to the method as an array of Java objects, and the return value of the JavaScript method is returned as a Java object.

Chapter 23, Scripting Java Applets and Flash Movies describes the data conversion of the method arguments from Java objects to JavaScript values, and the method return value from a JavaScript value to a Java object.


Name

JSObject.eval( ): evaluate a string of JavaScript code — Java method in Java plug-in

Synopsis

public Object eval(Strings)

Arguments

s

A string that contains arbitrary JavaScript statements separated by semicolons.

Returns

The JavaScript value of the last expression evaluated in s, converted to a Java object.

Description

The eval( ) method of the Java JSObject class evaluates the JavaScript code contained in the string s in the context of the JavaScript object specified by the JSObject. The behavior of the eval( ) method of the Java JSObject class is much like that of the JavaScript global eval( ) function.

The argument s may contain any number of JavaScript statements separated by semicolons; these statements are executed in the order in which they appear. The return value of eval( ) is the value of the last statement or expression evaluated in s.


Name

JSObject.getMember( ): read a property of a JavaScript object — Java method in Java plug-in

Synopsis

public Object getMember(Stringname)

Arguments

name

The name of the property to be read.

Returns

A Java object that contains the value of the named property of the specified JSObject.

Description

The getMember( ) method of the Java JSObject class reads and returns to Java the value of a named property of a JavaScript object. The return value may be another JSObject object or a Double, Boolean, or String object, but it is returned as a generic Object, which you must cast as necessary.


Name

JSObject.getSlot( ): read an array element of a JavaScript object — Java method in Java plug-in

Synopsis

public Object getSlot(intindex)

Arguments

index

The index of the array element to be read.

Returns

The value of the array element at the specified index of a JavaScript object.

Description

The getSlot( ) method of the Java JSObject class reads and returns to Java the value of an array element at the specified index of a JavaScript object. The return value may be another JSObject object or a Double, Boolean, or String object, but it is returned as a generic Object, which you must cast as necessary.


Name

JSObject.getWindow( ): return initial JSObject for browser window — Java method in Java plug-in

Synopsis

public static JSObject getWindow(java.applet.Appletapplet)

Arguments

applet

An Applet object running in the web browser window for which a JSObject is to be obtained.

Returns

A JSObject that represents the JavaScript Window object for the web browser window that contains the specified applet.

Description

The getWindow( ) method is the first JSObject method that any Java applet calls. JSObject does not define a constructor, and the static getWindow( ) method provides the only way to obtain an initial "root" JSObject from which other JSObjects may be obtained.


Name

JSObject.removeMember( ): delete a property of a JavaScript object — Java method in Java plug-in

Synopsis

public void removeMember(Stringname)

Arguments

name

The name of the property to be deleted from the JSObject.

Description

The removeMember( ) method of the Java JSObject class deletes a named property from the JavaScript object represented by the JSObject.


Name

JSObject.setMember( ): set a property of a JavaScript object — Java method in Java plug-in

Synopsis

public void setMember(Stringname, Object value)

Arguments

name

The name of the property to be set in the JSObject.

value

The value to which the named property should be set.

Description

The setMember( ) method of the Java JSObject class sets the value of a named property of a JavaScript object from Java. The specified value may be any Java Object. Primitive Java values may not be passed to this method. In JavaScript, the specified value is accessible as a JavaObject object.


Name

JSObject.setSlot( ): set an array element of a JavaScript object — Java method in Java plug-in

Synopsis

public void setSlot(intindex, Object value)

Arguments

index

The index of the array element to be set in the JSObject.

value

The value to which the specified array element should be set.

Description

The setSlot( ) method of the Java JSObject class sets the value of a numbered array element of a JavaScript object from Java. The specified value may be any Java Object. Primitive Java values may not be passed to this method. In JavaScript, the specified value is accessible as a JavaObject object.


Name

JSObject.toString( ): return the string value of a JavaScript object — Java method in Java plug-in

Synopsis

public String toString( )

Returns

The string returned by invoking the toString( ) method of the JavaScript object represented by the specified Java JSObject.

Description

The toString( ) method of the Java JSObject class invokes the JavaScript toString( ) method of the JavaScript object represented by a JSObject and returns the result of that method.


Name

KeyEvent: details about a keyboard event — Firefox and compatible browsers: Event → UIEvent → KeyEvent

Properties

readonly boolean altKey

Whether the Alt key was held down when the event occurred.

readonly integer charCode

This number is the Unicode encoding of the printable character (if any) generated by a keypress event. This property is zero for nonprinting function keys and is not used for keydown and keyup events. Use String.fromCharCode( ) to convert this property to a string.

readonly boolean ctrlKey

Whether the Ctrl key was held down when the event occurred. Defined for all types of mouse events.

readonly integer keyCode

The virtual keycode of the key that was pressed. This property is used for all types of keyboard events. Keycodes may be browser-, OS-, and keyboard-hardware-dependent. Typically, when a key displays a printing character on it, the virtual keycode for that key is the same as the encoding of the character. Key codes for nonprinting function keys may vary more, but see Example 17-6, “A Keymap class for keyboard shortcuts” for a set of commonly used codes.

readonly boolean shiftKey

Whether the Shift key was held down when the event occurred. Defined for all types of mouse events.

Description

A KeyEvent object provides details about a keyboard event and is passed to event handlers for keydown, keypress, and keyup events. The DOM Level 2 Events standard does not cover keyboard events, and the KeyEvent object has not been standardized. This entry describes the Firefox implementation. Many of these properties are also supported in the IE event model; see the IE-specific properties described for the Event object. Note that in addition to the properties listed here, KeyEvent objects also inherit the properties of Event and UIEvent.

Chapter 17, Events and Event Handling includes several practical examples of working with KeyEvent objects.


Name

Layer: an obsolete Netscape API — Netscape 4 only; discontinued in Netscape 6

Description

The Layer object was Netscape 4's technique for supporting dynamically positionable HTML elements. It was never standardized and is now obsolete.


Name

Link: a hyperlink or anchor in an HTML document — DOM Level 0: Node → Element → HTMLElement → Link

Properties

The most important property of a Link is its href, which is the URL to which it links. The Link object also defines a number of other properties that hold portions of the URL. For each of these properties, the example given is a portion of the following (fictitious) URL:

http://www.oreilly.com:1234/catalog/search.html?q=JavaScript&m=10#results
String hash

Specifies the anchor portion of the Link's URL, including the leading hash (#) mark—for example, "#results". This anchor portion of a URL refers to a named position within the document referenced by the Link. In HTML files, positions are named with the name attribute of the <a> tag. (see Anchor).

String host

Specifies the hostname and port portions of a Link's URL—for example, "http://www.oreilly.com:1234".

String hostname

Specifies the hostname portion of a Link's URL—for example, "http://www.oreilly.com".

String href

Specifies the complete text of the Link's URL, unlike other Link URL properties that specify only portions of the URL.

String pathname

Specifies the pathname portion of a Link's URL—for example, "/catalog/search.html".

String port

Specifies the port portion of a Link's URL—for example, "1234".

String protocol

Specifies the protocol portion of a Link's URL, including the trailing colon—for example, "http:".

String search

Specifies the query portion of a Link's URL, including the leading question mark—for example, "?q=JavaScript&m=10".

In addition to these URL-related properties, Link objects also define properties that correspond to the attributes for the HTML <a> and <area> tags:

Property

Attribute

Description

String accessKey

accesskey

Keyboard shortcut

String charset

charset

Encoding of the destination document

String coords

coords

For <area> tags

String hreflang

hreflang

Language of the linked document

String name

name

Anchor name; see Anchor

String rel

rel

Link type

String rev

rev

Reverse link type

String shape

shape

For <area> tags

long tabIndex

tabindex

Link's position in tabbing order

String target

target

Name of the frame or window in which the destination document is to be displayed

String type

type

Content type of the destination document

Methods

blur( )

Takes keyboard focus away from the link.

focus( )

Scrolls the document so the link is visible and gives keyboard focus to the link.

Event Handlers

The Link object has special behavior for three event handlers:

onclick

Invoked when the user clicks on the link.

onmouseout

Invoked when the user moves the mouse off the link.

onmouseover

Invoked when the user moves the mouse over the link.

HTML Syntax

A Link object is created with standard <a> and </a> tags. The href attribute is required for all Link objects. If the name attribute is also specified, an Anchor object is also created:

<a href="url"                  // The destination of the link
    [ name="anchor_tag" ]      // Creates an Anchor object
    [ target="window_name" ]   // Where the new document should be displayed
    [ onclick="handler" ]      // Invoked when link is clicked
    [ onmouseover="handler" ]  // Invoked when mouse is over link
    [ onmouseout="handler" ]   // Invoked when mouse leaves link

>link text or image  // The visible part of the link
</a>

Description

A Link object represents a hyperlink in a document. Links are usually created with <a> tags that have an href attribute defined, but they may also be created with <area> tags inside a client-side image map. When an <a> tag has a name attribute instead of an href attribute, it defines a named position in a document and is represented by an Anchor object instead of a Link object. See Anchor for details.

All links in a document (whether created with <a> or <area> tags) are represented by Link objects in the links[] array of the Document object.

The destination of a hypertext link is a URL, of course, and many of the properties of the Link object specify the contents of that URL. In this way, the Link object is similar to the Location object, which also has a full set of URL properties.

Example

// Get the URL of the first hyperlink in the document
var url = document.links[0].href;

See Also

Anchor, Location


Name

Link.blur( ): take keyboard focus away from a hyperlink — DOM Level 0

Synopsis

void blur( );

Description

For web browsers that allow hyperlinks to have the keyboard focus, this method takes keyboard focus away from a hyperlink.


Name

Link.focus( ): make a link visible and give it keyboard focus — DOM Level 0

Synopsis

void focus( );

Description

This method scrolls the document so the specified hyperlink is visible. If the browser allows links to have keyboard focus, this method also gives keyboard focus to the link.


Name

Link.onclick: event handler invoked when a Link is clicked — DOM Level 0

Synopsis

Function onclick

Description

The onclick property of a Link object specifies an event-handler function that is invoked when the user clicks on the link. The browser default action after the event handler returns is to follow the hyperlink that was clicked. You can prevent this default by returning false or by using one of the other event-cancellation methods described in Chapter 17, Events and Event Handling.

See Also

Element.addEventListener( ), MouseEvent; Chapter 17, Events and Event Handling


Name

Link.onmouseout: event handler invoked when the mouse leaves a link — DOM Level 0

Synopsis

Function onmouseout

Description

The onmouseout property of a Link object specifies an event-handler function that is invoked when the user moves the mouse off a hypertext link. It is often used with the onmouseover event handler.

See Also

Element.addEventListener( ), Link.onmouseover, MouseEvent; Chapter 17, Events and Event Handling


Name

Link.onmouseover: event handler invoked when the mouse goes over a link — DOM Level 0

Synopsis

Function onmouseover

Description

The onmouseover property of a Link object specifies an event-handler function that is invoked when the user moves the mouse over a hypertext link. When the user holds the mouse over a hyperlink, the browser displays the URL for that link in the status line. In older browsers, it is possible to prevent this default action and display your own text in the status line. For security reasons (to help prevent phishing attacks, for example) most modern browsers have disabled this capability.

See Also

Element.addEventListener( ), Link.onmouseout, MouseEvent; Chapter 17, Events and Event Handling


Name

Location: represents and controls browser location — JavaScript 1.0: Object → Location

Synopsis

locationwindow.location

Properties

The properties of a Location object refer to the various portions of the current document's URL. In each of the following property descriptions, the example given is a portion of this (fictitious) URL:

http://www.oreilly.com:1234/catalog/search.html?q=JavaScript&m=10#results
hash

A read/write string property that specifies the anchor portion of the URL, including the leading hash (#) mark—for example, "#results". This portion of the document URL specifies the name of an anchor within the document.

host

A read/write string property that specifies the hostname and port portions of the URL—for example, "http://www.oreilly.com:1234".

hostname

A read/write string property that specifies the hostname portion of a URL—for example, "http://www.oreilly.com".

href

A read/write string property that specifies the complete text of the document's URL, unlike other Location properties that specify only portions of the URL. Setting this property to a new URL causes the browser to read and display the contents of the new URL.

pathname

A read/write string property that specifies the pathname portion of a URL—for example, "/catalog/search.html".

port

A read/write string (not a number) property that specifies the port portion of a URL— for example, "1234".

protocol

A read/write string property that specifies the protocol portion of a URL, including the trailing colon—for example, "http:".

search

A read/write string property that specifies the query portion of a URL, including the leading question mark—for example, "?q=JavaScript&m=10".

Methods

reload( )

Reloads the current document from the cache or the server.

replace( )

Replaces the current document with a new one without generating a new entry in the browser's session history.

Description

The location property of the Window object refers to a Location object that represents the web address (the "location") of the document currently displayed in that window. The href property contains the complete URL of that document, and the other properties of the Location object each describe a portion of that URL. These properties are much like the URL properties of the Link object. When a Location object is converted to a string, the value of the href property is returned. This means that you can use the expression location in place of location.href.

While the Link object represents a hyperlink in a document, the Location object represents the URL, or location, currently displayed by the browser. However, the Location object does more than that: it also controls the location displayed by the browser. If you assign a string containing a URL to the Location object or to its href property, the web browser responds by loading the newly specified URL and displaying the document it refers to.

Instead of setting location or location.href to replace the current URL with a completely new one, you can modify just a portion of the current URL by assigning strings to the other properties of the Location object. This creates a new URL with one new portion, which the browser loads and displays. For example, if you set the hash property of the Location object, you can cause the browser to move to a named location within the current document. Similarly, if you set the search property, you can cause the browser to reload the current URL with a new query string appended.

In addition to its URL properties, the Location object also defines two methods. The reload( ) method reloads the current document. The replace( ) method loads a new document without creating a new history entry for it; the new document replaces the current one in the browser's history list.

See Also

Link, the URL property of the HTMLDocument object


Name

Location.reload( ): reload the current document — JavaScript 1.1

Synopsis

location.reload( )

location.reload(force)

Arguments

force

An optional boolean argument that specifies whether the document should be reloaded even if the server reports that it has not been modified since it was last loaded. If this argument is omitted, or if it is false, the method reloads the full page only if it has changed since last loaded.

Description

The reload( ) method of the Location object reloads the document that is currently displayed in the window of the Location object. When called with no arguments or with the argument false, it uses the If-Modified-Since HTTP header to determine whether the document has changed on the web server. If the document has changed, reload reloads the document from the server, and if not, it reloads the document from the cache. This is the same action that occurs when the user clicks on the browser's Reload button.

When reload( ) is called with the argument true, it always bypasses the cache and reloads the document from the server, regardless of the last-modified time of the document. This is the same action that occurs when the user Shift-clicks on the browser's Reload button.


Name

Location.replace( ): replace one displayed document with another — JavaScript 1.1

Synopsis

location.replace(url)

Arguments

url

A string that specifies the URL of the new document that is to replace the current one.

Description

The replace( ) method of the Location object loads and displays a new document. Loading a document in this way is different from simply setting location or location .href in one important respect: the replace( ) method does not generate a new entry in the History object. When you use replace( ), the new URL overwrites the current entry in the History object. After calling replace( ), the browser's Back button does not return you to the previous URL; it returns you to the URL before that one.

See Also

History


Name

MimeType: represents a MIME datatype — JavaScript 1.1; not supported by IE: Object → MimeType

Synopsis

navigator.mimeTypes[i]
navigator.mimeTypes["type"]
navigator.mimeTypes.length

Properties

description

A read-only string that provides a human-readable description (in English) of the data type described by the MimeType.

enabledPlugin

A read-only reference to a Plugin object that represents the installed and enabled plug-in that handles the specified MIME type. If the MIME type is not handled by any plug-ins (for example, if it's handled directly by the browser), the value of this property is null. This property is also null when a plug-in exists but has been disabled.

suffixes

A read-only string that contains a comma-separated list of filename suffixes (not including the "." character) that are commonly used with files of the specified MIME type. For example, the suffixes for the "text/html" MIME type are "html, htm".

type

A read-only string that specifies the name of the MIME type. This is a unique string such as "text/html" or "image/jpeg" that distinguishes the MIME type from all others. It describes the general type of data and the data format used. The value of the type property can also be used as an index to access the elements of the navigator.mimeTypes[] array.

Description

The MimeType object represents a MIME type (i.e., a data format) supported by a web browser. The format may be supported directly by the browser, or through an external helper application or a plug-in for embedded data. MimeType objects are members of the mimeTypes[] array of the Navigator object. In IE, the mimeTypes[] array is always empty, and there is no equivalent of this functionality.

Usage

The navigator.mimeTypes[] array may be indexed numerically or with the name of the desired MIME type (which is the value of the type property). To check which MIME types are supported by a browser, you can loop through each element in the array numerically. Or, if you just want to check whether a specific type is supported, you can write code like the following:

var show_movie = (navigator.mimeTypes["video/mpeg"] != null);

See Also

Navigator, Plugin


Name

MouseEvent: details about a mouse event — DOM Level 2 Events: Event → UIEvent → MouseEvent

Properties

readonly boolean altKey

Whether the Alt key was held down when the event occurred. Defined for all types of mouse events.

readonly unsigned short button

Which mouse button changed state during a mousedown, mouseup, or click event. A value of 0 indicates the left button, a value of 2 indicates the right button, and a value of 1 indicates the middle mouse button. Note that this property is defined when a button changes state; it is not used to report whether a button is held down during a mousemove event, for example. Also, this property is not a bitmap: it cannot tell you if more than one button is held down.

readonly long clientX, clientY

The X and Y coordinates of the mouse pointer relative to the client area, or browser window. Note that these coordinates do not take document scrolling into account; if an event occurs at the very top of the window, clientY is 0 regardless of how far down the document has been scrolled. These properties are defined for all types of mouse events.

readonly boolean ctrlKey

Whether the Ctrl key was held down when the event occurred. Defined for all types of mouse events.

readonly boolean metaKey

Whether the Meta key was held down when the event occurred. Defined for all types of mouse events.

readonly Node relatedTarget

Refers to a document node that is related to the target node of the event. For mouseover events, it is the node the mouse left when it moved over the target. For mouseout events, it is the node the mouse entered when leaving the target. relatedTarget is undefined for other types of mouse events.

readonly long screenX, screenY

The X and Y coordinates of the mouse pointer relative to the upper-left corner of the user's monitor. These properties are defined for all types of mouse events.

readonly boolean shiftKey

Whether the Shift key was held down when the event occurred. Defined for all types of mouse events.

Methods

initMouseEvent( )

Initializes the properties of a newly created MouseEvent object.

Description

This interface defines the type of Event object that is passed to events of types click, mousedown, mousemove, mouseout, mouseover, and mouseup. Note that in addition to the properties listed here, this interface also inherits the properties of the UIEvent and Event interfaces.


Name

MouseEvent.initMouseEvent( ): initialize the properties of a MouseEvent object — DOM Level 2 Events

Synopsis

void initMouseEvent(StringtypeArg,
                    boolean canBubbleArg,
                    boolean cancelableArg,
                    AbstractView viewArg,
                    long detailArg,
                    long screenXArg,
                    long screenYArg,
                    long clientXArg,
                    long clientYArg,
                    boolean ctrlKeyArg,
                    boolean altKeyArg,
                    boolean shiftKeyArg,
                    boolean metaKeyArg,
                    unsigned short buttonArg,
                    Element relatedTargetArg);

Arguments

The many arguments to this method specify the initial values of the properties of this MouseEvent object, including the properties inherited from the Event and UIEvent interfaces. The name of each argument clearly indicates the property for which it specifies the value, so they are not listed individually here.

Description

This method initializes the various properties of a newly created MouseEvent object. It may be called only on a MouseEvent object created with Document.createEvent( ) and only before that MouseEvent is passed to Element.dispatchEvent( ).

See Also

Document.createEvent( ), Event.initEvent( ), UIEvent.initUIEvent( )


Name

Navigator: information about the browser in use — JavaScript 1.0: Object → Navigator

Synopsis

navigator

Properties

appCodeName

A read-only string that specifies the code name of the browser. In all browsers based on the Netscape code base (Netscape, Mozilla, Firefox), this is "Mozilla". For compatibility, this property is "Mozilla" in Microsoft browsers as well.

appName

A read-only string property that specifies the name of the browser. For Netscape-based browsers, the value of this property is "Netscape". In IE, the value of this property is "Microsoft Internet Explorer". Other browsers may identify themselves correctly or spoof another browser for compatibility.

appVersion

A read-only string that specifies version and platform information for the browser. The first part of this string is a version number. Pass the string to parseInt( ) to obtain only the major version number or to parseFloat( ) to obtain the major and minor version numbers as a floating-point value. The remainder of the string value of this property provides other details about the browser version, including the operating system it is running on. Unfortunately, however, the format of this information varies widely from browser to browser.

cookieEnabled

A read-only boolean that is true if the browser has cookies enabled and false if they are disabled.

mimeTypes[]

An array of MimeType objects, each of which represents one of the MIME types (e.g., "text/html" and "image/gif") supported by the browser. This array may be indexed numerically or by the name of the MIME type. The mimeTypes[] array is defined by Internet Explorer but is always empty because IE does not support the MimeType object.

platform

A read-only string that specifies the operating system and/or hardware platform on which the browser is running. Although there is no standard set of values for this property, some typical values are "Win32", "MacPPC", and "Linux i586".

plugins[]

An array of Plugin objects, each of which represents one plug-in that is installed in the browser. The Plugin object provides information about the plug-in, including a list of MIME types it supports.

The plugins[] array is defined by Internet Explorer but is always empty because IE does not support the Plugin object.

userAgent

A read-only string that specifies the value the browser uses for the user-agent header in HTTP requests. Typically, this is the value of navigator.appCodeName followed by a slash and the value of navigator.appVersion. For example:

Mozilla/4.0 (compatible; MSIE 4.01; Windows 95)

Functions

navigator.javaEnabled( )

Tests whether Java is supported and enabled in the current browser.

Description

The Navigator object contains properties that describe the web browser in use. You can use its properties to perform platform-specific customization. The name of this object obviously refers to the Netscape Navigator browser, but all browsers that implement JavaScript support this object as well. There is only a single instance of the Navigator object, which you can reference through the navigator property of any Window object.

Historically, the Navigator object has been used for "client sniffing" to run different code depending on what browser was in use. Example 14-3, “Determining browser vendor and version” shows a simple way to do this, and the accompanying text describes the many pitfalls of relying on the Navigator object. A better approach to cross-browser compatibility is described in the section called “Feature Testing”.

See Also

MimeType, Plugin


Name

Navigator.javaEnabled( ): test whether Java is available — JavaScript 1.1

Synopsis

navigator.javaEnabled( )

Returns

true if Java is supported by and enabled on the current browser; false otherwise.

Description

You can use navigator.javaEnabled( ) to check whether the current browser supports Java and can therefore display applets.


Name

Node: a node in a document tree — DOM Level 1 Core

Subinterfaces

Attr, CDATASection, CharacterData, Comment, Document, DocumentFragment, DocumentType, Element, ProcessingInstruction, Text

Constants

All Node objects implement one of the subinterfaces listed above. Every Node object has a nodeType property that specifies which subinterface it implements. These constants are the legal values for that property; their names are self-explanatory. Note that these are static properties of the Node( ) constructor function; they are not properties of individual Node objects. Also note that they are not supported by Internet Explorer. For compatibilty with IE, you must use numeric literals directly. For example, use 1 instead of Node.ELEMENT_NODE:

Node.ELEMENT_NODE = 1;                 // Element
Node.ATTRIBUTE_NODE = 2;               // Attr
Node.TEXT_NODE = 3;                    // Text
Node.CDATA_SECTION_NODE = 4;           // CDATASection
Node.PROCESSING_INSTRUCTION_NODE = 7;  // ProcessingInstruction
Node.COMMENT_NODE = 8;                 // Comment
Node.DOCUMENT_NODE = 9;                // Document
Node.DOCUMENT_TYPE_NODE = 10;          // DocumentType
Node.DOCUMENT_FRAGMENT_NODE = 11;      // DocumentFragment

Properties

readonly Attr[] attributes

If this is an Element node, the attributes property is a read-only, array-like object of Attr nodes that represent the attributes of that element. Note that this array is "live": any changes to the attributes of this element are immediately visible through it.

Technically, the attributes[] array is a NamedNodeMap object. The NamedNodeMap interface is specified by the Level 1 DOM standard and defines a number of methods for querying, setting, and removing elements. The Element interface defines better methods for setting and querying element attributes, and there are no other uses of NamedNodeMap that are relevant to client-side JavaScript. For these reasons, therefore, NamedNodeMap is not documented in this book. Treat the attributes property as a read-only array of Attr objects, or use the methods defined by Element to query, set, and delete attributes.

readonly Node[] childNodes

Contains the child nodes of the current node. This property should never be null: for nodes with no children, childNodes is an array with length zero. This property is technically a NodeList object, but it behaves just like a read-only array of Node objects. Note that the NodeList object is live: any changes to this element's list of children are immediately visible through the NodeList.

readonly Node firstChild

The first child of this node, or null if the node has no children.

readonly Node lastChild

The last child of this node, or null if the node has no children.

readonly String localName [DOM Level 2]

In XML documents that use namespaces, specifies the local part of the element or attribute name. This property is never used with HTML documents. See also the namespaceURI and prefix properties.

readonly String namespaceURI [DOM Level 2]

In XML documents that use namespaces, specifies the URI of the namespace of an Element or Attribute node. This property is never used with HTML documents. See also the localName and prefix properties.

readonly Node nextSibling

The sibling node that immediately follows this one in the childNodes[] array of the parentNode, or null if there is no such node.

readonly String nodeName

The name of the node. For Element nodes, specifies the tag name of the element, which can also be retrieved with the tagName property of the Element interface. For other types of nodes, the value depends on the node type. See the upcoming table in the Description section for details.

readonly unsigned short nodeType

The type of the node—i.e., which subinterface the node implements. The legal values are defined by the previously listed constants. Since these constants are not supported by Internet Explorer, however, you may prefer to use hardcoded values instead of the constants. In HTML documents, the common values for this property are 1 for Element nodes, 3 for Text nodes, 8 for Comment nodes, and 9 for the single top-level Document node.

String nodeValue

The value of a node. For Text nodes, it holds the text content. For other node types, the value depends on the nodeType, as shown in the upcoming table in the Description section.

readonly Document ownerDocument

The Document object of which this node is a part. For Document nodes, this property is null.

readonly Node parentNode

The parent (or container) node of this node, or null if there is no parent. Note that the Document, DocumentFragment, and Attr nodes never have parent nodes. Also, nodes that have been removed from the document, or that are newly created and have not yet been inserted into the document tree, have a parentNode of null.

String prefix [DOM Level 2]

For XML documents that use namespaces, specifies the namespace prefix of an Element or Attribute node. This property is never used with HTML documents. See also the localName and namespaceURL properties.

readonly Node previousSibling

The sibling node that immediately precedes this one in the childNodes[] array of the parentNode, or null if there is no such node.

readonly String xml [IE only]

If the node is an XML Document or an Element within an XML document, this IE-specific property returns the text of the element or document as a string. Compare this property to the innerHTML property of HTMLElement, and see XMLSerializer for a cross-platform alternative.

Methods

appendChild( )

Adds a node to the document tree by appending it to the childNodes[] array of this node. If the node is already in the document tree, it is removed and then reinserted at its new position.

cloneNode( )

Makes a copy of this node, or of the node and all its descendants.

hasAttributes( ) [DOM Level 2]

Returns true if this node is an Element and has any attributes.

hasChildNodes( )

Returns true if this node has any children.

insertBefore( )

Inserts a node into the document tree immediately before the specified child of this node. If the node being inserted is already in the tree, it is removed and reinserted at its new location.

isSupported( ) [DOM Level 2]

Returns true if the specified version number of a named feature is supported by this node.

normalize( )

"Normalizes" all Text node descendants of this node by deleting empty Text nodes and merging adjacent Text nodes.

removeChild( )

Removes (and returns) the specified child node from the document tree.

replaceChild( )

Removes (and returns) the specified child node from the document tree, replacing it with another node.

selectNodes( ) [IE only]

This IE-specific method performs an XPath query using this node as the root and returns the result as a NodeList. See Document.evaluate( ) and Document.createExpression( ) for DOM-based alternatives.

selectSingleNode( ) [IE only]

This IE-specific method performs an XPath query using this node as the root and returns the result as a single node. See Document.evaluate( ) and Document.createExpression( ) for DOM-based alternatives.

transformNode( ) [IE only]

This IE-specific method applies an XSLT stylesheet to this node and returns the results as a String. See XSLTProcessor for a non-IE alternative.

transformNodeToObject( ) [IE only]

This IE-specific method applies an XSLT stylesheet to this node and returns the results as a new Document object. See XSLTProcessor for a non-IE alternative.

Description

All objects in a document tree (including the Document object itself) implement the Node interface, which provides the fundamental properties and methods for traversing and manipulating the tree. (In Internet Explorer, the Node interface also defines some IE-specific properties and methods for working with XML documents, XPath expressions, and XSLT transforms. See Chapter 21, JavaScript and XML for details.)

The parentNode property and childNodes[] array allow you to move up and down the document tree. You can enumerate the children of a given node by looping through the elements of childNodes[] or by using the firstChild and nextSibling properties (or the lastChild and previousSibling properties, to loop backward). The appendChild( ), insertBefore( ), removeChild( ), and replaceChild( ) methods allow you to modify the document tree by altering the children of a node.

Every object in a document tree implements both the Node interface and a more specialized subinterface, such as Element or Text. The nodeType property specifies which subinterface a node implements. You can use this property to test the type of a node before using properties or methods of the more specialized interface. For example:

var n;   // Holds the node we're working with
if (n.nodeType == 1) {       // Or use the constant Node.ELEMENT_NODE
    var tagname = n.tagName; // If the node is an Element, this is the tag name
}

The nodeName and nodeValue properties specify additional information about a node, but their value depends on nodeType, as shown in the following table. Note that subinterfaces typically define specialized properties (such as the tagName property of Element nodes and the data property of Text nodes) for obtaining this information:

nodeType

nodeName

nodeValue

ELEMENT_NODE

The element's tag name

null

ATTRIBUTE_NODE

The attribute name

The attribute value

TEXT_NODE

#text

The text of the node

CDATA_SECTION_NODE

#cdata-section

The text of the node

PROCESSING_INSTRUCTION_NODE

The target of the PI

The remainder of the PI

COMMENT_NODE

#comment

The text of the comment

DOCUMENT_NODE

#document

null

DOCUMENT_TYPE_NODE

The document type name

null

DOCUMENT_FRAGMENT_NODE

#document-fragment

null

See Also

Document, Element, Text, XMLSerializer, XPathExpression, XSLTProcessor; Chapter 15, Scripting Documents


Name

Node.appendChild( ): insert a node as the last child of this node — DOM Level 1 Core

Synopsis

Node appendChild(NodenewChild)
    throws DOMException;

Arguments

newChild

The node to be inserted into the document. If the node is a DocumentFragment, it is not directly inserted, but each of its children are.

Returns

The node that was added.

Throws

This method may throw a DOMException with one of the following code values in the following circumstances:

HIERARCHY_REQUEST_ERR

The node does not allow children, it does not allow children of the specified type, or newChild is an ancestor of this node (or is this node itself).

WRONG_DOCUMENT_ERR

The ownerDocument property of newChild is not the same as the ownerDocument property of this node.

NO_MODIFICATION_ALLOWED_ERR

This node is read-only and does not allow children to be appended, or the node being appended is already part of the document tree, and its parent is read-only and does not allow children to be removed.

Description

This method adds the node newChild to the document, inserting it as the last child of this node. If newChild is already in the document tree, it is removed from the tree and then reinserted at its new location. If newChild is a DocumentFragment node, it is not inserted itself; instead, all its children are appended, in order, to the end of this node's childNodes[] array. Note that a node from (or created by) one document cannot be inserted into a different document. That is, the ownerDocument property of newChild must be the same as the ownerDocument property of this node.

Example

The following function inserts a new paragraph at the end of the document:

function appendMessage(message) {
    var pElement = document.createElement("p");
    var messageNode = document.createTextNode(message);
    pElement.appendChild(messageNode);    // Add text to paragraph
    document.body.appendChild(pElement);  // Add paragraph to document body
}

See Also

Node.insertBefore( ), Node.removeChild( ), Node.replaceChild( )


Name

Node.cloneNode( ): duplicate a node and, optionally, all of its descendants — DOM Level 1 Core

Synopsis

Node cloneNode(booleandeep);

Arguments

deep

If this argument is true, cloneNode( ) recursively clones all descendants of this node. Otherwise, it clones only this node.

Returns

A copy of this node.

Description

The cloneNode( ) method makes and returns a copy of the node on which it is called. If passed the argument true, it recursively clones all descendants of the node as well. Otherwise, it clones only the node and none of its children. The returned node is not part of the document tree, and its parentNode property is null. When an Element node is cloned, all of its attributes are also cloned. Note, however, that event-listener functions registered on a node are not cloned.


Name

Node.hasAttributes( ): determine whether a node has attributes — DOM Level 2 Core

Synopsis

boolean hasAttributes( );

Returns

true if this node has one or more attributes; false if it has none. Note that only Element nodes can have attributes.

See Also

Element.getAttribute( ), Element.hasAttribute( ), Node


Name

Node.hasChildNodes( ): determine whether a node has children — DOM Level 1 Core

Synopsis

boolean hasChildNodes( );

Returns

true if this node has one or more children; false if it has none.


Name

Node.insertBefore( ): insert a node into the document tree before the specified node — DOM Level 1 Core

Synopsis

Node insertBefore(NodenewChild,
                  Node refChild)
    throws DOMException;

Arguments

newChild

The node to be inserted into the tree. If it is a DocumentFragment, its children are inserted instead.

refChild

The child of this node before which newChild is to be inserted. If this argument is null, newChild is inserted as the last child of this node.

Returns

The node that was inserted.

Throws

This method may throw a DOMException with the following code values:

HIERARCHY_REQUEST_ERR

This node does not support children, it does not allow children of the specified type, or newChild is an ancestor of this node (or is this node itself).

WRONG_DOCUMENT_ERR

The ownerDocument property of newChild and this node are different.

NO_MODIFICATION_ALLOWED_ERR

This node is read-only and does not allow insertions, or the parent of newChild is read-only and does not allow deletions.

NOT_FOUND_ERR

refChild is not a child of this node.

Description

This method inserts the node newChild into the document tree as a child of this node. The new node is positioned within this node's childNodes[] array so that it comes immediately before the refChild node. If refChild is null, newChild is inserted at the end of childNodes[], just as with the appendChild( ) method. Note that it is illegal to call this method with a refChild that is not a child of this node.

If newChild is already in the document tree, it is removed from the tree and then reinserted at its new position. If newChild is a DocumentFragment node, it is not inserted itself; instead, each of its children is inserted, in order, at the specified location.

Example

The following function inserts a new paragraph at the beginning of a document:

function insertMessage(message) {
    var paragraph = document.createElement("p");  // Create a <p> Element
    var text = document.createTextNode(message);  // Create a Text node
    paragraph.appendChild(text);                  // Add text to the paragraph
    // Now insert the paragraph before the first child of the body
    document.body.insertBefore(paragraph, document.body.firstChild)
}

See Also

Node.appendChild( ), Node.removeChild( ), Node.replaceChild( )


Name

Node.isSupported( ): determine if a node supports a feature — DOM Level 2 Core

Synopsis

boolean isSupported(Stringfeature,
                    String version);

Arguments

feature

The name of the feature to test.

version

The version number of the feature to test, or the empty string to test for support of any version of the feature.

Returns

true if the node supports the specified version of the specified feature, and false if it does not.

Description

The W3C DOM standard is modular, and implementations are not required to implement all modules or features of the standard. This method tests whether the implementation of this node supports the specified version of the named feature. See DOMImplementation.hasFeature( ) for a list of values for the feature and version arguments.

See Also

DOMImplementation.hasFeature( )


Name

Node.normalize( ): merge adjacent Text nodes and remove empty ones — DOM Level 1 Core

Synopsis

void normalize( );

Description

This method traverses all descendants of this node and "normalizes" the document by removing any empty Text nodes and merging all adjacent Text nodes into a single node. This can simplify the tree structure after node insertions or deletions.

See Also

Text


Name

Node.removeChild( ): remove (and return) the specified child of this node — DOM Level 1 Core

Synopsis

Node removeChild(NodeoldChild)
    throws DOMException;

Arguments

oldChild

The child node to remove.

Returns

The node that was removed.

Throws

This method may throw a DOMException with the following code values in the following circumstances:

NO_MODIFICATION_ALLOWED_ERR

This node is read-only and does not allow children to be removed.

NOT_FOUND_ERR

oldChild is not a child of this node.

Description

This method removes the specified child from the childNodes[] array of this node. It is an error to call this method with a node that is not a child. removeChild( ) returns the oldChild node after removing it. oldChild continues to be a valid node and may be reinserted into the document later.

Example

You can delete the last child of the document body with this code:

document.body.removeChild(document.body.lastChild);

See Also

Node.appendChild( ), Node.insertBefore( ), Node.replaceChild( )


Name

Node.replaceChild( ): replace a child node with a new node — DOM Level 1 Core

Synopsis

Node replaceChild(NodenewChild,
                  Node oldChild)
    throws DOMException;

Arguments

newChild

The replacement node.

oldChild

The node to be replaced.

Returns

The node that was removed from the document and replaced.

Throws

This method may throw a DOMException with the following code values:

HIERARCHY_REQUEST_ERR

This node does not allow children, it does not allow children of the specified type, or newChild is an ancestor of this node (or is this node itself).

WRONG_DOCUMENT_ERR

newChild and this node have different values for ownerDocument.

NO_MODIFICATION_ALLOWED_ERR

This node is read-only and does not allow replacement, or newChild is the child of a node that does not allow removals.

NOT_FOUND_ERR

oldChild is not a child of this node.

Description

This method replaces one node of the document tree with another. oldChild is the node to be replaced and must be a child of this node. newChild is the node that takes its place in the childNodes[] array of this node.

If newChild is already part of the document, it is first removed from the document before being reinserted at its new position. If newChild is a DocumentFragment, it is not inserted itself; instead each of its children is inserted, in order, at the position formerly occupied by oldChild.

Example

The following code replaces a node n with a <b> element and then inserts the replaced node into the <b> element, which reparents the node and makes it appear in bold:

// Get the first child node of the first paragraph in the document
var n = document.getElementsByTagName("p")[0].firstChild;
var b = document.createElement("b");  // Create a <b> element
n.parentNode.replaceChild(b, n);      // Replace the node with <b>
b.appendChild(n);                     // Reinsert the node as a child of <b>

See Also

Node.appendChild( ), Node.insertBefore( ), Node.removeChild( )


Name

Node.selectNodes( ): select nodes with an XPath query — IE 6

Synopsis

NodeList selectNodes(Stringquery)

Arguments

query

The XPath query string.

Returns

A single Node that matches the query, or null if there are none.

Description

This IE-specific method evaluates an XPath expression using this node as the context node. It returns the first matching node found, or null if no nodes match. The selectSingleNode( ) method exists only on the nodes of XML documents, not HTML documents. Note that since Document objects are themselves nodes, this method can be applied to entire XML documents.

For a cross-browser alternative, see Document.evaluate( ).

See Also

Document.evaluate( ), XPathExpression; Chapter 21, JavaScript and XML


Name

Node.transformNode( ): transform a node to a string using XSLT — IE 6

Synopsis

String transformNode(Documentxslt)

Arguments

xslt

An XSLT stylesheet, parsed to a Document object.

Returns

The text produced by applying the specified stylesheet to this node and its descendants.

Description

This IE-specific method transforms a Node and its descendants according to the rules specified in an XSLT stylesheet and returns the result as an unparsed string. The transformNode( ) method exists only on the nodes of XML documents, not HTML documents. Note that since Document objects are themselves nodes, this method can be applied to entire XML documents.

For similar functionality in other browsers, see XSLTProcessor.

See Also

XSLTProcessor, Node.transformNodeToObject( ); Chapter 21, JavaScript and XML


Name

Node.transformNodeToObject( ): transform a node to a document using XSLT — IE 6

Synopsis

Document transformNodeToObject(Documentxslt)

Arguments

xslt

An XSLT stylesheet, parsed to a Document object.

Returns

The result of the transformation, parsed to a Document object.

Description

This IE-specific method transforms a Node and its descendants according to the rules specified in an XSLT stylesheet and returns the result as a Document object. The transformNodeToObject( ) method exists only on the nodes of XML documents, not HTML documents. Note that since Document objects are themselves nodes, this method can be applied to entire XML documents.

For similar functionality in other browsers, see XSLTProcessor.

See Also

XSLTProcessor, Node.transformNode(); Chapter 21, JavaScript and XML


Name

NodeList: a read-only array of nodes — DOM Level 1 Core: Object → NodeList

Properties

readonly unsigned long length

The number of nodes in the array.

Methods

item()

Returns the specified element of the array.

Description

The NodeList interface defines a read-only, ordered list (i.e., an array) of Node objects. The length property specifies how many nodes are in the list, and the item( ) method allows you to obtain the node at a specified position in the list. The elements of a NodeList are always valid Node objects: NodeLists never contain null elements.

In JavaScript, NodeList objects behave like JavaScript arrays, and you can query an element from the list using square-bracket array notation instead of calling the item( ) method. However, you cannot assign new nodes to a NodeList using square brackets. Since it is always easier to think of a NodeList object as a read-only JavaScript array, this book uses the notation Element[] or Node[] (i.e., an Element array or Node array) instead of NodeList. The methods Document.getElementsByTagName( ), Element.getElementsByTagName( ), and HTMLDocument.getElementsByName( ) are all documented in this book as returning a Element[] instead of a NodeList object. Similarly, the childNodes property of the Node object is technically a NodeList object, but the Node reference page defines it as a Node[], and the property itself is usually referred to as "the childNodes[] array."

Note that NodeList objects are live: they are not static snapshots but immediately reflect changes to the document tree. For example, if you have a NodeList that represents the children of a specific node and you then delete one of those children, the child is removed from your NodeList. Be careful when you are looping through the elements of a NodeList: the body of your loop can make changes to the document tree (such as deleting nodes) that can affect the contents of the NodeList!

See Also

Document, Element


Name

NodeList.item(): get an element of a NodeList — DOM Level 1 Core

Synopsis

Node item(unsigned long index);

Arguments

index

The position (or index) of the desired node in the NodeList. The index of the first node in the NodeList is 0, and the index of the last Node is length−1.

Returns

The node at the specified position in the NodeList, or null if index is less than zero or greater than or equal to the length of the NodeList.

Description

This method returns the specified element of a NodeList. In JavaScript, you can use the square-bracket array notation instead of calling item( ).


Name

Option: an option in a Select element — DOM Level 2 HTML: Node → Element → HTMLElement → HTMLOptionElement

Constructor

Option objects can be created with Document.createElement( ), like any other tag. In the DOM Level 0, Option objects can also be dynamically created with the Option( ) constructor, as follows:

new Option(Stringtext, String value,
           boolean defaultSelected, boolean selected)

Arguments

text

An optional string argument that specifies the text property of the Option object.

value

An optional string argument that specifies the value property of the Option object.

defaultSelected

An optional boolean argument that specifies the defaultSelected property of the Option object.

selected

An optional boolean argument that specifies the selected property of the Option object.

Properties

boolean defaultSelected

The initial value of the selected attribute of the <option> element. If the form is reset, the selected property is reset to the value of this property. Setting this property also sets the value of the selected property.

boolean disabled

If true, this <option> element is disabled, and the user is not allowed to select it. Mirrors the disabled attribute.

readonlyHTMLFormElementform

A reference to the <form> element that contains this element.

readonly long index

The position of this <option> element within the <select> element that contains it.

String label

The text to be displayed for the option. Mirrors the label attribute. If this property is not specified, the plain-text content of the <option> element is used instead.

boolean selected

The current state of this option: if true, the option is selected. The initial value of this property comes from the selected attribute.

readonly String text

The plain text contained within the <option> element. This text appears as the label for the option.

String value

The value submitted with the form if this option is selected when form submission occurs. Mirrors the value attribute.

HTML Syntax

An Option object is created by an <option> tag within a <select> tag, which is within a <form>. Multiple <option> tags typically appear within the <select> tag:

< form ...>
< select  ...>
< option
  [ value="value" ]  // The value returned when the form is submitted
  [ selected ] >      // Specifies whether this option is initially selected
   plain_text_label  // The text to display for this option
[ < /option>  ]
  ...

< /select>
  ...
/form>

Description

The Option object describes a single option displayed within a Select object. The properties of this object specify whether it is selected by default, whether it is currently selected, the position it has in the options[] array of its containing Select object, the text it displays, and the value it passes to the server if it is selected when the containing form is submitted.

Note that although the text displayed by this option is specified outside the <option> tag, it must be plain, unformatted text without any HTML tags so it can be properly displayed in listboxes and drop-down menus that do not support HTML formatting.

You can dynamically create new Option objects for display in a Select object with the Option( ) constructor. Once a new Option object is created, it can be appended to the list of options in a Select object with Select.add( ). See Select.options[] for further details.

See Also

Select, Select.options[]; Chapter 18, Forms and Form Elements


Name

Packages: see Packages in Part III


Name

Password: see Input


Name

Plugin: describes an installed plug-in — JavaScript 1.1; not supported by IE: Object → Plugin

Synopsis

navigator.plugins[i]
navigator.plugins['name']

Properties

description

A read-only string that contains a human-readable description of the specified plug-in. The text of this description is provided by the creators of the plug-in and may contain vendor and version information as well as a brief description of the plug-in's function.

filename

A read-only string that specifies the name of the file on disk that contains the plug-in program itself. This name may vary from platform to platform. The name property is more useful than filename for identifying a plug-in.

length

Each Plugin object is also an array of MimeType objects that specify the data formats supported by the plug-in. As with all arrays, the length property specifies the number of elements in the array.

name

The name property of a Plugin object is a read-only string that specifies the name of the plug-in. Each plug-in should have a name that uniquely identifies it. The name of a plug-in can be used as an index into the navigator.plugins[] array. You can use this fact to determine easily whether a particular named plug-in is installed in the current browser:

var flash_installed = (navigator.plugins["Shockwave Flash"] != null);

Array Elements

The array elements of the Plugin object are MimeType objects that specify the data formats supported by the plug-in. The length property specifies the number of MimeType objects in this array.

Description

A plug-in is a software module that can be invoked by a browser to display specialized types of embedded data within the browser window. Plug-ins are represented by the Plugin object, and the plugins[] property of the Navigator object is an array of Plugin objects representing the installed plug-ins for the browser. IE does not support the Plugin object, and the navigator.plugins[] array is always empty on that browser.

navigator.plugins[] may be indexed numerically when you want to loop through the complete list of installed plug-ins, looking for one that meets your needs (for example, one that supports the MIME type of the data you want to embed in your web page). This array can also be indexed by plug-in name, however. That is, if you want to check whether a specific plug-in is installed in the user's browser, you might use code like this:

var flash_installed = (navigator.plugins["Shockwave Flash"] != null);

The name used as an array index with this technique is the same name that appears as the value of the name property of the Plugin.

The Plugin object is somewhat unusual in that it has both regular object properties and array elements. The properties of the Plugin object provide various pieces of information about the plug-in, and its array elements are MimeType objects that specify the embedded data formats that the plug-in supports. Don't confuse the fact that Plugin objects are stored in an array of the Navigator object with the fact that each Plugin object is itself an array of MimeType objects. Because there are two arrays involved, you may end up with code that looks like this:

navigator.plugins[i][j]            // The jth MIME type of the ith plug-in
navigator.plugins["LiveAudio"][0]  // First MIME type of LiveAudio plug-in

Finally, note that while the array elements of a Plugin object specify the MIME types supported by that plug-in, you can also determine which plug-in supports a given MIME type with the enabledPlugin property of the MimeType object.

See Also

Navigator, MimeType


Name

ProcessingInstruction : a processing instruction in an XML document — DOM Level 1 XML: Node → ProcessingInstruction

Properties

String data

The content of the processing instruction (i.e., the first nonspace character after the target up to but not including the closing ?>).

readonly String target

The target of the processing instruction. This is the first identifier that follows the opening <?; it specifies the "processor" for which the processing instruction is intended.

Description

This infrequently used interface represents a processing instruction (or PI) in an XML document. Programmers working with HTML documents will never encounter a ProcessingInstruction node.

See Also

Document.createProcessingInstruction()


Name

Radio: see Input


Name

Range: represents a contiguous range of a document — DOM Level 2 Range: Object → Range

Constants

These constants specify how the boundary points of two Range objects are compared. They are the legal values for the how argument to the compareBoundaryPoints( ) method (see the Range.compareBoundaryPoints( ) reference page):

unsigned short START_TO_START = 0

Compares the start of the specified range to the start of this range.

unsigned short START_TO_END = 1

Compares the start of the specified range to the end of this range.

unsigned short END_TO_END = 2

Compares the end of the specified range to the end of this range.

unsigned short END_TO_START = 3

Compares the end of the specified range to the start of this range.

Properties

The Range interface defines the following properties. Note that all of these properties are read-only. You cannot change the start or end points of a range by setting properties; you must call setEnd( ) or setStart( ) instead. Note also that after you call the detach( ) method of a Range object, any subsequent attempt to read any of these properties throws a DOMException with a code of INVALID_STATE_ERR:

readonly boolean collapsed

true if the start and the end of the range are at the same point in the document—that is, if the range is empty or "collapsed."

readonly Node commonAncestorContainer

The most deeply nested Document node that contains (i.e., is an ancestor of) both the start and end points of the range.

readonly Node endContainer

The Document node that contains the end point of the range.

readonly long endOffset

The position of the range's ending point within endContainer.

readonly Node startContainer

The Document node that contains the starting point of the range.

readonly long startOffset

The position of the range's starting point within startContainer.

Methods

The Range interface defines the following methods. Note that if you call detach( ) on a range, any subsequent calls of any methods on that range throw a DOMException with a code of INVALID_STATE_ERR. Because this exception is ubiquitous within this interface, it is not listed in the reference pages for the individual Range methods:

cloneContents()

Returns a new DocumentFragment object that contains a copy of the region of the document represented by this range.

cloneRange( )

Creates a new Range object that represents the same region of the document as this one.

collapse( )

Collapses this range so that one boundary point is the same as the other.

compareBoundaryPoints( )

Compares a boundary point of the specified range to a boundary point of this range and returns −1, 0, or 1, depending on their order. Which points to compare is specified by the first argument, which must be one of the constants listed in the Constants section.

deleteContents( )

Deletes the region of the document represented by this range.

detach( )

Tells the implementation that this range will no longer be used and that it can stop keeping track of it. If you call this method for a range, subsequent method calls or property lookups on that range throw a DOMException with a code of INVALID_STATE_ERR.

extractContents( )

Deletes the region of the document represented by this range, but returns the contents of that region as a DocumentFragment object. This method is like a combination of cloneContents( ) and deleteContents( ).

insertNode( )

Inserts the specified node into the document at the start point of the range.

selectNode( )

Sets the boundary points of this range so that it contains the specified node and all of its descendants.

selectNodeContents( )

Sets the boundary points of this range so that it contains all the descendants of the specified node but not the node itself.

setEnd( )

Sets the end point of this range to the specified node and offset.

setEndAfter( )

Sets the end point of this range to immediately after the specified node.

setEndBefore( )

Sets the end point of this range to immediately before the specified node.

setStart( )

Sets the start position of this range to the specified offset within the specified node.

setStartAfter( )

Sets the start position of this range to immediately after the specified node.

setStartBefore( )

Sets the start position of this range to immediately before the specified node.

surroundContents( )

Inserts the specified node into the document at the start position of the range and then reparents all the nodes within the range so that they become descendants of the newly inserted node.

toString( )

Returns the plain-text content of the document region described by this range.

Description

A Range object represents a contiguous range or region of a document, such as the region that the user might select with a mouse drag in a web browser window. If an implementation supports the Range module (at the time of this writing, Firefox and Opera support it, Safari has partial support, and Internet Explorer does not support it), the Document object defines a createRange( ) method that you can call to create a new Range object. Be careful, however: Internet Explorer defines an incompatible Document.createRange( ) method that returns a nonstandard object similar to, but not compatible with, the Range interface. The Range interface defines a number of methods for specifying a "selected" region of a document and several more methods for implementing cut-and-paste operations on the selected region.

A range has two boundary points: a start point and an end point. Each boundary point is specified by a combination of a node and an offset within that node. The node is typically an Element, Document, or Text node. For Element and Document nodes, the offset refers to the children of that node. An offset of 0 specifies a boundary point before the first child of the node. An offset of 1 specifies a boundary point after the first child and before the second child. If the boundary node is a Text node, however, the offset specifies a position between two characters of that text.

The properties of the Range interface provide a way to obtain boundary nodes and offsets of a range. The methods of the interface provide a number of ways to set the boundaries of a range. Note that the boundaries of a range may be set to nodes within a Document or a DocumentFragment.

Once the boundary points of a range are defined, you can use deleteContents( ), extractContents( ), cloneContents( ), and insertNode( ) to implement cut, copy, and paste operations.

When a document is altered by insertion or deletion, all Range objects that represent portions of that document are altered, if necessary, so that their boundary points remain valid and they represent (as closely as possible) the same document content.

See Also

Document.createRange( ), DocumentFragment


Name

Range.cloneContents(): copy range contents into a DocumentFragment — DOM Level 2 Range

Synopsis

DocumentFragment cloneContents( )
    throws DOMException;

Returns

A DocumentFragment object that contains a copy of the document content within this range.

Throws

If this range includes a DocumentType node, this method throws a DOMException with a code of HIERARCHY_REQUEST_ERR.

Description

This method duplicates the contents of this range and returns the results in a DocumentFragment object.

See Also

DocumentFragment, Range.deleteContents( ), Range.extractContents( )


Name

Range.cloneRange(): make a copy of this range — DOM Level 2 Range

Synopsis

Range cloneRange( );

Returns

A new Range object that has the same boundary points as this range.

See Also

Document.createRange( )


Name

Range.collapse(): make one boundary point equal to the other — DOM Level 2 Range

Synopsis

void collapse(booleantoStart)
    throws DOMException;

Arguments

toStart

If this argument is true, the method sets the end point of the range to the same value as the starting point. Otherwise, it sets the starting point to the same value as the end point.

Description

This method sets one boundary point of the range to be the same as the other point. The point to be modified is specified by the toStart argument. After this method returns, the range is said to be collapsed: it represents a single point within a document and has no content. When a range is collapsed like this, its collapsed property is true.


Name

Range.compareBoundaryPoints(): compare positions of two ranges — DOM Level 2 Range

Synopsis

short compareBoundaryPoints(unsigned shorthow,
                            Range sourceRange)
    throws DOMException;

Arguments

how

Specifies how to perform the comparison (i.e., which boundary points to compare). Legal values are the constants defined by the Range interface.

sourceRange

The range that is to be compared to this range.

Returns

The value −1 if the specified boundary point of this range is before the specified boundary point of sourceRange, 0 if the two specified boundary points are the same, or 1 if the specified boundary point of this range is after the specified boundary point of sourceRange.

Throws

If sourceRange represents a range of a different document than this range does, this method throws a DOMException with a code of WRONG_DOCUMENT_ERR.

Description

This method compares a boundary point of this range to a boundary point of the specified sourceRange and returns a value that specifies their relative order in the document source. The how argument specifies which boundary points of each range are to be compared. The legal values for this argument, and their meanings, are as follows:

Range.START_TO_START

Compares the start points of the two Range nodes.

Range.END_TO_END

Compares the end points of the two Range nodes.

Range.START_TO_END

Compares the start point of sourceRange to the end point of this range.

Range.END_TO_START

Compares the end point of sourceRange to the start point of this range.

The return value of this method is a number that specifies the relative position of this range to the specified sourceRange. Therefore, you might expect the range constants for the how argument to specify the boundary point for this range first and the boundary point for sourceRange second. Counterintuitively, however, the Range.START_TO_END constant specifies a comparison of the end point of this range with the start point of the specified sourceRange. Similarly, the Range.END_TO_START constant specifies a comparison of the start point of this range with the end point of the specified range.


Name

Range.deleteContents(): delete a region of the document — DOM Level 2 Range

Synopsis

void deleteContents( )
    throws DOMException;

Throws

If any portion of the document that is represented by this range is read-only, this method throws a DOMException with a code of NO_MODIFICATION_ALLOWED_ERR.

Description

This method deletes all document content represented by this range. When this method returns, the range is collapsed with both boundary points at the start position. Note that the deletion may result in adjacent Text nodes that can be merged with a call to Node.normalize( ).

See Range.cloneContents( ) for a way to copy document content and Range.extractContents( ) for a way to copy and delete document content in a single operation.

See Also

Node.normalize( ), Range.cloneContents( ), Range.extractContents( )


Name

Range.detach(): free a Range object — DOM Level 2 Range

Synopsis

void detach( )
    throws DOMException;

Throws

Like all Range methods, detach( ) throws a DOMException with a code of INVALID_STATE_ERR if it is called on a Range object that has already been detached.

Description

DOM implementations keep track of all Range objects created for a document because they may need to change the range boundary points when the document is modified. When you are certain that a Range object isn't needed any more, call the detach( ) method to tell the implementation that it no longer needs to keep track of that range. Note that once this method has been called for a Range object, any use of that Range throws an exception. Calling detach( ) is not required but may improve performance in some circumstances when the document is being modified. A Range object is not subject to immediate garbage collection.


Name

Range.extractContents( ): delete document content and return it in a DocumentFragment — DOM Level 2 Range

Synopsis

DocumentFragment extractContents( )
    throws DOMException;

Returns

A DocumentFragment node that contains the contents of this range.

Throws

This method throws a DOMException with a code of NO_MODIFICATION_ALLOWED_ERR if any part of the document content to be extracted is read-only or a code of HIERARCHY_REQUEST_ERR if the range contains a DocumentType node.

Description

This method deletes the specified range of a document and returns a DocumentFragment node that contains the deleted content. When this method returns, the range is collapsed, and the document may contain adjacent Text nodes (which can be merged with Node.normalize( )).

See Also

DocumentFragment, Range.cloneContents( ), Range.deleteContents( )


Name

Range.insertNode( ): insert a node at the start of a range — DOM Level 2 Range

Synopsis

void insertNode(NodenewNode)
    throws RangeException,
           DOMException;

Arguments

newNode

The node to be inserted into the document.

Throws

This method throws a RangeException with a code of INVALID_NODE_TYPE_ERR if newNode is an Attr, Document, Entity, or Notation node.

This method also throws a DOMException with one of the following code values under the following conditions:

HIERARCHY_REQUEST_ERR

The node that contains the start of the range does not allow children, it does not allow children of the specified type, or newNode is an ancestor of that node.

NO_MODIFICATION_ALLOWED_ERR

The node that contains the start of the range or any of its ancestors is read-only.

WRONG_DOCUMENT_ERR

newNode is part of a different document than the range is.

Description

This method inserts the specified node (and all its descendants) into the document at the start position of this range. When this method returns, this range includes the newly inserted node. If newNode is already part of the document, it is removed from its current position and then reinserted at the start of the range. If newNode is a DocumentFragment node, it is not inserted itself, but all of its children are inserted, in order, at the start of the range.

If the node that contains the start of the range is a Text node, it is split into two adjacent nodes before the insertion takes place. If newNode is a Text node, it is not merged with any adjacent Text nodes after it is inserted. To merge adjacent Text nodes, call Node.normalize( ).

See Also

DocumentFragment, Node.normalize( )


Name

Range.selectNode(): set range boundaries to a node — DOM Level 2 Range

Synopsis

void selectNode(NoderefNode)
    throws RangeException, DOMException;

Arguments

refNode

The node to be "selected" (i.e., the node that is to become the content of this range).

Throws

A RangeException with a code of INVALID_NODE_TYPE_ERR if refNode is an Attr, Document, or DocumentFragment.

A DOMException with a code of WRONG_DOCUMENT_ERR if refNode is part of a different document than the one through which this range was created.

Description

This method sets the contents of this range to the specified refNode—i.e., it "selects" the node and its descendants.

See Also

Range.selectNodeContents( )


Name

Range.selectNodeContents( ): set range boundaries to the children of a node — DOM Level 2 Range

Synopsis

void selectNodeContents(NoderefNode)
    throws RangeException, DOMException;

Arguments

refNode

The node whose children are to become the contents of this range.

Throws

A RangeException with a code of INVALID_NODE_TYPE_ERR if refNode or one of its ancestors is a DocumentType, Entity, or Notation node.

A DOMException with a code of WRONG_DOCUMENT_ERR if refNode is part of a different document than the one through which this range was created.

Description

This method sets the boundary points of this range so that the range contains the children of refNode.

See Also

Range.selectNode( )


Name

Range.setEnd( ): set the end point of a range — DOM Level 2 Range

Synopsis

void setEnd(NoderefNode,
            long offset)
    throws RangeException, DOMException;

Arguments

refNode

The node that contains the new end point.

offset

The position of the end point within refNode.

Throws

A RangeException with a code of INVALID_NODE_TYPE_ERR if refNode or one of its ancestors is a DocumentType node.

A DOMException with a code of WRONG_DOCUMENT_ERR if refNode is part of a different document than the one through which this range was created, or a code of INDEX_SIZE_ERR if offset is negative or is greater than the number of children or characters in refNode.

Description

This method sets the end point of a range by specifying the values of the endContainer and endOffset properties.


Name

Range.setEndAfter( ): end a range after a specified node — DOM Level 2 Range

Synopsis

void setEndAfter(NoderefNode)
    throws RangeException, DOMException;

Arguments

refNode

The node after which the end point of the range is to be set.

Throws

A RangeException with a code of INVALID_NODE_TYPE_ERR if refNode is a Document, DocumentFragment or Attr node, or if the root container of refNode is not a Document, DocumentFragment, or Attr node.

A DOMException with a code of WRONG_DOCUMENT_ERR if refNode is part of a different document than the one through which this range was created.

Description

This method sets the end point of this range to fall immediately after the specified refNode.


Name

Range.setEndBefore( ): end a range before the specified node — DOM Level 2 Range

Synopsis

void setEndBefore(NoderefNode)
    throws RangeException, DOMException;

Arguments

refNode

The node before which the end point of the range is to be set.

Throws

This method throws the same exceptions in the same circumstances as Range.setEndAfter( ). See that method for details.

Description

This method sets the end point of this range to fall immediately before the specified refNode.


Name

Range.setStart( ): set the start point of a range — DOM Level 2 Range

Synopsis

void setStart(NoderefNode,
              long offset)
    throws RangeException, DOMException;

Arguments

refNode

The node that contains the new start point.

offset

The position of the new start point within refNode.

Throws

This method throws the same exceptions, for the same reasons, as Range.setEnd( ). See that reference page for details.

Description

This method sets the start point of this range by specifying the values of the startContainer and startOffset properties.


Name

Range.setStartAfter( ): start a range after the specified node — DOM Level 2 Range

Synopsis

void setStartAfter(NoderefNode)
    throws RangeException, DOMException;

Arguments

refNode

The node after which the start point of the range is to be set.

Throws

This method throws the same exceptions in the same circumstances as Range.setEndAfter( ). See that reference page for details.

Description

This method sets the starting point of this range to be immediately after the specified refNode.


Name

Range.setStartBefore( ): start a range before the specified node — DOM Level 2 Range

Synopsis

void setStartBefore(NoderefNode)
    throws RangeException, DOMException;

Arguments

refNode

The node before which the start point of the range is to be set.

Throws

This method throws the same exceptions in the same circumstances as Range.setEndAfter( ). See that reference page for details.

Description

This method sets the starting point of this range to be immediately before the specified refNode.


Name

Range.surroundContents( ): surround range contents with the specified node — DOM Level 2 Range

Synopsis

void surroundContents(NodenewParent)
    throws RangeException, DOMException;

Arguments

newParent

The node that is to become the new parent of the contents of this range.

Throws

This method throws a DOMException or RangeException with one of the following code values in the following circumstances:

DOMException.HIERARCHY_REQUEST_ERR

The container node of the start of the range does not allow children or does not allow children of the type of newParent, or newParent is an ancestor of that container node.

DOMException.NO_MODIFICATION_ALLOWED_ERR

An ancestor of a boundary point of the range is read-only and does not allow insertions.

DOMException.WRONG_DOCUMENT_ERR

newParent and this range were created using different Document objects.

RangeException.BAD_BOUNDARYPOINTS_ERR

The range partially selects a node (other than a Text node), so the region of the document it represents cannot be surrounded.

RangeException.INVALID_NODE_TYPE_ERR

newParent is a Document, DocumentFragment, DocumentType, Attr, Entity, or Notation node.

Description

This method reparents the contents of this range to newParent and then inserts newParent into the document at the start position of the range. It is useful to place a region of document content within a <div> or <span> element, for example.

If newParent is already part of the document, it is first removed from the document, and any children it has are discarded. When this method returns, this range begins immediately before newParent and ends immediately after it.


Name

Range.toString( ): get range contents as a plain-text string — DOM Level 2 Range

Synopsis

String toString( );

Returns

The contents of this range as a string of plain text without any markup.


Name

RangeException: signals a range-specific exception — DOM Level 2 Range: Object → RangeException

Constants

The following constants define the legal values for the code property of a RangeException object. Note that these constants are static properties of RangeException, not properties of individual exception objects.

unsigned short BAD_BOUNDARYPOINTS_ERR = 1

The boundary points of a range are not legal for the requested operation.

unsigned short INVALID_NODE_TYPE_ERR = 2

An attempt was made to set the container node of a range boundary point to an invalid node or a node with an invalid ancestor.

Properties

unsigned short code

An error code that provides some detail about what caused the exception. The legal values (and their meanings) for this property are defined by the constants just listed.

Description

A RangeException is thrown by certain methods of the Range interface to signal a problem of some sort. Note that most exceptions thrown by Range methods are DOMException objects. A RangeException is generated only when none of the existing DOMException error constants is appropriate to describe the exception.


Name

Reset: see Input


Name

Screen: provides information about the display — JavaScript 1.2: Object → Screen

Synopsis

screen

Properties

availHeight

Specifies the available height, in pixels, of the screen on which the web browser is displayed. On operating systems such as Windows, this available height does not include vertical space allocated to semipermanent features, such as the task bar at the bottom of the screen.

availWidth

Specifies the available width, in pixels, of the screen on which the web browser is displayed. On operating systems such as Windows, this available width does not include horizontal space allocated to semipermanent features, such as application shortcut bars.

colorDepth

Specifies the color depth of the screen in bits per pixel.

height

Specifies the total height, in pixels, of the screen on which the web browser is displayed. See also availHeight.

width

Specifies the total width, in pixels, of the screen on which the web browser is displayed. See also availWidth.

Description

The screen property of every Window refers to a Screen object. The properties of this global object contain information about the screen on which the browser is displayed. JavaScript programs can use this information to optimize their output for the user's display capabilities. For example, a program can choose between large and small images based on the display size and between 8-bit and 16-bit color images based on the screen's color depth. A JavaScript program can also use the information about the size of the screen to center new browser windows on the screen.

See Also

The screen property of the Window object


Name

Select: a graphical selection list — DOM Level 2 HTML: Node → Element → HTMLElement → Select

Properties

readonly Form form

The <form> element that contains this <select> element.

readonly long length

The number of <option> elements contained by this <select> element. Same as options.length.

readonly HTMLCollection options

An array (HTMLCollection) of Option objects that represent the <option> elements contained in this <select> element, in the order in which they appear. See Select.options[] for further details.

long selectedIndex

The position of the selected option in the options array. If no options are selected, this property is −1. If multiple options are selected, this property holds the index of the first selected option.

Setting the value of this property selects the specified option and deselects all other options, even if the Select object has the multiple attribute specified. When you're doing listbox selection (when size > 1), you can deselect all options by setting selectedIndex to −1. Note that changing the selection in this way does not trigger the onchange( ) event handler.

readonly String type

If multiple is true, this property is "select-multiple"; otherwise, it is "select-one". This property exists for compatibilty with the type property of the Input object.

In addition to the properties above, Select objects also mirror HTML attributes with the following properties:

Property

Attribute

Description

boolean disabled

disabled

Whether the user element is disabled

boolean multiple

multiple

Whether more than one option may be selected

String name

name

Element name for form submission

long size

size

The number of options to display at once

long tabIndex

tabindex

Position of Select element in the tabbing order

Methods

add( )

Inserts a new Option object into the options array, either by appending it at the end of the array or by inserting it before another specified option.

blur( )

Takes keyboard focus away from this element.

focus( )

Transfers keyboard focus to this element.

remove( )

Removes the <option> element at the specified position.

Event Handlers

onchange

Invoked when the user selects or deselects an item.

HTML Syntax

A Select element is created with a standard HTML <select> tag. Options to appear within the Select element are created with the <option> tag:

<form>

       ...
<select
   name="name"  // A name that identifies this element; specifies name property
    [ size="integer" ]      // Number of visible options in Select element
    [ multiple ]            // Multiple options may be selected, if present
    [ onchange="handler" ]  // Invoked when the selection changes
>
<option value="value1" [selected]>option_label1
<option value="value2" [selected]>option_label2// Other options here

</select>
   ...
</form>

Description

The Select element represents an HTML <select> tag, which displays a graphical list of choices to the user. If the multiple attribute is present in the HTML definition of the element, the user may select any number of options from the list. If that attribute is not present, the user may select only one option, and options have a radio-button behavior—selecting one deselects whichever was previously selected.

The options in a Select element may be displayed in two distinct ways. If the size attribute has a value greater than 1, or if the multiple attribute is present, they are displayed in a list box that is size lines high in the browser window. If size is smaller than the number of options, the listbox includes a scrollbar so all the options are accessible. On the other hand, if size is specified as 1 and multiple is not specified, the currently selected option is displayed on a single line, and the list of other options is made available through a drop-down menu. The first presentation style displays the options clearly but requires more space in the browser window. The second style requires minimal space but does not display alternative options as explicitly.

The options[] property of the Select element is the most interesting. This is the array of Option objects that describe the choices presented by the Select element. The length property specifies the length of this array (as does options.length). See Option for details.

For a Select element without the multiple attribute specified, you can determine which option is selected with the selectedIndex property. When multiple selections are allowed, however, this property tells you the index of only the first selected option. To determine the full set of selected options, you must iterate through the options[] array and check the selected property of each Option object.

The options displayed by the Select element may be dynamically modified. Add a new option with the add( ) method and the Option( ) constructor; remove an option with the remove( ) method. Changes are also possible by direct manipulation of the options array.

See Also

Form, Option, Select.options[]; Chapter 18, Forms and Form Elements


Name

Select.add( ): insert an <option> element — DOM Level 2 HTML

Synopsis

void add(HTMLElementelement,
         HTMLElement before)
    throws DOMException;

Arguments

element

The Option element to be added.

before

The element of the options array before which the new element should be added. If this argument is null, element is appended at the end of the options array.

Throws

This method throws a DOMException with a code of NOT_FOUND_ERR if the before argument specifies an object that is not a member of the options array.

Description

This method adds a new <option> element to this <select> element. element is an Option object that represents the <option> element to be added. before specifies the Option before which element is to be added. If before is part of an <optgroup>, element is always inserted as part of that same group. If before is null, element becomes the last child of the <select> element.

See Also

Option


Name

Select.blur( ): take keyboard focus away from this element — DOM Level 2 HTML

Synopsis

void blur( );

Description

This method takes keyboard focus away from this element.


Name

Select.focus( ): give keyboard focus to this element — DOM Level 2 HTML

Synopsis

void focus( );

Description

This method transfers keyboard focus to this <select> element so the user can interact with it using the keyboard instead of the mouse.


Name

Select.onchange: event handler invoked when the selection changes — DOM Level 0

Synopsis

Function onchange

Description

The onchange property of a Select object refers to an event-handler function that is invoked when the user selects or deselects an option. The event does not specify what the new selected option or options are; you must consult the selectedIndex property of the Select object or the selected property of the various Option objects to determine this.

See Element.addEventListener( ) for another way to register event handlers.

See Also

Element.addEventListener( ), Option; Chapter 17, Events and Event Handling


Name

Select.options[]: the choices in a Select object — DOM Level 2 HTML

Synopsis

readonly HTMLCollection options

Description

The options[] property is an array-like HTMLCollection of Option objects. Each Option object describes one of the selection options presented within the Select object.

The options[] property is not an ordinary HTMLCollection. For backward compatibility with the earliest browsers, this collection has certain special behaviors that allow you to change the options displayed by the Select object:

  • If you set options.length to 0, all options in the Select object are cleared.

  • If you set options.length to a value less than the current value, the number of options in the Select object is decreased, and those at the end of the array disappear.

  • If you set an element in the options[] array to null, that option is removed from the Select object, and the elements above it in the array are moved down, changing their indices to occupy the new space in the array (see also Select.remove( )).

  • If you create a new Option object with the Option( ) constructor (see Option), you can add that option to the end of the options list in the Select object by appending it to the options[] array. To do this, set options[options.length] (see also Select.add( )).

See Also

Option


Name

Select.remove( ): remove an <option> — DOM Level 2 HTML

Synopsis

void remove(longindex);

Arguments

index

The position within the options array of the <option> element to be removed.

Description

This method removes the <option> element at the specified position in the options array. If the specified index is less than zero or greater than or equal to the number of options, the remove( ) method ignores it and does nothing.

See Also

Option


Name

Style: see CSS2Properties


Name

Submit: see Input


Name

Table: a <table> in an HTML document — DOM Level 2 HTML: Node → Element → HTMLElement → Table

Properties

HTMLElement caption

A reference to the <caption> element for the table, or null if there is none.

readonly HTMLCollection rows

An array (HTMLCollection) of TableRow objects that represent all the rows in the table. This includes all rows defined within <thead>, <tfoot>, and <tbody> tags.

readonly HTMLCollection tBodies

An array (HTMLCollection) of TableSection objects that represent all the <tbody> sections in this table.

TableSection tFoot

The <tfoot> element of the table, or null if there is none.

TableSection tHead

The <thead> element of the table, or null if there is none.

In addition to the properties just listed, this interface defines the properties in the following table to represent the HTML attributes of the <table> element:

Property

Attribute

Description

deprecated String align

align

Horizontal alignment of table in document

deprecated String bgColor

bgcolor

Table background color

String border

border

Width of border around table

String cellPadding

cellpadding

Space between cell contents and border

String cellSpacing

cellspacing

Space between cell borders

String frame

frame

Which table borders to draw

String rules

rules

Where to draw lines within the table

String summary

summary

Summary description of table

String width

width

Table width

Methods

createCaption( )

Returns the existing <caption> for the table, or creates (and inserts) a new one if none already exists.

createTFoot( )

Returns the existing <tfoot> element for the table, or creates (and inserts) a new one if none already exists.

createTHead( )

Returns the existing <thead> element for the table, or creates (and inserts) a new one if none already exists.

deleteCaption( )

Deletes the <caption> element from the table, if it has one.

deleteRow( )

Deletes the row at the specified position in the table.

deleteTFoot( )

Deletes the <tfoot> element from the table, if it has one.

deleteTHead( )

Deletes the <thead> element from the table, if it has one.

insertRow( )

Inserts a new, empty <tr> element into the table at the specified position.

Description

The Table object represents an HTML <table> element and defines a number of convenience properties and methods for querying and modifying various sections of the table. These methods and properties make it easier to work with tables, but their functionality can also be duplicated with core DOM methods.

See Also

TableCell, TableRow, TableSection


Name

Table.createCaption( ): get or create a <caption> — DOM Level 2 HTML

Synopsis

HTMLElement createCaption( );

Returns

An HTMLElement object representing the <caption> element for this table. If the table already has a caption, this method simply returns it. If the table does not have an existing <caption>, this method creates a new (empty) one and inserts it into the table before returning it.


Name

Table.createTFoot( ): get or create a <tfoot> — DOM Level 2 HTML

Synopsis

HTMLElement createTFoot( );

Returns

A TableSection representing the <tfoot> element for this table. If the table already has a footer, this method simply returns it. If the table does not have an existing footer, this method creates a new (empty) <tfoot> element and inserts it into the table before returning it.


Name

Table.createTHead( ): get or create a <thead> — DOM Level 2 HTML

Synopsis

HTMLElement createTHead( );

Returns

A TableSection representing the <thead> element for this table. If the table already has a header, this method simply returns it. If the table does not have an existing header, this method creates a new (empty) <thead> element and inserts it into the table before returning it.


Name

Table.deleteCaption( ): delete the <caption> of a table — DOM Level 2 HTML

Synopsis

void deleteCaption( );

Description

If this table has a <caption> element, this method removes it from the document tree. Otherwise, it does nothing.


Name

Table.deleteRow( ): delete a row of a table — DOM Level 2 HTML

Synopsis

void deleteRow(longindex)
    throws DOMException;

Arguments

index

Specifies the position within the table of the row to be deleted.

Throws

This method throws a DOMException with a code of INDEX_SIZE_ERR if index is less than zero or is greater than or equal to the number of rows in the table.

Description

This method deletes the row at the specified position from the table. Rows are numbered in the order in which they appear in the document source. Rows in <thead> and <tfoot> sections are numbered along with all other rows in the table.

See Also

TableSection.deleteRow( )


Name

Table.deleteTFoot( ): delete the <tfoot> of a table — DOM Level 2 HTML

Synopsis

void deleteTFoot( );

Description

If this table has a <tfoot> element, this method removes it from the document tree. If the table has no footer, this method does nothing.


Name

Table.deleteTHead( ): delete the <thead> of a table — DOM Level 2 HTML

Synopsis

void deleteTHead( );

Description

If this table has a <thead> element, this method deletes it; otherwise, it does nothing.


Name

Table.insertRow( ): add a new, empty row to the table — DOM Level 2 HTML

Synopsis

HTMLElement insertRow(longindex)
    throws DOMException;

Arguments

index

The position at which the new row is to be inserted.

Returns

A TableRow that represents the newly inserted row.

Throws

This method throws a DOMException with a code of INDEX_SIZE_ERR if index is less than zero or greater than the number of rows in the table.

Description

This method creates a new TableRow representing a <tr> tag and inserts it into the table at the specified position.

The new row is inserted in the same section and immediately before the existing row at the position specified by index. If index is equal to the number of rows in the table, the new row is appended to the last section of the table. If the table is initially empty, the new row is inserted into a new <tbody> section that is itself inserted into the table.

You can use the convenience method TableRow.insertCell( ) to add content to the newly created row.

See Also

TableSection.insertRow( )


Name

TableCell: cell in an HTML table — DOM Level 2 HTML: Node → Element → HTMLElement → TableCell

Properties

readonly long cellIndex

The position of this cell within its row.

In addition to the cellIndex property, this interface defines the following properties, which correspond directly to the HTML attributes of the <td> and <th> elements:

Property

Attribute

Description

String abbr

abbr

See HTML specification

String align

align

Horizontal alignment of cell

String axis

axis

See HTML specification

deprecated String bgColor

bgcolor

Background color of cell

String ch

char

Alignment character

String chOff

choff

Alignment character offset

long colSpan

colspan

Columns spanned by cell

String headers

headers

id values for headers for this cell

deprecated String height

height

Cell height in pixels

deprecated boolean noWrap

nowrap

Don't word-wrap cell

long rowSpan

rowspan

Rows spanned by cell

String scope

scope

Scope of this header cell

String vAlign

valign

Vertical alignment of cell

deprecated String width

width

Cell width in pixels

Description

This interface represents <td> and <th> elements in HTML tables.


Name

TableRow: a <tr> element in an HTML table — DOM Level 2 HTML: Node → Element → HTMLElement → TableRow

Properties

readonly HTMLCollection cells

An array (HTMLCollection) of TableCell objects representing the cells in this row.

readonly long rowIndex

The position of this row in the table.

readonly long sectionRowIndex

The position of this row within its section (i.e., within its <thead>, <tbody>, or <tfoot> element).

In addition to the properties just listed, this interface also defines the following properties, which correspond to the HTML attributes of the <tr> element:

Property

Attribute

Description

String align

align

Default horizontal alignment of cells in this row

deprecated String bgColor

bgcolor

Background color of this row

String ch

char

Alignment character for cells in this row

String chOff

choff

Alignment character offset for cells in this row

String vAlign

valign

Default vertical alignment for cells in this row

Methods

deleteCell( )

Deletes the specified cell from this row.

insertCell( )

Inserts an empty <td> element into this row at the specified position.

Description

This interface represents a row in an HTML table.


Name

TableRow.deleteCell( ): delete a cell in a table row — DOM Level 2 HTML

Synopsis

void deleteCell(longindex)
    throws DOMException;

Arguments

index

The position in the row of the cell to delete.

Throws

This method throws a DOMException with a code of INDEX_SIZE_ERR if index is less than zero or is greater than or equal to the number of cells in the row.

Description

This method deletes the cell at the specified position in the table row.


Name

TableRow.insertCell( ): insert a new, empty <td> element into a table row — DOM Level 2 HTML

Synopsis

HTMLElement insertCell(longindex)
    throws DOMException;

Arguments

index

The position at which the new cell is to be inserted.

Returns

An TableCell object that represents the newly created and inserted <td> element.

Throws

This method throws a DOMException with a code of INDEX_SIZE_ERR if index is less than zero or is greater than the number of cells in the row.

Description

This method creates a new <td> element and inserts it into the row at the specified position. The new cell is inserted immediately before the cell that is currently at the position specified by index. If index is equal to the number of cells in the row, the new cell is appended to the end of the row.

Note that this convenience method inserts <td> data cells only. If you need to add a header cell into a row, you must create and insert the <th> element using Document.createElement( ) and Node.insertBefore( ), or related methods.


Name

TableSection: a header, footer, or body section of a table — DOM Level 2 HTML: Node → Element → HTMLElement → TableSection

Properties

readonly HTMLCollection rows

An array (HTMLCollection) of TableRow objects representing the rows in this section of the table.

In addition to the rows property, this interface defines the following properties, which represent the attributes of the underlying HTML element:

Property

Attribute

Description

String align

align

Default horizontal alignment of cells in this section of the table

String ch

char

Default alignment character for cells in this section

String chOff

choff

Default alignment offset for cells in this section

String vAlign

valign

Default vertical alignment for cells in this section

Methods

deleteRow( )

Deletes the specified numbered row from this section.

insertRow( )

Inserts an empty row into this section at the specified position.

Description

This interface represents a <tbody>, <thead>, or <tfoot> section of an HTML table. The tHead and tFoot properties of a Table are TableSection objects, and the tBodies property is an array of TableSection objects.


Name

TableSection.deleteRow( ): delete a row within a table section — DOM Level 2 HTML

Synopsis

void deleteRow(longindex)
    throws DOMException;

Arguments

index

The position of the row within this section.

Throws

This method throws a DOMException with a code of INDEX_SIZE_ERR if index is less than zero or is greater than or equal to the number of rows in this section.

Description

This method deletes the row at the specified position within this section. Note that for this method, index specifies a row's position within its section, not within the entire table.

See Also

Table.deleteRow( )


Name

TableSection.insertRow( ): insert a new, empty row into this table section — DOM Level 2 HTML

Synopsis

HTMLElement insertRow(longindex)
    throws DOMException;

Arguments

index

The position within the section at which the new row is to be inserted.

Returns

A TableRow that represents the newly created and inserted <tr> element.

Throws

This method throws a DOMException with a code of INDEX_SIZE_ERR if index is less than zero or is greater than the number of rows in this section.

Description

This method creates a new empty <tr> element and inserts it into this table section at the specified position. If index equals the number of rows currently in the section, the new row is appended to the end of the section. Otherwise, the new row is inserted immediately before the row that is currently at the position specified by index. Note that for this method, index specifies a row position within a single table section, not within the entire table.

See Also

Table.insertRow( )


Name

Text: a run of text in an HTML or XML document — DOM Level 1 Core: Node → CharacterData → Text

Subinterfaces

CDATASection

Methods

splitText( )

Splits this Text node into two at the specified character position and returns the new Text node.

Description

A Text node represents a run of plain text in an HTML or XML document. Plain text appears within HTML and XML elements and attributes, and Text nodes typically appear as children of Element and Attr nodes. Text nodes inherit from CharacterData, and the textual content of a Text node is available through the data property inherited from CharacterData or through the nodeValue property inherited from Node. Text nodes may be manipulated using any of the methods inherited from CharacterData or with the splitText( ) method defined by the Text interface itself. Create a new Text node with Document.createTextNode( ). Text nodes never have children.

See Node.normalize( ) for a way to remove empty Text nodes and merge adjacent Text nodes from a subtree of a document.

See Also

CharacterData, Node.normalize( )


Name

Text.splitText( ): split a Text node in two — DOM Level 1 Core

Synopsis

Text splitText(unsigned longoffset)
    throws DOMException;

Arguments

offset

The character position at which to split the Text node.

Returns

The Text node that was split from this node.

Throws

This method may throw a DOMException with one of the following code values:

INDEX_SIZE_ERR

offset is negative or greater than the length of the Text or Comment node.

NO_MODIFICATION_ALLOWED_ERR

The node is read-only and may not be modified.

Description

This method splits a Text node in two at the specified offset. The original Text node is modified so that it contains all text content up to, but not including, the character at position offset. A new Text node is created to contain all the characters from (and including) the position offset to the end of the string. This new Text node is the return value of the method. Additionally, if the original Text node has a parentNode, the new node is inserted into this parent node immediately after the original node.

The CDATASection interface inherits from Text, and this splitText( ) method can also be used with CDATASection nodes, in which case the newly created node is a CDATASection rather than a Text node.

See Also

Node.normalize( )


Name

Textarea: a multiline text input area — DOM Level 2 HTML: Node → Element → HTMLElement → Textarea

Properties

String defaultValue

The initial content of the text area. When the form is reset, the text area is restored to this value. Setting this property changes the displayed text in the text area.

readonly Form form

The Form object that represents the <form> element containing this Textarea, or null if this element is not inside a form.

readonly String type

The type of this element, for compatibility with Input objects. This property always has the value "textarea".

String value

The text currently displayed in the text area. The initial value of this property is the same as the defaultValue property. When the user types into this element, the value property is updated to match the user's input. If you set the value property explicitly, the string you specify is displayed in the Textarea object. This value property contains the text that is sent to the server when the form is submitted.

In addition to these properties, Textarea objects also mirror HTML attributes with the following properties:

Property

Attribute

Description

String accessKey

accesskey

Keyboard shortcut character

long cols

cols

The width in character columns

boolean disabled

disabled

Whether the Textarea is disabled

String name

name

Textarea name for form submission and element access.

boolean readOnly

readonly

Whether the Textarea is noneditable

long rows

rows

Height of Textarea in lines

long tabIndex

tabindex

Position of Textarea in tabbing order

Methods

blur( )

Takes keyboard focus away from this element.

focus( )

Transfers keyboard focus to this element.

select( )

Selects the entire contents of the text area.

Event Handlers

onchange

Invoked when the user edits the text displayed in this element and then moves the keyboard focus elsewhere. This event handler is not invoked for every keystroke in the Textarea element but only when the user completes an edit.

HTML Syntax

A Textarea is created with standard HTML <textarea> and </textarea> tags:

<form>

    ...
  <textarea
    [ name="name" ]        // A name that can be used to refer to this element
    [ rows="integer" ]     // How many lines tall the element is
    [ cols="integer" ]     // How many characters wide the element is
    [ onchange="handler" ] // The onchange( ) event handler
  >
  plain_text             // The initial text; specifies defaultValue
</textarea>

...</form>

Description

A Textarea object represents an HTML <textarea> element that creates a multiline text input field (usually within an HTML form). The initial contents of the text area are specified between the <textarea> and </textarea> tags. You can query and set the text with the value property.

Textarea is a form input element like Input and Select. Like those objects, it defines form, name, and type properties.


Name

Textarea.blur( ): take keyboard focus away from this element — DOM Level 2 HTML

Synopsis

void blur( );

Description

This method takes keyboard focus away from this element.


Name

Textarea.focus( ): give keyboard focus to this element — DOM Level 2 HTML

Synopsis

void focus( );

Description

This method transfers keyboard focus to this element so the user can edit the displayed text without having to first click on the text area.


Name

Textarea.onchange: event handler invoked when input value changes — DOM Level 0

Synopsis

Function onchange

Description

The onchange property of a Textarea refers to an event-handler function that is invoked when the user changes the value in the text area and then "commits" those changes by moving the keyboard focus elsewhere.

Note that the onchange event handler is not invoked when the value property of a Text object is set by JavaScript. Also note that this handler is intended to process a complete change to the input value, and therefore it is not invoked on a keystroke-by-keystroke basis. See HTMLElement.onkeypress for information on receiving notification of every key press event and Element.addEventListener( ) for another way to register event handlers.

See Also

Element.addEventListener( ), HTMLElement.onkeypress, Input.onchange; Chapter 17, Events and Event Handling


Name

Textarea.select( ): select the text in this element — DOM Level 2 HTML

Synopsis

void select( );

Description

This method selects all the text displayed by this <textarea> element. In most browsers, this means that the text is highlighted and that new text entered by the user replaces the highlighted text instead of being appended to it.


Name

TextField: see Input


Name

UIEvent: details about user-interface events — DOM Level 2 Events: Event → UIEvent

Subinterfaces

KeyEvent, MouseEvent

Properties

readonly long detail

A numeric detail about the event. For click, mousedown, and mouseup events (see MouseEvent), this field is the click count: 1 for a single-click, 2 for a double-click, 3 for a triple-click, and so on. For DOMActivate events, this field is 1 for a normal activation or 2 for a "hyperactivation," such as a double-click or Shift-Enter combination.

readonly Window view

The window (the "view") in which the event was generated.

Methods

initUIEvent( )

Initializes the properties of a newly created UIEvent object, including the properties inherited from the Event interface.

Description

The UIEvent interface is a subinterface of Event and defines the type of Event object passed to events of type DOMFocusIn, DOMFocusOut, and DOMActivate. These event types are not commonly used in web browsers, and what is more important about the UIEvent interface is that it is the parent interface of MouseEvent.

See Also

Event, KeyEvent, MouseEvent; Chapter 17, Events and Event Handling


Name

UIEvent.initUIEvent( ): initialize the properties of a UIEvent object — DOM Level 2 Events

Synopsis

void initUIEvent(StringtypeArg,
                 boolean canBubbleArg,
                 boolean cancelableArg,
                 Window viewArg,
                 long detailArg);

Arguments

typeArg

The event type.

canBubbleArg

Whether the event will bubble.

cancelableArg

Whether the event may be canceled with preventDefault( ).

viewArg

The window in which the event occurred.

detailArg

The detail property for the event.

Description

This method initializes the view and detail properties of this UIEvent and also the type, bubbles, and cancelable properties inherited from the Event interface. This method may be called only on newly created UIEvent objects, before they have been passed to Element.dispatchEvent( ).

See Also

Document.createEvent( ), Event.initEvent( ), MouseEvent.initMouseEvent( )


Name

Window: a web browser window or frame — JavaScript 1.0: Object → Global → Window

Synopsis

self
windowwindow.frames[i]

Properties

The Window object defines the following properties and also inherits all the global properties of core JavaScript (see Global in Part III, “Core JavaScript Reference”):

closed

A read-only boolean value that specifies whether the window has been closed. When a browser window closes, the Window object that represents it does not simply disappear; it continues to exist, but its closed property is set to true.

defaultStatus

A read/write string that specifies the default message that appears in the status line. See Window.defaultStatus.

document

A read-only reference to the Document object that describes the document contained in this window or frame (see Document for details).

event [IE only]

In Internet Explorer, this property refers to the Event object that describes the most recent event. This property is used in the IE event model. In the standard DOM event model, the Event object is passed as an argument to event-handler functions. See Event and Chapter 17, Events and Event Handling for further details.

frames[]

An array of Window objects, one for each frame or <iframe> contained within this window. The frames.length property contains the number of elements in the frames[] array. Note that frames referenced by the frames[] array may themselves contain frames and may have a frames[] array of their own.

history

A read-only reference to the History object of this window or frame. See History for details.

innerHeight, innerWidth

Read-only properties that specify the height and width, in pixels, of the document display area of this window. These dimensions do not include the size of the menu bar, toolbars, scrollbars, and so on. These properties are not supported by IE and return values that include scrollbar size in Firefox. On those browsers use the clientWidth and clientHeight properties of document.documentElement. See the section called “Window Geometry” for details.

location

The Location object for this window or frame. This object specifies the URL of the currently loaded document. Setting this property to a new URL string causes the browser to load and display the contents of that URL. See Location for further details.

name

A string that contains the name of the window. The name is optionally specified when the window is created with the open( ) method or with the name attribute of a <frame> tag. The name of a window may be used as the value of a target attribute of an <a> or <form> tag. Using the target attribute in this way specifies that the hyperlinked document or the results of form submission should be displayed in the named window or frame.

navigator

A read-only reference to the Navigator object, which provides version and configuration information about the web browser. See Navigator for details.

opener

A read/write reference to the Window object that contained the script that called open( ) to open this browser window. This property is valid only for Window objects that represent top-level windows, not those that represent frames. The opener property is useful so that a newly created window can refer to properties and functions defined in the window that created it.

outerHeight, outerWidth

These read-only integers specify the total height and width, in pixels, of the browser window. These dimensions include the height and width of the menu bar, toolbars, scrollbars, window borders, and so on. These properties are not supported by IE, and IE offers no alternative properties.

pageXOffset, pageYOffset

Read-only integers that specify the number of pixels that the current document has been scrolled to the right (pageXOffset) and down (pageYOffset). These properties are not supported by Internet Explorer. In IE, use the scrollLeft and scrollTop properties of document.documentElement or document.body (depending on the version of IE). See the section called “Window Geometry” for details.

parent

A read-only reference to the Window object that contains this window or frame. If this window is a top-level window, parent refers to the window itself. If this window is a frame, the parent property refers to the window or frame that contains it.

screen

A read-only reference to a Screen object that specifies information about the screen: the number of available pixels and the number of available colors. See Screen for details.

screenLeft, screenTop, screenX, screenY

Read-only integers that specify the coordinates of the upper-left corner of the window on the screen. IE, Safari, and Opera support screenLeft and screenTop, while Firefox and Safari support screenX and screenY.

self

A read-only reference to this window itself. This is a synonym for the window property.

status

A read/write string that specifies the current contents of the browser's status line. See Window.status for details.

top

A read-only reference to the top-level window that contains this window. If this window is a top-level window itself, the top property simply contains a reference to the window itself. If this window is a frame, the top property refers to the top-level window that contains the frame. Contrast with the parent property.

window

The window property is identical to the self property; it contains a reference to this window.

Methods

The Window object defines the following methods, and also inherits all the global functions defined by core JavaScript (see Global in Part III, “Core JavaScript Reference”).

addEventListener( )

Adds an event-handler function to the set of event handlers for this window. This method is supported by all modern browsers except IE. See attachEvent( ) for IE.

alert( )

Displays a simple message in a dialog box.

attachEvent( )

Adds an event-handler function to the set of handlers for this window. This is the IE-specific alternative to addEventListener( ).

blur( )

Takes keyboard focus away from the top-level browser window.

clearInterval( )

Cancels periodic execution of code.

clearTimeout( )

Cancels a pending timeout operation.

close( )

Closes a window.

confirm( )

Asks a yes-or-no question with a dialog box.

detachEvent( )

Removes an event-handler function from this window. This is the IE-specific alternative to removeEventListener( ).

focus( )

Gives the top-level browser window keyboard focus; this brings the window to the front on most platforms.

getComputedStyle( )

Determines the CSS styles that apply to a document element.

moveBy( )

Moves the window by a relative amount.

moveTo( )

Moves the window to an absolute position.

open( )

Creates and opens a new window.

print( )

Simulates a click on the browser's Print button.

prompt( )

Asks for simple string input with a dialog box.

removeEventListener( )

Removes an event-handler function from the set of handlers for this window. This method is implemented by all modern browsers except IE. IE provides detachEvent( ) instead.

resizeBy( )

Resizes the window by a specified amount.

resizeTo( )

Resizes the window to a specified size.

scrollBy

Scrolls the window by a specified amount.

scrollTo( )

Scrolls the window to a specified position.

setInterval( )

Executes code at periodic intervals.

setTimeout( )

Executes code after a specified amount of time elapses.

Event Handlers

onblur

Invoked when the window loses focus.

onerror

Invoked when a JavaScript error occurs.

onfocus

Invoked when the window gains focus.

onload

Invoked when the document (or frameset) is fully loaded.

onresize

Invoked when the window is resized.

onunload

Invoked when the browser leaves the current document or frameset.

Description

The Window object represents a browser window or frame. It is documented in detail in Chapter 14, Scripting Browser Windows. In client-side JavaScript, the Window serves as the "global object," and all expressions are evaluated in the context of the current Window object. This means that no special syntax is required to refer to the current window, and you can use the properties of that window object as if they were global variables. For example, you can write document rather than window .document. Similarly, you can use the methods of the current window object as if they were functions: e.g., alert( ) instead of window .alert( ). In addition to the properties and methods listed here, the Window object also implements all the global properties and functions defined by core JavaScript. See Global in Part III, “Core JavaScript Reference” for details.

The Window object has window and self properties that refer to the window object itself. You can use these to make the current window reference explicit rather than implicit. In addition to these two properties, the parent and top properties and the frames[] array refer to other Window objects related to the current one.

To refer to a frame within a window, use:

frames[i]       // Frames of current window
self.frames[i]  // Frames of current window

w.frames[i]     // Frames of specified window w

To refer to the parent window (or frame) of a frame, use:

parent          // Parent of current window
self.parent     // Parent of current windoww.parent        // Parent of specified window w

To refer to the top-level browser window from any frame contained (or nested multiple levels deep) within it, use:

top             // Top window of current frame
self.top        // Top window of current framef.top           // Top window of specified frame f

New top-level browser windows are created with the Window.open( ) method. When you call this method, save the return value of the open( ) call in a variable and use that variable to reference the new window. The opener property of the new window is a reference back to the window that opened it.

In general, the methods of the Window object manipulate the browser window or frame in some way. The alert( ), confirm( ), and prompt( ) methods are notable: they interact with the user through simple dialog boxes.

See Chapter 14, Scripting Browser Windows for an in-depth overview of the Window object, and see the individual reference pages for complete details on Window methods and event handlers.


Name

Window.addEventListener( ): see Element.addEventListener( )


Name

Window.alert( ): display a message in a dialog box — JavaScript 1.0:

Synopsis

window.alert(message)

Arguments

message

The plain-text (not HTML) string to display in a dialog box popped up over window.

Description

The alert( ) method displays the specified message to the user in a dialog box. The dialog box contains an OK button the user can click to dismiss it. The dialog box is typically modal, and the call to alert( ) typically blocks until the dialog is dismissed.

Usage

Perhaps the most common use of the alert( ) method is to display error messages when the user's input to some form element is invalid in some way. The alert dialog box can inform the user of the problem and explain what needs to be corrected to avoid the problem in the future.

The appearance of the alert( ) dialog box is platform-dependent, but it generally contains graphics that indicate an error, warning, or alert message of some kind. While alert( ) can display any desired message, the alert graphics of the dialog box mean that this method is not appropriate for simple informational messages like "Welcome to my blog" or "You are the 177th visitor this week!"

Note that the message displayed in the dialog box is a string of plain text, not formatted HTML. You can use the newline character "\n" in your strings to break your message across multiple lines. You can also do some rudimentary formatting using spaces and can approximate horizontal rules with underscore characters, but the results depend greatly on the font used in the dialog box and thus are system-dependent.

See Also

Window.confirm( ), Window.prompt( )


Name

Window.attachEvent( ): see Element.attachEvent( )


Name

Window.blur( ): remove keyboard focus from a top-level window — JavaScript 1.1:

Synopsis

window.blur( )

Description

The blur( ) method removes keyboard focus from the top-level browser window specified by the Window object. It is unspecified which window gains keyboard focus as a result. In some browsers and/or platforms, this method may have no effect.

See Also

Window.focus( )


Name

Window.clearInterval( ): stop periodically executing code — JavaScript 1.2:

Synopsis

window.clearInterval(intervalId)

Arguments

intervalId

The value returned by the corresponding call to setInterval( ).

Description

clearInterval( ) stops the repeated execution of code that was started by a call to setInterval( ). intervalId must be the value that was returned by a call to setInterval( ).

See Also

Window.setInterval( )


Name

Window.clearTimeout( ): cancel deferred execution — JavaScript 1.0:

Synopsis

window.clearTimeout(timeoutId)

Arguments

timeoutId

A value returned by setTimeout( ) that identifies the timeout to be canceled.

Description

clearTimeout( ) cancels the execution of code that has been deferred with the setTimeout( ) method. The timeoutId argument is a value returned by the call to setTimeout( ) and identifies which deferred code to cancel.

See Also

Window.setTimeout( )


Name

Window.close( ): close a browser window — JavaScript 1.0:

Synopsis

window.close( )

Description

The close( ) method closes the top-level browser window specified by window. A window can close itself by calling self.close( ) or simply close( ). Only windows opened by JavaScript can be closed by JavaScript. This prevents malicious scripts from causing the user's browser to exit.

See Also

Window.open( ), the closed and opener properties of Window


Name

Window.confirm( ): ask a yes-or-no question — JavaScript 1.0:

Synopsis

window.confirm(question)

Arguments

question

The plain-text (not HTML) string to be displayed in the dialog box. It should generally express a question you want the user to answer.

Returns

true if the user clicks the OK button; false if the user clicks the Cancel button.

Description

The confirm( ) method displays the specified question in a dialog box. The dialog box contains OK and Cancel buttons that the user can use to answer the question. If the user clicks the OK button, confirm( ) returns true. If the user clicks Cancel, confirm( ) returns false.

The dialog box that is displayed by the confirm( ) method is modal. That is, it blocks all user input to the main browser window until the user dismisses the dialog box by clicking on the OK or Cancel buttons. Since this method returns a value depending on the user's response to the dialog box, JavaScript execution pauses in the call to confirm( ), and subsequent statements are not executed until the user responds to the dialog box.

There is no way to change the labels that appear in the buttons of the dialog box (to make them read Yes and No, for example). Therefore, you should take care to phrase your question or message so that OK and Cancel are suitable responses.

See Also

Window.alert( ), Window.prompt( )


Name

Window.defaultStatus: the default status line text — JavaScript 1.0:

Synopsis

window.defaultStatus

Description

defaultStatus is a read/write string property that specifies the default text that appears in the window's status line. Web browsers typically use the status line to display the browser's progress while loading a file and to display the destination of hypertext links that the mouse is over. While it is not displaying any of these transient messages, the status line is, by default, blank. However, you can set the defaultStatus property to specify a default message to be displayed when the status line is not otherwise in use, and you can read the defaultStatus property to determine what the default message is. The text you specify may be temporarily overwritten with other messages, such as those that are displayed when the user moves the mouse over a hypertext link, but the defaultStatus message is always redisplayed when the transient message is erased.

The defaultStatus property has been disabled in some modern browsers. See Window.status for details.

See Also

Window.status


Name

Window.detachEvent( ): see Element.detachEvent( )


Name

Window.focus( ): give keyboard focus to a window — JavaScript 1.1:

Synopsis

window.focus( )

Description

The focus( ) method gives keyboard focus to the browser window specified by the Window object.

On most platforms, a top-level window is brought forward to the top of the window stack so that it becomes visible when it is given focus.

See Also

Window.blur( )


Name

Window.getComputedStyle( ): retrieve the CSS styles used to render an element — DOM Level 2 CSS:

Synopsis

CSS2Properties getComputedStyle(Elementelt,
                                String pseudoElt);

Arguments

elt

The document element whose style information is desired.

pseudoElt

The CSS pseudoelement string, such as ":before" or ":first-line", or null if there is none.

Returns

A read-only CSS2Properties object that represents the style attributes and values used to render the specified element in this window. Any length values queried from this object are always expressed as pixel or absolute values, not relative or percentage values.

Description

An element in a document may obtain style information from an inline style attribute and from any number of style sheets in the stylesheet "cascade." Before the element can actually be displayed in a view, its style information must be extracted from the cascade, and styles specified with relative units (such as percentages or "ems") must be "computed" to convert to absolute units.

This method returns a read-only CSS2Properties object that represents those cascaded and computed styles. The DOM specification requires that any styles representing lengths use absolute units such as inches or millimeters. In practice, pixel values are commonly returned instead, although there is no guarantee that an implementation will always do this.

Contrast getComputedStyle( ) with the style property of an HTMLElement, which gives you access only to the inline styles of an element, in whatever units they were specified, and tells you nothing about stylesheet styles that apply to the element.

In Internet Explorer, similar functionality is available through the nonstandard currentStyle property of each HTMLElement object.

See Also

CSS2Properties, HTMLElement


Name

Window.moveBy( ): move a window to a relative position — JavaScript 1.2:

Synopsis

window.moveBy(dx, dy)

Arguments

dx

The number of pixels to move the window to the right.

dy

The number of pixels to move the window down.

Description

moveBy( ) moves the window to the relative position specified by dx and dy. See the security and usability considerations described under Window.moveTo( ).


Name

Window.moveTo( ): move a window to an absolute position — JavaScript 1.2:

Synopsis

window.moveTo(x, y)

Arguments

x

The X coordinate of the new window position.

y

The Y coordinate of the new window position.

Description

moveTo( ) moves the window so its upper-left corner is at the position specified by x and y. For security resasons, browsers may restrict this method so it cannot move a window offscreen. It is usually a bad idea to move a user's browser window unless he explicitly request it. Scripts should typically use this method only on windows that they created themselves with Window.open( ).


Name

Window.onblur: event handler invoked when the window loses keyboard focus — JavaScript 1.1:

Synopsis

Function onblur

Description

The onblur property of a Window specifies an event-handler function that is invoked when the window loses keyboard focus.

The initial value of this property is a function that contains the semicolon-separated JavaScript statements specified by the onblur attribute of the <body> or <frameset> tags.

Usage

If your web page has animation or other dynamic effects, you can use the onblur event handler to stop the animation when the window doesn't have the input focus. In theory, if the window doesn't have the focus, the user probably can't see it or isn't paying attention to it.

See Also

Window.blur( ), Window.focus( ), Window.onfocus; Chapter 17, Events and Event Handling


Name

Window.onerror: error handler invoked when a JavaScript error occurs — JavaScript 1.1:

Synopsis

You register an onerror handler like this:

window.onerror=handler-func

The browser invokes the handler like this:

window.onerror(message, url, line)

Arguments

message

A string that specifies the error message for the error that occurred.

url

A string that specifies the URL of the document in which the error occurred.

line

A number that specifies the line number at which the error occurred.

Returns

true if the handler has handled the error and JavaScript should take no further action; false if JavaScript should post the default error message dialog box for this error.

Description

The onerror property of the Window object specifies an error-handler function that is invoked when a JavaScript error occurs and is not caught with a catch statement. You can customize error handling by providing your own onerror error handler.

You define an onerror handler for a window by setting the onerror property of a Window object to an appropriate function. Note that onerror is an error handler and differs from event handlers. In particular, an error handler cannot be defined with an onerror attribute on the <body> tag.

When the onerror handler is invoked, it is passed three arguments: a string specifying the error message, a string specifying the URL of the document in which the error occurred, and a number that specifies the line number at which the error occurred. An error handling function may do anything it wants with these arguments: it may display its own error dialog box or log the error in some way, for example. When the error-handling function is done, it should return true if it has completely handled the error and wants the browser to take no further action, or false if it has merely noted or logged the error in some fashion and still wants the browser to handle the error.


Name

Window.onfocus: event handler invoked when a window is given focus — JavaScript 1.1:

Synopsis

Function onfocus

Description

The onfocus property of a Window specifies an event-handler function that is invoked when the window is given keyboard focus.

The initial value of this property is a function that contains the semicolon-separated JavaScript statements specified by the onfocus attribute of the <body> or <frameset> tags.

Usage

If your web page has animation or other dynamic effects, you might use the onfocus event handler to start the animation and the onblur handler to stop it, so it runs only when the user is paying attention to the window.

See Also

Window.blur( ), Window.focus( ), Window.onblur; Chapter 17, Events and Event Handling


Name

Window.onload: event handler invoked when a document finishes loading — JavaScript 1.0:

Synopsis

Function onload

Description

The onload property of a Window specifies an event handler function that is invoked when a document or frameset is completely loaded into its window or frame.

The initial value of this property is a function that contains the semicolon-separated JavaScript statements specified by the onload attribute of the <body> or <frameset> tags.

When the onload event handler is invoked, you can be certain that the document has fully loaded, and therefore that all scripts within the document have executed, all functions within scripts are defined, and all document elements have been parsed and are available through the Document object.

You can use Window.addEventListener( ) or Window.attachEvent( ) to register multiple event-handler functions for onload events.


Name

Window.onresize: event handler invoked when a window is resized — JavaScript 1.2:

Synopsis

Function onresize

Description

The onresize property of the Window object specifies an event-handler function that is invoked when the user changes the size of the window or frame.

The initial value of this property is a function that contains the JavaScript statements specified by the onresize attribute of the HTML <body> or <frameset> tag that defined the window.


Name

Window.onunload: the handler invoked when the browser leaves a page — DOM Level 0:

Synopsis

Function onunload

Description

The onunload property of a Window specifies an event-handler function that is invoked when the browser "unloads" a document in preparation for loading a new one.

The initial value of this property is a function that contains the semicolon-separated JavaScript statements specified by the onunload attribute of the <body> or <frameset> tags.

The onunload event handler enables you to perform any necessary cleanup of the browser state before a new document is loaded.

The onunload( ) handler is invoked when the user has instructed the browser to leave the current page and move somewhere else. Therefore, it is usually inappropriate to delay the loading of the desired new page by popping up dialog boxes (with Window.confirm( ) or Window.prompt( ), for example) from an onunload event handler.


Name

Window.open( ): open a new browser window or locate a named window — JavaScript 1.0:

Synopsis

window.open(url, name, features, replace)

Arguments

url

An optional string that specifies the URL to be displayed in the new window. If this argument is omitted, or if the empty string is specified, the new window does not display a document.

name

An optional string of alphanumeric and underscore characters that specifies a name for the new window. This name can be used as the value of the target attribute of <a> and <form> HTML tags. If this argument names a window that already exists, the open( ) method does not create a new window, but simply returns a reference to the named window. In this case, the features argument is ignored.

features

A string that specifies which features of a standard browser window are to appear in the new window. The format of this string is specified in the Window Features section. This argument is optional; if it is not specified, the new window has all the standard features.

replace

An optional boolean argument that specifies whether the URL loaded into the window should create a new entry in the window's browsing history or replace the current entry in the browsing history. If this argument is true, no new history entry is created. Note that this argument is intended for use when changing the contents of an existing named window.

Returns

A reference to a Window object, which may be a newly created or an already existing one, depending on the name argument.

Description

The open( ) method looks up an existing window or opens a new browser window. If the name argument specifies the name of an existing window, a reference to that window is returned. The returned window displays the URL specified by url, but the features argument is ignored. This is the only way in JavaScript to obtain a reference to a window that is known only by name.

If the name argument is not specified, or if no window with that name already exists, the open( ) method creates a new browser window. The created window displays the URL specified by url and has the name specified by name and the size and controls specified by features (the format of this argument is described in the next section). If url is the empty string, open( ) opens an empty window.

The name argument specifies a name for the new window. This name may contain only alphanumeric characters and the underscore character. It may be used as the value of the target attribute of an <a> or <form> tag in HTML to force documents to be displayed in the window.

When you use Window.open( ) to load a new document into an existing named window, you can pass the replace argument to specify whether the new document has its own entry in the window's browsing history or whether it replaces the history entry of the current document. If replace is true, the new document replaces the old. If this argument is false or is not specified, the new document has its own entry in the Window's browsing history. This argument provides functionality much like that of the Location.replace( ) method.

Don't confuse Window.open( ) with Document.open( ); the two methods perform very different functions. For clarity in your code, you may want to use Window.open( ) instead of open( ). In event handlers defined as HTML attributes, open( ) is usually interpreted as Document.open( ), so in this case, you must use Window.open( ).

Window Features

The features argument is a comma-separated list of features that appears in the window. If this optional argument is empty or not specified, all features are present in the window. On the other hand, if features specifies any one feature, any features that do not appear in the list do not appear in the window. The string should not contain any spaces or other whitespace. Each element in the list has the format:

feature[=value]

For most features, the value is yes or no. For these features, the equals sign and the value may be omitted; if the feature appears, yes is assumed, and if it doesn't, no is assumed. For the width and height features, value is required and must specify a size in pixels.

Here are the commonly supported features and their meanings:

height

Specifies the height, in pixels, of the window's document display area.

left

The X coordinate, in pixels, of the window.

location

The input field for entering URLs directly into the browser.

menubar

The menu bar.

resizable

If this feature is not present or is set to no, the window does not have resize handles around its border. (Depending on the platform, the user may still have ways to resize the window.) Note that a common bug is to misspell this feature as "resizeable," with an extra "e."

scrollbars

Enables horizontal and vertical scrollbars when they are necessary.

status

The status line.

toolbar

The browser toolbar, with Back and Forward buttons, etc.

top

The Y coordinate, in pixels, of the window.

width

Specifies the width, in pixels, of the window's document display area.

See Also

Location.replace( ), Window.close( ), the closed and opener properties of Window


Name

Window.print( ): print the document — JavaScript 1.5:

Synopsis

window.print( )

Description

Calling print( ) causes the browser to behave as if the user had clicked the browser's Print button. Usually, this brings up a dialog box that enables the user to cancel or customize the print request.


Name

Window.prompt( ): get user input with a dialog box — JavaScript 1.0:

Synopsis

window.prompt(message, default)

Arguments

message

The plain-text (not HTML) string to be displayed in the dialog box. It should ask the user to enter the information you want.

default

A string that is displayed as the default input in the dialog box. Pass the empty string ("") to make prompt( ) display an empty input box.

Returns

The string entered by the user, the empty string if the user did not enter a string, or null if the user clicked Cancel.

Description

The prompt( ) method displays the specified message in a dialog box that also contains a text input field and OK and Cancel buttons. Platform-dependent graphics in the dialog box help indicate to the user that her input is desired.

If the user clicks the Cancel button, prompt( ) returns null. If the user clicks the OK button, prompt( ) returns the text currently displayed in the input field.

The dialog box that is displayed by the prompt( ) method is modal. That is, it blocks all user input to the main browser window until the user dismisses the dialog box by clicking on the OK or Cancel buttons. Since this method returns a value depending on the user's response to the dialog box, JavaScript execution pauses in the call to prompt( ), and subsequent statements are not executed until the user responds to the dialog box.

See Also

Window.alert( ), Window.confirm( )


Name

Window.removeEventListener( ): see Element.removeEventListener( )


Name

Window.resizeBy( ): resize a window by a relative amount — JavaScript 1.2:

Synopsis

window.resizeBy(dw, dh)

Arguments

dw

The number of pixels by which to increase the width of the window.

dh

The number of pixels by which to increase the height of the window.

Description

resizeBy( ) resizes window by the relative amounts specified by dh and dw. See the security and usability considerations discussed under Window.resizeTo( ).


Name

Window.resizeTo( ): resize a window — JavaScript 1.2:

Synopsis

window.resizeTo(width, height)

Arguments

width

The desired width for the window.

height

The desired height for the window.

Description

resizeTo( ) resizes window so it is width pixels wide and height pixels high. For security reasons, the browser may restrict this method to prevent scripts from making windows very small. For usability reasons, it is almost always a bad idea to change the size of a user's window. If a script created a window, the script can resize it, but it is bad form for a script to resize the window that it is loaded into.


Name

Window.scrollBy( ): scroll the document by a relative amount — JavaScript 1.2:

Synopsis

window.scrollBy(dx, dy)

Arguments

dx

The number of pixels by which to scroll the document to the right.

dy

The number of pixels by which to scroll the document down.

Description

scrollBy( ) scrolls the document displayed in window by the relative amounts specified by dx and dy.


Name

Window.scrollTo( ): scroll the document — JavaScript 1.2:

Synopsis

window.scrollTo(x, y)

Arguments

x

The document X coordinate that is to appear at the left edge of the window's document display area.

y

The document Y coordinate that is to appear at the top of the window's document display area.

Description

scrollTo( ) scrolls the document displayed within window so the point in the document specified by the x and y coordinates is displayed in the upper-left corner, if possible.


Name

Window.setInterval( ): periodically execute specified code — JavaScript 1.2:

Synopsis

window.setInterval(code, interval)

Arguments

code

A function to be periodically invoked or a string of JavaScript code to be periodically evaluated. If this string contains multiple statements, they must be separated from each other by semicolons. In IE 4 (but not later versions), this argument must be a string.

interval

The interval, in milliseconds, between invocations or evaluations of code.

Returns

A value that can be passed to Window.clearInterval( ) to cancel the periodic execution of code.

Description

setInterval( ) repeatedly invokes or evaluates the function or string specified by code, at intervals of interval milliseconds.

setInterval( ) returns a value that can later be passed to Window.clearInterval( ) to cancel the execution of code.

setInterval( ) is related to setTimeout( ). Use setTimeout( ) when you want to defer the execution of code but do not want it to be repeatedly executed. See Window.setTimeout( ) for a discussion of the execution context of code.

See Also

Window.clearInterval( ), Window.setTimeout( )


Name

Window.setTimeout( ): defer execution of code — JavaScript 1.0:

Synopsis

window.setTimeout(code, delay)

Arguments

code

A function to be invoked, or a string of JavaScript code to be evaluated after the delay has elapsed. If this argument is a string, multiple statements must be separated from each other with semicolons. In IE 4, this argument must be a string; the function form of the method is not supported in that browser.

delay

The amount of time, in milliseconds, before the code should be executed.

Returns

An opaque value ("timeout id") that can be passed to the clearTimeout( ) method to cancel the execution of code.

Description

The setTimeout( ) method defers the invocation of a JavaScript function or the evaluation of a string of JavaScript code for delay milliseconds. Note that setTimeout( ) executes code only once. If you want multiple invocations, use setInterval( ) or have the code itself call setTimeout( ) again.

When code is executed, it is executed in the context of the Window object. If code is a function, the Window object is the value of the this keyword. If code is a string, it is evaluated in the global scope with the Window object as the only object on the scope chain. This is true even if the call to setTimeout( ) occurred within a function with a longer scope chain.

See Also

Window.clearTimeout( ), Window.setInterval( )


Name

Window.status: specify a transient status-line message — JavaScript 1.0:

Synopsis

String status

Description

status is a read/write string property that specifies a transient message to appear in the window's status line. The message generally appears only for a limited amount of time, until it is overwritten by another message or until the user moves the mouse to some other area of the window, for example. When a message specified with status is erased, the status line returns to its default blank state or to the default message specified by the defaultStatus property.

At the time of this writing, many browsers have disabled scripting of their status lines. This is a security measure to protect against phishing attacks that hide the true destination of hyperlinks.

See Also

Window.defaultStatus


Name

XMLHttpRequest: An HTTP request and response — Firefox 1.0, Internet Explorer 5.0, Safari 1.2, Opera 7.60: Object → XMLHttpRequest

Constructor

new XMLHttpRequest( )                     // All browsers except IE 5 and IE 6
new ActiveXObject("Msxml2.XMLHTTP")      // IE
new ActiveXObject("Microsoft.XMLHTTP")   // IE with older system libraries

Properties

readonly short readyState

The state of the HTTP request. The value of this property begins at 0 when an XMLHttpRequest is first created and increases to 4 when the complete HTTP response has been received. Each of the five states has an informal name associated with it, and the table below lists the states, their names, and their meanings:

State

Name

Description

0

Uninitialized

This is the initial state. The XMLHttpRequest object has just been created or has been reset with the abort( ) method.

1

Open

The open( ) method has been called, but send( ) has not. The request has not yet been sent.

2

Sent

The send( ) method has been called, and the HTTP request has been transmitted to the web server. No response has been received yet.

3

Receiving

All response headers have been received. The response body is being received but is not complete.

4

Loaded

The HTTP response has been fully received.

The value of readyState never decreases, unless abort( ) or open( ) are called on a request that is already in progress. Every time the value of this property increases, the onreadystatechange event handler is triggered.

readonly String responseText

The body of the response (not including headers) that has been received from the server so far, or the empty string if no data has been received yet. If readyState is less than 3, this property is the empty string. When readyState is 3, this property returns whatever portion of the response has been received so far. If readyState is 4, this property holds the complete body of the response.

If the response includes headers that specify a character encoding for the body, that encoding is used. Otherwise, the Unicode UTF-8 encoding is assumed.

readonly Document responseXML

The response to the request, parsed as XML and returned as a Document object. This property will be null unless all three of the following conditions are true:

  • readyState is 4.

  • The response includes a Content-Type header of "text/xml", "application/xml", or anything ending with "+xml" to indicate that the response is an XML document.

  • The response body consists of well-formed XML markup that can be parsed without errors.

readonly short status

The HTTP status code returned by the server, such as 200 for success and 404 for "Not Found" errors. Reading this property when readyState is less than 3 causes an exception.

readonly String statusText

This property specifies the HTTP status code of the request by name rather than by number. That is, it is "OK" when status is 200 and "Not Found" when status is 404. As with the status property, reading this property when readyState is less than 3 causes an exception.

Methods

abort( )

Cancels the current request, closing connections and stopping any pending network activity.

getAllResponseHeaders( )

Returns the HTTP response headers as an unparsed string.

getResponseHeader( )

Returns the value of a named HTTP response header

open( )

Initializes HTTP request parameters, such as the URL and HTTP method, but does not send the request.

send( )

Sends the HTTP request, using parameters passed to the open( ) method and an optional request body passed to this method.

setRequestHeader( )

Sets or adds an HTTP request header to an open but unsent request.

Event Handlers

onreadystatechange

Event-handler function invoked each time the readyState property changes. It may also be invoked multiple times while readyState is 3.

Description

The XMLHttpRequest object allows client-side JavaScript to issue HTTP requests and receive responses (which need not be XML) from web servers. XMLHttpRequest is the subject of Chapter 20, Scripting HTTP, and that chapter contains many examples of its use.

XMLHttpRequest is quite portable and well supported by all modern browsers. The only browser dependency involves the creation of an XMLHttpRequest object. In Internet Explorer 5 and 6, you must use the IE-specific ActiveXObject( ) constructor, as shown in the Constructor section earlier.

Once an XMLHttpRequest object has been created, you typically use it like this:

  1. Call open( ) to specify the URL and method (usually "GET" or "POST") for the request. When you call open( ), you also specify whether you want the request to be synchronous or asynchronous.

  2. If you specified an asynchronous request, set the onreadystatechange property to the function that will be notified of the progress of the request.

  3. Call setRequestHeader( ), if needed, to specify additional request parameters.

  4. Call send( ) to send the request to the web server. If it is a POST request, you may also pass a request body to this method. If you specify a synchronous request in your call to open( ), the send( ) method blocks until the response is complete and readyState is 4. Otherwise, your onreadystatechange event-handler function must wait until the readyState property reaches 4 (or at least 3).

  5. Once send( ) has returned for synchronous requests, or readyState has reached 4 for asynchronous requests, you can use the server's response. First, check the status code to ensure that the request was successful. If so, use getResponseHeader( ) or getResponseHeaders( ) to retrieve values from the response header, and use the responseText or responseXML properties to obtain the response body.

The XMLHttpRequest object has not been standardized, but work on a standard has begun at the W3C at the time of this writing. This documentation is based on working drafts of the standard. Current XMLHttpRequest implementations are quite interoperable but differ in minor ways from the standard. An implementation might return null where the standard requires the empty string, for example, or might set readyState to 3 without guaranteeing that all response headers are available.


Name

XMLHttpRequest.abort( ): cancel an HTTP request

Synopsis

void abort( )

Description

This method resets the XMLHttpRequest object to a readyState of 0 and aborts any pending network activity. You might call this method, for example, if a request has taken too long, and the response is no longer necessary.


Name

XMLHttpRequest.getAllResponseHeaders( ): return unparsed HTTP response headers

Synopsis

String getAllResponseHeaders( )

Returns

If readyState is less than 3, this method returns null. Otherwise, it returns all HTTP response headers (but not the status line) sent by the server. The headers are returned as a single string, with one header per line. Lines are delimited by "\r\n" line terminators.


Name

XMLHttpRequest.getResponseHeader( ): get the value of a named HTTP response header

Synopsis

String getResponseHeader(Stringheader)

Arguments

header

The name of the HTTP response header whose value is to be returned. You may specify this header name using any case: the comparison to response headers is case-insensitive.

Returns

The value of the named HTTP response header, or the empty string if no such header was received or if readyState is less than 3. If more than one header with the specified name is received, the values of those headers are concatenated and returned, using a comma and space as the delimiter.


Name

XMLHttpRequest.onreadystatechange: event handler function invoked when readyState changes

Synopsis

Function onreadystatechange

Description

This property specifies an event-handler function that is invoked each time the readyState property changes. It may also be invoked (but this is not required) multiple times while readyState is 3 to provide notification of download progress.

An onreadystatechange handler typically checks the readyState of the XMLHttpRequest object to see if it has reached 4. If so, it does something with the responseText or responseXML properties.

It is unspecified whether any arguments will be passed to the function. In particular, there is no standard way for the event-handler function to get a reference to the XMLHttpRequest object it is registered on. This means that it is not possible to write a generic handler function that can be used for multiple requests.

The XMLHttpRequest object is supposed to follow the DOM event model and implement an addEventListener( ) method for registering handlers for readystatechange events. (See Event.addEventListener( ), for example.) Since IE does not support the DOM event model, and since it is rare to require more than one event handler per request, it is safer to simply assign a single handler function to onreadystatechange.


Name

XMLHttpRequest.open( ): initialize HTTP request parameters

Synopsis

void open(Stringmethod,
          String url,
          boolean async,
          String username, String password)

Arguments

method

The HTTP method to be used for the request. Reliably implemented values include GET, POST, and HEAD. Implementations may also support methods as well.

url

The URL that is the subject of the request. Most browsers impose a same-origin security policy (see the section called “The Same-Origin Policy”) and require that this URL have the same hostname and port as the document that contains the script. Relative URLs are resolved in the normal way, using the URL of the document that contains the script.

async

Whether the request should be performed asynchronously or not. If this argument is false, the request is synchronous, and a subsequent call to send( ) will block until the response is fully received. If this argument is true or is omitted, the request is asynchronous, and an onreadystatechange event handler is typically required.

username, password

These optional arguments specify authorization credentials for use with URLs that require authorization. If specified, they override any credentials specified in the URL itself.

Description

This method initializes request parameters for later use by the send( ) method. It sets readyState to 1; deletes any previously specified request headers and previously received response headers; and sets the responseText, responseXML, status, and statusText properties to their default values. It is safe to call this method when readyState is 0 (when the XMLHttpRequest object is just created, or after a call to abort( )) and when readyState is 4 (after a response has been received). The behavior of open( ) is unspecified when it is called from any other state.

Other than storing request parameters for use by send( ) and resetting the XMLHttpRequest object for reuse, the open( ) method has no other behavior. In particular, note that implementations do not typically open a network connection to the web server when this method is called.

See Also

XMLHttpRequest.send( ); Chapter 20, Scripting HTTP


Name

XMLHttpRequest.send( ): send an HTTP request

Synopsis

void send(Objectbody)

Arguments

body

If the HTTP method specified by the call to open( ) is "POST" or "PUT", this argument specifies the body of the request, as a string or Document object, or null if no body is necessary. For any other method, this argument is unused and should be null. (Some implementations do not allow you to omit this argument.)

Description

This method causes an HTTP request to be issued. If there has been no previous call to open( ), or, more generally, if readyState is not 1, send( ) throws an exception. Otherwise, it issues an HTTP request that consists of:

  • The HTTP method, URL, and authorization credentials (if any) specified in the previous call to open( )

  • The request headers, if any, specified by previous calls to setRequestHeader( )

  • The body argument passed to this method

Once the request has been issued, send( ) sets readyState to 2 and triggers the onreadystatechange event handler.

If the async argument to the previous call to open( ) was false, this method blocks and does not return until readyState is 4 and the server's response has been fully received. Otherwise, if the async argument is true or if that argument is omitted, send( ) returns immediately, and the server's response is processed, as described next, on a background thread.

If the server responds with an HTTP redirect, the send( ) method or the background thread follow the redirect automatically. When all HTTP response headers have been received, send( ) or the background thread sets readyState to 3 and triggers the onreadystatechange event handler. If the response is long, send( ) or the background thread may trigger the onreadystatechange more than once while in state 3: this can serve as a download progress indicator. Finally, when the response is complete, send( ) or the background thread sets readyState to 4 and triggers the event handler one last time.

See Also

XMLHttpRequest.open( ); Chapter 20, Scripting HTTP


Name

XMLHttpRequest.setRequestHeader( ): add a HTTP request header to the request

Synopsis

void setRequestHeader(Stringname, String value)

Arguments

name

The name of the header to be set. This argument should not contain spaces, colons, linefeeds, or newlines.

value

The value for the header. This argument should not contain linefeeds or newlines.

Description

setRequestHeader( ) specifies an HTTP request header that should be included in the request issued by a subsequent call to send( ). This method may be called only when readyState is 1—i.e., after a call to open( ) but before a call to send( ).

If a header with the specified name has already been specified, the new value for that header is the previously specified value, plus a comma, a space, and the value specified in this call.

If the call to open( ) specifies authorization credentials, XMLHttpRequest automatically sends an appropriate Authorization request header. You can append to this header with setRequestHeader( ), however. Similarly, if the web browser has stored cookies associated with the URL passed to open( ), appropriate Cookie or Cookie2 headers are automatically included with the request. You can append additional cookies to these headers by calling setRequestHeader( ). XMLHttpRequest may also provide a default value for the User-Agent header. If it does this, any value you specify for that header is appended to the default value.

Some request headers are automatically set by the XMLHttpRequest for conformance to the HTTP protocol and may not be set with this method. These include proxy-related headers as well as the following:

Host
Connection
Keep-Alive
Accept-Charset
Accept-Encoding
If-Modified-Since
If-None-Match
If-Range
Range

See Also

XMLHttpRequest.getResponseHeader( )


Name

XMLSerializer: serializes XML documents and nodes — Firefox 1.0, Safari 2.01, Opera 7.60: Object → XMLSerializer

Constructor

new XMLSerializer( )

Methods

serializeToString( )

This instance method performs the actual serialization.

Description

An XMLSerializer object enables you to convert or "serialize" an XML Document or Node object to a string of unparsed XML markup. To use an XMLSerializer, instantiate one with the no-argument constructor, and then call its serializeToString( ) method:

var text = (new XMLSerializer( )).serializeToString(element);

Internet Explorer does not support the XMLSerializer object. Instead, it makes XML text available through the xml property of the Node object.

See Also

DOMParser, Node; Chapter 21, JavaScript and XML


Name

XMLSerializer.serializeToString( ): convert an XML document or node to a string

Synopsis

String serializeToString(Nodenode)

Arguments

node

The XML node to be serialized. This may be a Document object or any Element within the document.

Returns

A string of XML markup that represents the serialized form of the specified node and all its descendants.


Name

XPathExpression: a compiled XPath query — Firefox 1.0, Safari 2.01, Opera 9: Object → XPathExpression

Methods

evaluate( )

Evaluates this expression for a specified context node.

Description

An XPathExpression object is a compiled representation of an XPath query, returned by Document.createExpression( ). Evaluate the expression against a particular document node with the evaluate( ) method. If you need to evaluate an XPath query only once, you can use Document.evaluate( ), which compiles and evaluates the expression in a single step.

Internet Explorer does not support the XPathExpression object. For IE-specific XPath methods, see Node.selectNodes( ) and Node.selectSingleNode( ).

See Also

Document.createExpression( )
Document.evaluate( )
Node.selectNodes( )
Node.selectSingleNode( )
Chapter 21, JavaScript and XML

Name

XPathExpression.evaluate( ): evaluate a compiled XPath query

Synopsis

XPathResult evaluate(NodecontextNode,
                     short type,
                     XPathResult result)

Arguments

contextNode

The node (or document) against which the query should be evaluated.

type

The desired result type. This argument should be one of the constants defined by XPathResult.

result

An XPathResult object into which the results of the query should be stored, or null to have the evaluate( ) method create and return a new XPathResult object.

Returns

An XPathResult that hold the results of the query. This is either the object passed as the result argument or a newly created XPathResult object if result was null.

Description

This method evaluates the XPathExpression against a specified node or document and returns the results in an XPathResult object. See XPathResult for details on how to extract values from the returned object.

See Also

Document.evaluate( ), Node.selectNodes( ), XPathResult; Chapter 21, JavaScript and XML


Name

XPathResult: the result of an XPath query — Firefox 1.0; Safari 2.01; Opera 9: Object → XPathResult

Constants

The following constants define the possible types an XPath query can return. The resultType property of an XPathResult object holds one of these values to specify which kind of result the object holds. These constants are also used with Document.evaluate( ) and XPathExpression.evaluate( ) methods to specify the desired result type. The constants and their meanings are as follows:

ANY_TYPE

Passes this value to Document.evaluate( ) or XPathExpression.evaluate( ) to specify that any type of result is acceptable. The resultType property is never set to this value.

NUMBER_TYPE

numberValue holds the result.

STRING_TYPE

stringValue holds the result.

BOOLEAN_TYPE

booleanValue holds the result.

UNORDERED_NODE_ITERATOR_TYPE

The result is an unordered set of nodes, which can be accessed sequentially by calling iterateNext( ) repeatedly until it returns null. The document must not be modified during this iteration.

ORDERED_NODE_ITERATOR_TYPE

The result is a list of nodes, arranged in document order, which can be accessed sequentially by calling iterateNext( ) repeatedly until it returns null. The document must not be modified during this iteration.

UNORDERED_NODE_SNAPSHOT_TYPE

The result is a random-access list of nodes. The snapshotLength property specifies the length of the list, and the snapshotItem( ) method returns the node at a specified index. The nodes may not be in the same order they appear in the document. Since this kind of result is a "snapshot," it remains valid even if the document is changed.

ORDERED_NODE_SNAPSHOT_TYPE

The result is a random-access list of nodes, just like UNORDERED_NODE_SNAPSHOT_TYPE, except that this list is arranged in document order.

ANY_UNORDERED_NODE_TYPE

The singleNodeValue property refers to a node that matches the query or null if no nodes matched. If more than one node matches the query, singleNodeValue may be any one of the matching nodes.

FIRST_ORDERED_NODE_TYPE

singleNodeValue holds the first node in the document that matched the query, or null if no nodes matched.

Instance Properties

Many of these properties are valid only when resultType holds a particular value. Accessing properties that are not defined for the current resultType causes an exception.

readonly boolean booleanValue

Holds the result value when resultType is BOOLEAN_TYPE.

readonly boolean invalidIteratorState

Is true if resultType is one of the ITERATOR_TYPE constants and the document has been modified, making the iterator invalid, because the result was returned.

readonly float numberValue

Holds the result value when resultType is NUMBER_TYPE.

readonly short resultType

Specifies what kind of result the XPath query returned. Its value is one of the constants listed earlier. The value of this property tells you which other properties or methods you can use.

readonly Node singleNodeValue

Holds the result value when resultType is XPathResult.ANY_UNORDERED_NODE_TYPE or XPathResult.FIRST_UNORDERED_NODE_TYPE.

readonly integer snapshotLength

Specifies the number of nodes returned when resultType is UNORDERED_NODE_SNAPSHOT_TYPE or ORDERED_NODE_SNAPSHOT_TYPE. Use this property in conjunction with snapshotItem( ).

readonly String stringValue

Holds the result value when resultType is STRING_TYPE.

Methods

iterateNext( )

Returns the next node in the node set. Use this method if the resultType is UNORDERED_NODE_ITERATOR_TYPE or ORDERED_NODE_ITERATOR_TYPE.

snapshotItem( )

Returns the node at the specified index in the list of result nodes. This method may be used only if resultType is UNORDERED_NODE_SNAPSHOT_TYPE or ORDERED_NODE_SNAPSHOT_TYPE. Use the snapshotLength property in conjunction with this method.

Description

An XPathResult object represents the value of an XPath expression. Objects of this type are returned by Document.evaluate( ) and XPathExpression.evaluate( ). XPath queries can evaluate to strings, numbers, booleans, nodes, and lists of nodes. XPath implementations can return lists of nodes in several different ways, so this object defines a slightly complex API for obtaining the actual result of an XPath query.

To use an XPathResult, first check the resultType property. It will hold one of the XPathResult constants. The value of this property tells you which property or method you need to use to determine the result value. Calling methods or reading properties that are not defined for the current resultType causes an exception.

Internet Explorer does not support the XPathResult API. To perform XPath queries in IE, see Node.selectNodes( ) and Node.selectSingleNode( ).

See Also

Document.evaluate( ), XPathExpression.evaluate( )


Name

XPathResult.iterateNext( ): return the next node that matches an XPath query

Synopsis

Node iterateNext( )
    throws DOMException

Returns

Returns the next node in the list of matching nodes, or null if there are no more.

Throws

This method throws an exception if the document has been modified since the XPathResult was returned. It also throws an exception if called when returnType is not UNORDERED_NODE_ITERATOR_TYPE or ORDERED_NODE_ITERATOR_TYPE.

Description

iterateNext( ) returns the next node that matches the XPath query or null if all matching nodes have already been returned. Use this method if resultType is UNORDERED_NODE_ITERATOR_TYPE or ORDERED_NODE_ITERATOR_TYPE. If the type is ordered, nodes are returned in the order they appear in the document. Otherwise, they can be returned in any order.

If the invalidIteratorState property is true, the document has been modified, and this method throws an exception.