Client-Side JavaScript Reference: Chapter 25 - JavaScript: The Definitive Guide
by David FlanaganThis 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!
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.
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
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.
Name
Applet: an applet embedded in a web page — DOM Level 0:
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.
See Also
JSObject; JavaObject in Part III, “Core JavaScript Reference” ; Chapter 12, Scripting Java,
Chapter 23, Scripting Java Applets and Flash Movies
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
nullif the Attr object is not currently associated with any Element.-
readonly boolean specified trueif the attribute is explicitly specified in the document source or set by a script;falseif 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.
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/.
Name
Canvas.getContext( ): return a context for drawing on the canvas
Synopsis
CanvasRenderingContext2D getContext(StringcontextID)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.
Name
CanvasGradient: a color gradient for use in a canvas — Firefox 1.5, Safari 1.3, Opera 9: Object → CanvasGradient
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.
Name
CanvasGradient.addColorStop( ): add a change of color at some point in the gradient
Synopsis
void addColorStop(floatoffset, Stringcolor)
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.
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( ), andCanvasRenderingContext2D.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
lineJoinproperty 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( ), andCanvasRenderingContext2D.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
fillStyleproperty.-
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, andstrokeStyleproperties, 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.
Name
CanvasRenderingContext2D.arc( ): add an arc to the current subpath of a canvas, using a center point and radius
Synopsis
void arc(floatx, floaty, floatradius, floatstartAngle,endAngle, booleancounterclockwise)
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.
Name
CanvasRenderingContext2D.arcTo( ): add an arc of a circle to the current subpath, using tangent points and a radius
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
Name
CanvasRenderingContext2D.beginPath( ): start a new collection of subpaths in a canvas
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
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).
Name
CanvasRenderingContext2D.clearRect( ): erase a rectangular area of a canvas
Name
CanvasRenderingContext2D.clip( ): set the clipping path of a canvas
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
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( )).
Name
CanvasRenderingContext2D.createLinearGradient( ): create a linear color gradient
Synopsis
CanvasGradient createLinearGradient(floatxStart, floatyStart, floatxEnd, floatyEnd)
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.
Name
CanvasRenderingContext2D.createPattern( ): create a pattern of tiled images
Synopsis
CanvasPattern createPattern(Imageimage, StringrepetitionStyle)
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 |
|---|---|
|
|
Tile the image in both directions. This is the default. |
|
|
Tile the image in the X dimension only. |
|
|
Tile the image in the Y dimension only. |
|
|
Do not tile the image; use it a single time only. |
Name
CanvasRenderingContext2D.createRadialGradient( ): create a radial color gradient
Synopsis
CanvasGradient createRadialGradient(floatxStart, floatyStart, floatradiusStart, floatxEnd, floatyEnd, floatradiusEnd)
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.
Name
CanvasRenderingContext2D.drawImage( ): draw an image
Synopsis
void drawImage(Imageimage, floatx, floaty) void drawImage(Imageimage, floatx, floaty, floatwidth, floatheight) void drawImage(Imageimage, integersourceX, integersourceY, integersourceWidth, integersourceHeight, floatdestX, floatdestY, floatdestWidth, floatdestHeight)
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.
Name
CanvasRenderingContext2D.fill( ): fill the path
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.
Name
CanvasRenderingContext2D.fillRect( ): fill a 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.
Name
CanvasRenderingContext2D.globalCompositeOperation: specifies how colors are combined on the canvas
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. |
Name
CanvasRenderingContext2D.lineCap: specifies how the ends of lines are rendered
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. |
Name
CanvasRenderingContext2D.lineJoin: specifies how vertices are rendered
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.
Name
CanvasRenderingContext2D.lineTo( ): add a straight line to the current subpath
Name
CanvasRenderingContext2D.miterLimit: maximum-miter-length-to-line-width ratio
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".
Name
CanvasRenderingContext2D.moveTo( ): sets the current position and begins a new subpath
Name
CanvasRenderingContext2D.quadraticCurveTo( ): add a quadratic Bezier curve to the current subpath
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 ).
Name
CanvasRenderingContext2D.rect( ): add a rectangle subpath to the path
Name
CanvasRenderingContext2D.restore( ): reset drawing state to saved values
Name
CanvasRenderingContext2D.rotate( ): rotate the coordinate system of the canvas
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.
Name
CanvasRenderingContext2D.save( ): save a copy of the current graphics state
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.
Name
CanvasRenderingContext2D.scale( ): scale the user coordinate system of the canvas
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.
Name
CanvasRenderingContext2D.stroke( ): draw the current path
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.
Name
CanvasRenderingContext2D.strokeRect( ): draw a 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.
Name
CanvasRenderingContext2D.translate( ): translate the user coordinate system of the canvas
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( ).
Name
CharacterData: common functionality for Text and Comment nodes — DOM Level 1 Core: Node → CharacterData
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.
Name
CharacterData.appendData( ): append a string to a Text or Comment node — DOM Level 1 Core:
Name
CharacterData.deleteData( ): delete characters from a Text or Comment node — DOM Level 1 Core:
Synopsis
void deleteData(unsigned longoffset, unsigned longcount) throws DOMException;
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:
Name
CharacterData.replaceData( ): replace characters of a Text or Comment node with a string — DOM Level 1 Core:
Synopsis
void replaceData(unsigned longoffset, unsigned longcount, Stringarg) throws DOMException;
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 longcount) 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 offsetis negative or greater than the length of the Text or Comment node, orcountis 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
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( ).
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
codeofSYNTAX_ERR. Attempting to set this property when the CSS2Properties object is read-only throws a DOMException with acodeofNO_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:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
codeofNO_MODIFICATION_ALLOWED_ERRif the rule is read-only or acodeofSYNTAX_ERRif 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 thestyleproperty 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.
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
rulesproperty instead. In DOM-compliant implementations, this array includes objects that represent all rules in a stylesheet, including at-rules such as@importdirectives. 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. Iffalse, 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
nullfor inline stylesheets.-
readonly StyleSheet parentStyleSheet The stylesheet that included this one or
nullif 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
titleattribute 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, Stringstyle, integerindex)
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
rulesarray 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.
Name
CSSStyleSheet.deleteRule( ): delete a rule from a stylesheet — DOM Level 2 CSS:
Name
CSSStyleSheet.insertRule( ): insert a rule into a stylesheet — DOM Level 2 CSS:
Synopsis
unsigned long insertRule(Stringrule, unsigned longindex) 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
cssRulesarray at which the rule is to be inserted or appended.
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 indexis negative or greater thencssRules.length.-
NO_MODIFICATION_ALLOWED_ERR The stylesheet is read-only.
-
SYNTAX_ERR The specified
ruletext contains a syntax error.
Name
CSSStyleSheet.removeRule( ): IE-specific method to remove a rule from a stylesheet — IE 4:
Name
Document: an HTML or XML document — DOM Level 1 Core: Node → Document
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 isnull.-
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 thechildNodes[]array inherited from Node. See also thebodyproperty 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
idattribute, ornullif 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.createAttribute( ): create a new Attr node — DOM Level 1 Core:
Name
Document.createAttributeNS( ): create an Attr with a name and namespace — DOM Level 2 Core:
Synopsis
Attr createAttributeNS(StringnamespaceURI, StringqualifiedName) throws DOMException;
Arguments
-
namespaceURI The unique identifier of the namespace for the Attr or
nullfor no namespace.-
qualifiedName The qualified name of the attribute, which should include a namespace prefix, a colon, and a local name.
Throws
This method may throw a DOMException with one of the
following code values in the
following circumstances:
-
INVALID_CHARACTER_ERR qualifiedNamecontains an illegal character.-
NAMESPACE_ERR qualifiedNameis malformed or there is a mismatch betweenqualifiedNameandnamespaceURI.-
NOT_SUPPORTED_ERR The implementation does not support XML documents and therefore does not implement this method.
Name
Document.createCDATASection( ): create a new CDATASection node — DOM Level 1 Core:
Name
Document.createDocumentFragment( ): create a new, empty DocumentFragment node — DOM Level 1 Core:
Name
Document.createElement( ): create a new Element node — DOM Level 1 Core:
Name
Document.createElementNS( ): create a new Element node using a namespace — DOM Level 2 Core:
Synopsis
Element createElementNS(StringnamespaceURI, StringqualifiedName) throws DOMException;
Arguments
-
namespaceURI The unique identifier for the namespace of the new Element or
nullfor no namespace.-
qualifiedName The qualified name of the new Element. This should include a namespace prefix, a colon, and a local name.
Throws
This method may throw a DOMException with one of the
following code values in the
following circumstances:
-
INVALID_CHARACTER_ERR qualifiedNamecontains an illegal character.-
NAMESPACE_ERR qualifiedNameis malformed or there is a mismatch betweenqualifiedNameandnamespaceURI.-
NOT_SUPPORTED_ERR The implementation does not support XML documents and therefore does not implement this method.
Name
Document.createEvent( ): create an Event object — DOM Level 2 Events:
Synopsis
Event createEvent(StringeventType)
throws DOMExceptionDescription
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 |
|
|
MouseEvents |
MouseEvent |
|
|
UIEvents |
UIEvent |
|
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.
Name
Document.createExpression( ): create an XPath expression for later evaluation — Firefox 1.0, Safari 2.01, Opera 9:
Synopsis
XPathExpression createExpression(StringxpathText, FunctionnamespaceURLMapper) throws XPathException
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.
Name
Document.createProcessingInstruction( ): create a ProcessingInstruction node — DOM Level 1 Core:
Name
Document.createRange( ): create a Range object — DOM Level 2 Range:
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.
Name
Document.evaluate( ): evaluate an XPath expression — Firefox 1.0, Safari 2.01, Opera 9:
Synopsis
XPathResult evaluate(StringxpathText, NodecontextNode, FunctionnamespaceURLMapper, shortresultType, XPathResultresult) 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
nullif 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
typeare the constants defined by the XPathResult object.-
result An XPathResult object to be reused or
nullif 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.
Name
Document.getElementById( ): find an element with the specified unique ID — DOM Level 2 Core:
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.
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.)
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
}Name
Document.getElementsByTagNameNS( ): return all Element nodes with a specified name and namespace — DOM Level 2 Core:
Name
Document.importNode( ): copy a node from another document for use in this document — DOM Level 2 Core:
Synopsis
Node importNode(NodeimportedNode, booleandeep) throws DOMException;
Arguments
-
importedNode The node to be imported.
-
deep If
true, recursively copy all descendants ofimportedNodeas well.
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.
Name
Document.loadXML( ): populate this Document by parsing a string of XML markup — Internet Explorer:
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.
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.
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
nullif none is specified.readonly String systemId[DOM Level 2]The system identifier of the external subset of the DTD, or
nullif 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.
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.
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
documentElementproperty 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, StringqualifiedName, DocumentTypedoctype) throws DOMException;
Arguments
-
namespaceURI The unique identifier of the namespace of the root element to be created for the document, or
nullfor no namespace.-
qualifiedName The name of the root element to be created for this document. If
namespaceURIis notnull, this name should include a namespace prefix and a colon.-
doctype The DocumentType object for the newly created Document, or
nullif 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 qualifiedNamecontains an illegal character.-
NAMESPACE_ERR qualifiedNameis malformed or there is a mismatch betweenqualifiedNameandnamespaceURI.-
NOT_SUPPORTED_ERR The current implementation does not support XML documents and has not implemented this method.
-
WRONG_DOCUMENT_ERR doctypeis 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.
Name
DOMImplementation.createDocumentType( ): create a DocumentType node — DOM Level 2 Core:
Synopsis
DocumentType createDocumentType(StringqualifiedName, StringpublicId, StringsystemId) 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.
Throws
This method may throw a DOMException with one of the
following code values:
-
INVALID_CHARACTER_ERR qualifiedNamecontains an illegal character.-
NAMESPACE_ERR qualifiedNameis 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, Stringversion);
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
nullor 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.
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
}Name
DOMParser: parses XML markup to create a Document — Firefox 1.0, Safari 2.01, Opera 7.60: Object → DOMParser
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.
Name
DOMParser.parseFromString( ): parse XML markup
Name
Element: an HTML or XML element — DOM Level 1 Core: Node → Element
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 inheritednodeNameproperty 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
trueif this element has an attribute with the specified name, orfalseotherwise. Note that this method returnstrueif 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 byDocument.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, Functionlistener, booleanuseCapture);
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 specifiedlisteneris to be invoked only during the capturing phase of event propagation. The more common value offalsemeans that thelisteneris 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, Functionlistener);
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
eventproperty 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( )anddetachEvent( )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" foraddEventListener( ).Functions registered with
attachEvent( )are invoked with no Event object argument. Instead, they must read theeventproperty 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 withattachEvent( )executes, thethiskeyword 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.
Name
Element.detachEvent( ): delete an event listener — IE 4:
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;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.
Name
Element.getAttribute( ): return the string value of a named attribute — DOM Level 1 Core:
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;Name
Element.getAttributeNode( ): return the Attr node for the named attribute — DOM Level 1 Core:
Name
Element.getAttributeNodeNS( ): return the Attr node for an attribute with a namespace — DOM Level 2 Core:
Synopsis
Attr getAttributeNodeNS(StringnamespaceURI, StringlocalName);
Name
Element.getAttributeNS( ): get the value of an attribute that uses namespaces — DOM Level 2 Core:
Synopsis
String getAttributeNS(StringnamespaceURI, StringlocalName);
Name
Element.getElementsByTagName( ): find descendant elements with a specified tag name — DOM Level 1 Core:
Synopsis
Element[] getElementsByTagName(Stringname);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.
Name
Element.getElementsByTagNameNS( ): return descendant elements with the specified name and namespace — DOM Level 2 Core:
Synopsis
Node[] getElementsByTagNameNS(StringnamespaceURI, StringlocalName);
Name
Element.hasAttribute( ): determine whether this element has a specified attribute — DOM Level 2 Core:
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.
Name
Element.hasAttributeNS( ): determine whether this element has a specified attribute — DOM Level 2 Core:
Synopsis
boolean hasAttributeNS(StringnamespaceURI, StringlocalName);
Name
Element.removeAttribute( ): delete a named attribute of an element — DOM Level 1 Core:
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.
Name
Element.removeAttributeNode( ): remove an Attr node from an element — DOM Level 1 Core:
Name
Element.removeAttributeNS( ): delete an attribute specified by name and namespace — DOM Level 2 Core:
Synopsis
void removeAttributeNS(StringnamespaceURI, StringlocalName);
Name
Element.removeEventListener( ): delete an event listener — DOM Level 2 Events:
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, Stringvalue) throws DOMException;
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.
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.
Throws
This method may throw a DOMException with a code of the following values:
-
INUSE_ATTRIBUTE_ERR newAttris 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 newAttrhas a differentownerDocumentproperty 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( ).
Name
Element.setAttributeNodeNS( ): add a namespace Attr node to an Element — DOM Level 2 Core:
Synopsis
Attr setAttributeNodeNS(AttrnewAttr)
throws DOMException;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.
Name
Element.setAttributeNS( ): create or change an attribute with a namespace — DOM Level 2 Core:
Synopsis
void setAttributeNS(StringnamespaceURI, StringqualifiedName, Stringvalue) throws DOMException;
Arguments
-
namespaceURI The URI that uniquely identifies the namespace of the attribute to be set or created, or
nullfor 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
qualifiedNameargument contains a character that is not allowed in HTML or XML attribute names.-
NAMESPACE_ERR qualifiedNameis malformed, or there is a mismatch between the namespace prefix ofqualifiedNameand thenamespaceURIargument.-
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.
Name
Event: information about an event — DOM Level 2 Events, IE: Object → Event
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 trueif the event is of a type that bubbles (unlessstopPropagation( )is called);falseotherwise.-
readonly boolean cancelable trueif the default action associated with the event can be canceled withpreventDefault( );falseotherwise.-
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_PHASE1Event.AT_TARGET2Event.BUBBLING_PHASE3-
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. SeeDatein 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,
buttonspecifies 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,
fromElementrefers 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
falseto 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,
toElementrefers 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, thetypeproperty 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.
Name
Event.initEvent( ): initialize the properties of a new event — DOM Level 2 Events
Synopsis
void initEvent(StringeventTypeArg, booleancanBubbleArg, booleancancelableArg);
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.
Name
Event.preventDefault( ): cancel default action of an event — DOM Level 2 Events
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
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
falseif 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, Objectinstance, Functionfunc)
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
funcas a method of theinstanceobject.-
instance The ActionScript object on which
funcis to be invoked ornull. This argument becomes the value of thethiskeyword whenfuncis invoked.-
func The ActionScript function that is invoked when the JavaScript function named
nameis invoked.
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, Objectargs...)
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
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.LoadMovie( ): load an auxiliary movie — Flash 3
Name
FlashPlayer.Pan( ): move the viewport of the movie — Flash 2
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.
Name
FlashPlayer.SetVariable( ): set a variable defined by a Flash movie — Flash 4
Name
FlashPlayer.SetZoomRect( ): set the viewport of a movie — Flash 2
Name
FlashPlayer.Zoom( ): zoom in or out — Flash 2
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 |
|---|---|---|
|
|
|
Character sets the server can accept |
|
|
|
URL of the form handler |
|
|
|
Encoding of the form |
|
|
|
HTTP method used for form submission |
|
|
|
Name of the form |
|
|
|
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
Name
Form.elements[]: the input elements of a form — DOM Level 2 HTML
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.
Name
Form.onreset: event handler invoked when a form is reset — DOM Level 0
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
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
Name
Form.submit( ): submit form data to a web server — DOM Level 2 HTML
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
srcattribute of the HTML<frame>tag: it is not a Location object likeWindow.location.
In addition to these properties, the Frame object also defines the following properties, which correspond directly to HTML attributes:
|
Property |
Attribute |
Description |
|---|---|---|
|
|
|
Set to "0" for borderless frames |
|
|
|
The URL of a frame description |
|
|
|
Top and bottom frame margin, in pixels |
|
|
|
Left and right frame margin, in pixels |
|
|
|
The name of the frame, for DOM Level 0 lookup and form and link targets |
|
|
|
If |
|
|
|
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 nameWhen 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
History: the URL history of the browser — JavaScript 1.0: Object → 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.
Name
History.forward( ): visit the next URL — JavaScript 1.0
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
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
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
idornameattribute, ornullif 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
Name
HTMLCollection.item( ): get an element by position — DOM Level 2 HTML
Synopsis
Node item(unsigned longindex);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.
Name
HTMLCollection.namedItem( ): get an element by name — DOM Level 2 HTML
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.
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 asDocument.getElementById( )andDocument.getElementsByTagName( ), it is still used in deployed code. SeeHTMLDocument.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.cookiefor details.-
String domain The domain name of the server from which the document was loaded, or
nullif there is none. This property can also be used to ease the same-origin security policy in specific circumstances. SeeHTMLDocument.domainfor 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
nullif this document was not accessed through a hyperlink. This property allows client-side JavaScript to access the HTTPrefererheader. 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.hrefproperty of the Window that contains the document. When URL redirection occurs, however, thisURLproperty holds the actual URL of the document, andlocation.hrefholds 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
nameattribute.-
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.
Name
HTMLDocument.all[]: all HTML elements in a document — IE 4
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.
Name
HTMLDocument.close( ): close an open document and display it — DOM Level 0
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.
Name
HTMLDocument.cookie: the cookie(s) of the document — DOM Level 0
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
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
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.
Name
HTMLDocument.open( ): begin a new document, erasing the current one — DOM Level 0
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.
Name
HTMLDocument.write( ): append HTML text to an open document — DOM Level 0
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.
Name
HTMLDocument.writeln( ): append HTML text and a newline to an open document — DOM Level 0
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
classattribute 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
dirattribute of the element, which specifies the text direction for the document.-
String id The value of the
idattribute. No two elements within the same document should have the same value forid.-
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
langattribute, 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
offsetParentcontainer element. These are nonstandard but well-supported properties.-
Element offsetParent Specifies the container element that defines the coordinate system in which
offsetLeftandoffsetTopare measured. For most elements,offsetParentis the Document object that contains them. However, if an element has a dynamically positioned container, the dynamically positioned element is theoffsetParent. 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
overflowattribute, for example) these properties differ fromoffsetHeightandoffsetWidth, 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
overflowattribute set toauto. 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
styleattribute that specifies inline CSS styles for this element. Note that the value of this property is not a string. SeeCSS2Propertiesfor details.-
String title The value of the
titleattribute 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:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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: |
|
|
HTMLAnchorElement: |
|
|
HTMLAppletElement[*]: |
|
|
HTMLAreaElement: |
|
|
HTMLBaseElement: |
|
| |
|
|
HTMLQuoteElement: |
|
|
HTMLBodyElement: |
|
HTMLBRElement: | |
|
|
HTMLButtonElement: |
|
|
HTMLTableCaptionElement: |
|
|
HTMLTableColElement: |
|
|
HTMLModElement: |
|
| |
|
|
HTMLDivElement: |
|
|
HTMLDListElement: |
|
|
HTMLFieldSetElement: |
|
| |
|
|
HTMLFormElement: |
|
|
HTMLFrameElement: |
|
|
HTMLFrameSetElement: |
|
|
HTMLHeadingElement: |
|
|
HTMLHeadElement: |
|
|
HTMLHRElement: |
|
|
HTMLHtmlElement: |
|
|
HTMLIFrameElement: |
|
|
HTMLImageElement: |
|
|
HTMLInputElement: |
|
|
See |
|
|
HTMLIsIndexElement[*]: |
|
|
HTMLLabelElement: |
|
|
HTMLLegendElement: |
|
| |
|
|
HTMLLinkElement: |
|
|
HTMLMapElement: |
|
| |
|
|
HTMLMetaElement: |
|
|
HTMLObjectElement: |
|
|
HTMLOListElement: |
|
|
HTMLOptGroupElement: |
|
|
HTMLOptionElement: |
|
|
HTMLParagraphElement: |
|
|
HTMLParamElement: |
|
|
HTMLPreElement: |
|
|
See |
|
|
HTMLScriptElement: |
|
|
HTMLSelectElement: |
|
|
HTMLStyleElement: |
|
|
HTMLTableElement: |
|
|
HTMLTableSectionElement: |
|
|
HTMLTableCellElement: |
|
|
HTMLTextAreaElement: |
|
|
See |
|
|
See |
|
|
See |
|
|
HTMLTitleElement: |
|
|
HTMLTableRowElement: |
|
| |
[*] 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
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.
Name
HTMLElement.ondblclick: event handler invoked when the user double-clicks on an element — DOM Level 0
Name
HTMLElement.onkeydown: event handler invoked when the user presses a key — DOM Level 0
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.
Name
HTMLElement.onkeypress: event handler invoked when the user presses a key — DOM Level 0
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.
Name
HTMLElement.onkeyup: event handler invoked when the user releases a key — DOM Level 0
Name
HTMLElement.onmousedown: event handler invoked when the user presses a mouse button — DOM Level 0
Name
HTMLElement.onmousemove: event handler invoked when the mouse moves within an element — DOM Level 0
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.
Name
HTMLElement.onmouseout: event handler invoked when mouse moves out of an element — DOM Level 0
Name
HTMLElement.onmouseover: event handler invoked when the mouse moves over an element — DOM Level 0
Name
HTMLElement.onmouseup: event handler invoked when the user releases a mouse button — DOM Level 0
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.
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
srcattribute 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 |
|---|---|---|
|
|
|
Alignment with respect to inline content |
|
|
|
Set to "0" for borderless frames |
|
|
|
Height of the viewport in pixels or percent |
|
|
|
The URL of a frame description |
|
|
|
Top and bottom frame margin, in pixels |
|
|
|
Left and right frame margin, in pixels |
|
|
|
The name of the frame, for DOM Level 0 lookup and form and link targets |
|
|
|
Frame scroll policy: "auto", "yes", or "no" |
|
|
|
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
Properties
-
String name This property specifies the name for the image object. If an
<img>tag has anameattribute, 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
srcattribute 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 |
|---|---|---|
|
|
|
Alignment with respect to inline content |
|
|
|
Alternate text when image can't be displayed |
|
|
|
Size of image border |
|
|
|
Image height, in pixels |
|
|
|
Left and right margins, in pixels |
|
|
|
Whether to use a server-side image map |
|
|
|
The URI of a long image description |
|
|
|
Specifies a client-side image map for the image |
|
|
|
Top and bottom margin, in pixels |
|
|
|
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.onerror: event handler invoked when an error occurs during image loading — DOM Level 2 Events
Name
Input: an input element in an HTML form — DOM Level 2 HTML: Node → Element → HTMLElement → Input
Properties
-
String accept When
typeis "file", this property is a comma-separated list of MIME types that specify the types of files that may be uploaded. Mirrors theacceptattribute.-
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
accesskeyattribute.-
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
alignattribute.-
String alt Alternate text to be displayed by browsers that cannot render this input element. Particularly useful when
typeis "image". Mirrors thealtattribute.-
boolean checked When
typeis "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 thecheckedattribute.-
boolean defaultChecked When
typeis "radio" or "checkbox", this property holds the initial value of thecheckedattribute as it appears in the document source. When the form is reset, thecheckedproperty is restored to the value of this property. Changing the value of this property changes the value of thecheckedproperty and the current checked state of the element.-
String defaultValue When
typeis "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 thevalueproperty and the currently displayed value.-
boolean disabled If
true, the input element is disabled and is unavailable for user input. Mirrors thedisabledattribute.-
readonly HTMLFormElement form The Form object representing the
<form>element that contains this input element, ornullif the input element is not within a form.-
long maxLength If
typeis "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 thesizeproperty. Mirrors themaxlengthattribute.-
String name The name of the input element, as specified by the
nameattribute. See the following Description section for further details on form element names.-
boolean readOnly If
trueandtypeis "text" or "password", the user is not allowed to enter text into the element. Mirrors thereadonlyattribute.-
unsigned long size If
typeis "text" or "password", this property specifies the width of the element in characters. Mirrors thesizeattribute. See alsomaxLength.-
String src For input elements with a
typeof "image", specifies the URL of the image to be displayed. Mirrors thesrcattribute.-
long tabIndex The position of this input element in the tabbing order. Mirrors the
tabindexattribute.-
String type The type of the input element. Mirrors the
typeattribute. See the Description section for further details on form element types.-
String useMap For elements with a
typeof "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
typeof "text", "password", or "file", this property is the editable text contained by the input element. For elements with atypeof "button", "submit", or "reset", this is the (noneditable) label that appears in the button. For security reasons, thevalueproperty 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
typeis "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
typeis "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
onclickevent) 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
valueproperty. The button has no default behavior and must be given anonclickevent handler in order to be useful. For buttons that submit or reset a form, use atypeof "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
checkedproperty holds the current state of the button, and theonclickevent handler is triggered whenever this value changes (browsers may also trigger theonchangehandler). Thevalueproperty 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 samenameproperty and differentvalueproperties, 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
valueproperty 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
valueattribute is ignored, and thevalueproperty 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 theonchangeevent handler.- "hidden"
An input element of this type is, in fact, hidden. The
valueproperty 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
srcproperty) 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
valueproperty. In other respects, a password input element behaves like an element of type "text". It triggers theonchangeevent 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 samename. For toggle buttons without mutual exclusion, use atypeof "checkbox". Note that the HTML<select>tag can also be used for presenting exclusive or nonexclusive choices (seeSelect).The
checkedproperty 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 thecheckedproperty of each one. Radio buttons trigger theonclickevent handler when selected or deselected.The
valueproperty 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 HTMLvalueattribute or the JavaScriptdefaultValueproperty).The
valueproperty specifies the text to appear in the button. A reset button triggers theonclickhandler before resetting the form, and this handler may cancel the reset by returningfalseor by using other event cancellation methods described in Chapter 17, Events and Event Handling. See also theForm.reset( )method and theForm.onresetevent handler.- "submit"
An element of this type is a push button that submits the containing
<form>when clicked. Thevalueproperty specifies the text to appear in the button. Theonclickevent handler is triggered before the form is submitted, and a handler may cancel form submission by returningfalse. See also theForm.submit( )method andForm.onsubmitevent handler.- "text"
This is the default value of the
typeproperty; it creates a single-line text input field. The HTMLvalueattribute specifies the default text to appear in the field, and the JavaScriptvalueproperty holds the currently displayed text. Theonchangeevent handler is triggered when the user edits the displayed text and then transfers input focus to some other element. Usesizeto specify the width of the input field andmaxLengthto 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 (seeTextarea). For masked text input, settypeto "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=valuewhere 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,...,valuenSimilarly, 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[].
Name
Input.focus( ): give keyboard focus to a form element — DOM Level 2 HTML
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
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.
Name
Input.onchange: event handler invoked when a form element's value changes — DOM Level 2 Events
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.
Name
Input.onclick: event handler invoked when a form element is clicked — DOM Level 2 Events
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.
Name
Input.onfocus: event handler invoked when a form element gains focus — DOM Level 2 Events
Name
Input.select( ): select the text in a form element — DOM Level 2 HTML
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
JSObject: Java representation of a JavaScript object — Java class in Java plug-in
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, Objectargs[])
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
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
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
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
Name
JSObject.removeMember( ): delete a property of a JavaScript object — Java method in Java plug-in
Name
JSObject.setMember( ): set a property of a JavaScript object — Java method in Java plug-in
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
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
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
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
nameattribute of the<a>tag. (seeAnchor).-
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 |
|---|---|---|
|
|
|
Keyboard shortcut |
|
|
|
Encoding of the destination document |
|
|
|
For |
|
|
|
Language of the linked document |
|
|
|
Anchor name; see |
|
|
|
Link type |
|
|
|
Reverse link type |
|
|
|
For |
|
|
|
Link's position in tabbing order |
|
|
|
Name of the frame or window in which the destination document is to be displayed |
|
|
|
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.
Name
Link.onclick: event handler invoked when a Link is clicked — DOM Level 0
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.
Name
Link.onmouseout: event handler invoked when the mouse leaves a link — DOM Level 0
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
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
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.
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
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.
Name
MimeType: represents a MIME datatype — JavaScript 1.1; not supported by IE: Object → MimeType
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 alsonullwhen 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
typeproperty can also be used as an index to access the elements of thenavigator.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);
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,
clientYis 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
targetnode 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.relatedTargetis 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.
Name
MouseEvent.initMouseEvent( ): initialize the properties of a MouseEvent object — DOM Level 2 Events
Synopsis
void initMouseEvent(StringtypeArg, booleancanBubbleArg, booleancancelableArg, AbstractViewviewArg, longdetailArg, longscreenXArg, longscreenYArg, longclientXArg, longclientYArg, booleanctrlKeyArg, booleanaltKeyArg, booleanshiftKeyArg, booleanmetaKeyArg, unsigned shortbuttonArg, ElementrelatedTargetArg);
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.
Name
Navigator: information about the browser in use — JavaScript 1.0: Object → 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 toparseFloat( )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
trueif the browser has cookies enabled andfalseif 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.appCodeNamefollowed by a slash and the value ofnavigator.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”.
Name
Navigator.javaEnabled( ): test whether Java is available — JavaScript 1.1
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
attributesproperty 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 theattributesproperty 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,childNodesis an array withlengthzero. 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
nullif the node has no children.-
readonly Node lastChild The last child of this node, or
nullif 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
namespaceURIandprefixproperties.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
localNameandprefixproperties.-
readonly Node nextSibling The sibling node that immediately follows this one in the
childNodes[]array of theparentNode, ornullif 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
tagNameproperty 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
nullif 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 aparentNodeofnull.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
localNameandnamespaceURLproperties.-
readonly Node previousSibling The sibling node that immediately precedes this one in the
childNodes[]array of theparentNode, ornullif 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
innerHTMLproperty of HTMLElement, and seeXMLSerializerfor 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
trueif this node is an Element and has any attributes.-
hasChildNodes( ) Returns
trueif 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
trueif 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( )andDocument.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( )andDocument.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
XSLTProcessorfor 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
XSLTProcessorfor 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 |
|---|---|---|
|
|
The element's tag name |
|
|
|
The attribute name |
The attribute value |
|
|
|
The text of the node |
|
|
|
The text of the node |
|
|
The target of the PI |
The remainder of the PI |
|
|
|
The text of the comment |
|
|
|
|
|
|
The document type name |
|
|
|
|
|
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.
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
newChildis an ancestor of this node (or is this node itself).-
WRONG_DOCUMENT_ERR The
ownerDocumentproperty ofnewChildis not the same as theownerDocumentproperty 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
}Name
Node.cloneNode( ): duplicate a node and, optionally, all of its descendants — DOM Level 1 Core
Synopsis
Node cloneNode(booleandeep);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
Name
Node.insertBefore( ): insert a node into the document tree before the specified node — DOM Level 1 Core
Synopsis
Node insertBefore(NodenewChild, NoderefChild) 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
newChildis to be inserted. If this argument isnull,newChildis inserted as the last child of this node.
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
newChildis an ancestor of this node (or is this node itself).-
WRONG_DOCUMENT_ERR The
ownerDocumentproperty ofnewChildand this node are different.-
NO_MODIFICATION_ALLOWED_ERR This node is read-only and does not allow insertions, or the parent of
newChildis read-only and does not allow deletions.-
NOT_FOUND_ERR refChildis 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)
}Name
Node.isSupported( ): determine if a node supports a feature — DOM Level 2 Core
Synopsis
boolean isSupported(Stringfeature, Stringversion);
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.
Name
Node.normalize( ): merge adjacent Text nodes and remove empty ones — DOM Level 1 Core
Name
Node.removeChild( ): remove (and return) the specified child of this node — DOM Level 1 Core
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.
Name
Node.replaceChild( ): replace a child node with a new node — DOM Level 1 Core
Synopsis
Node replaceChild(NodenewChild, NodeoldChild) throws DOMException;
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
newChildis an ancestor of this node (or is this node itself).-
WRONG_DOCUMENT_ERR newChildand this node have different values forownerDocument.-
NO_MODIFICATION_ALLOWED_ERR This node is read-only and does not allow replacement, or
newChildis the child of a node that does not allow removals.-
NOT_FOUND_ERR oldChildis 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>Name
Node.selectNodes( ): select nodes with an XPath query — IE 6
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( ).
Name
Node.transformNode( ): transform a node to a string using XSLT — IE 6
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.
Name
Node.transformNodeToObject( ): transform a node to a document using XSLT — IE 6
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.
Name
NodeList: a read-only array of nodes — DOM Level 1 Core: Object → NodeList
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!
Name
NodeList.item(): get an element of a NodeList — DOM Level 1 Core
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, Stringvalue, booleandefaultSelected, booleanselected)
Arguments
-
text An optional string argument that specifies the
textproperty of the Option object.-
value An optional string argument that specifies the
valueproperty of the Option object.-
defaultSelected An optional boolean argument that specifies the
defaultSelectedproperty of the Option object.-
selected An optional boolean argument that specifies the
selectedproperty of the Option object.
Properties
-
boolean defaultSelected The initial value of the
selectedattribute of the<option>element. If the form is reset, theselectedproperty is reset to the value of this property. Setting this property also sets the value of theselectedproperty.-
boolean disabled If
true, this<option>element is disabled, and the user is not allowed to select it. Mirrors thedisabledattribute.-
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
labelattribute. 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 theselectedattribute.-
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
valueattribute.
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 selectedplain_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.
Name
Plugin: describes an installed plug-in — JavaScript 1.1; not supported by IE: Object → Plugin
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
nameproperty is more useful thanfilenamefor 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
lengthproperty specifies the number of elements in the array.-
name The
nameproperty 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 thenavigator.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.
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.
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 trueif 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
codeofINVALID_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( )anddeleteContents( ).-
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.
Name
Range.cloneContents(): copy range contents into a DocumentFragment — DOM Level 2 Range
Name
Range.collapse(): make one boundary point equal to the other — DOM Level 2 Range
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, RangesourceRange) 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.
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
sourceRangeto the end point of this range.-
Range.END_TO_START Compares the end point of
sourceRangeto 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
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.
Name
Range.detach(): free a Range object — DOM Level 2 Range
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
Name
Range.insertNode( ): insert a node at the start of a range — DOM Level 2 Range
Synopsis
void insertNode(NodenewNode)
throws RangeException,
DOMException;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
newNodeis 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 newNodeis 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( ).
Name
Range.selectNode(): set range boundaries to a node — DOM Level 2 Range
Synopsis
void selectNode(NoderefNode)
throws RangeException, DOMException;Name
Range.selectNodeContents( ): set range boundaries to the children of a node — DOM Level 2 Range
Name
Range.setEnd( ): set the end point of a range — DOM Level 2 Range
Synopsis
void setEnd(NoderefNode, longoffset) 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.
Name
Range.setEndAfter( ): end a range after a specified node — DOM Level 2 Range
Synopsis
void setEndAfter(NoderefNode)
throws RangeException, DOMException;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.
Name
Range.setEndBefore( ): end a range before the specified node — DOM Level 2 Range
Name
Range.setStart( ): set the start point of a range — DOM Level 2 Range
Name
Range.setStartAfter( ): start a range after the specified node — DOM Level 2 Range
Name
Range.setStartBefore( ): start a range before the specified node — DOM Level 2 Range
Name
Range.surroundContents( ): surround range contents with the specified node — DOM Level 2 Range
Synopsis
void surroundContents(NodenewParent)
throws RangeException, DOMException;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, ornewParentis 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 newParentand 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 newParentis 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
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
Screen: provides information about the display — JavaScript 1.2: Object → 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.
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 asoptions.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. SeeSelect.options[]for further details.-
long selectedIndex The position of the selected option in the
optionsarray. 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
multipleattribute specified. When you're doing listbox selection (whensize> 1), you can deselect all options by settingselectedIndexto −1. Note that changing the selection in this way does not trigger theonchange( )event handler.-
readonly String type If
multipleistrue, this property is "select-multiple"; otherwise, it is "select-one". This property exists for compatibilty with thetypeproperty of the Input object.
In addition to the properties above, Select objects also mirror HTML attributes with the following properties:
|
Property |
Attribute |
Description |
|---|---|---|
|
|
|
Whether the user element is disabled |
|
|
|
Whether more than one option may be selected |
|
|
|
Element name for form submission |
|
|
|
The number of options to display at once |
|
|
|
Position of Select element in the tabbing order |
Methods
-
add( ) Inserts a new Option object into the
optionsarray, 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.
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.
Name
Select.add( ): insert an <option> element — DOM Level 2 HTML
Synopsis
void add(HTMLElementelement, HTMLElementbefore) throws DOMException;
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.
Name
Select.onchange: event handler invoked when the selection changes — DOM Level 0
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.
Name
Select.options[]: the choices in a Select object — DOM Level 2 HTML
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.lengthto 0, all options in the Select object are cleared.If you set
options.lengthto 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 tonull, 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 alsoSelect.remove( )).If you create a new Option object with the
Option( )constructor (seeOption), you can add that option to the end of the options list in the Select object by appending it to theoptions[]array. To do this, setoptions[options.length](see alsoSelect.add( )).
Name
Select.remove( ): remove an <option> — DOM Level 2 HTML
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, ornullif 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, ornullif there is none.-
TableSection tHead The
<thead>element of the table, ornullif 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 |
|---|---|---|
|
|
|
Horizontal alignment of table in document |
|
|
|
Table background color |
|
|
|
Width of border around table |
|
|
|
Space between cell contents and border |
|
|
|
Space between cell borders |
|
|
|
Which table borders to draw |
|
|
|
Where to draw lines within the table |
|
|
|
Summary description of table |
|
|
|
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.
Name
Table.createCaption( ): get or create a <caption> — DOM Level 2 HTML
Name
Table.createTFoot( ): get or create a <tfoot> — DOM Level 2 HTML
Name
Table.createTHead( ): get or create a <thead> — DOM Level 2 HTML
Name
Table.deleteRow( ): delete a row of a table — DOM Level 2 HTML
Name
Table.insertRow( ): add a new, empty row to the table — DOM Level 2 HTML
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.
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 |
|---|---|---|
|
|
|
See HTML specification |
|
|
|
Horizontal alignment of cell |
|
|
|
See HTML specification |
|
|
|
Background color of cell |
|
|
|
Alignment character |
|
|
|
Alignment character offset |
|
|
|
Columns spanned by cell |
|
|
|
|
|
|
|
Cell height in pixels |
|
|
|
Don't word-wrap cell |
|
|
|
Rows spanned by cell |
|
|
|
Scope of this header cell |
|
|
|
Vertical alignment of cell |
|
|
|
Cell width in pixels |
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 |
|---|---|---|
|
|
|
Default horizontal alignment of cells in this row |
|
|
|
Background color of this row |
|
|
|
Alignment character for cells in this row |
|
|
|
Alignment character offset for cells in this row |
|
|
|
Default vertical alignment for cells in this row |
Name
TableRow.deleteCell( ): delete a cell in a table row — DOM Level 2 HTML
Name
TableRow.insertCell( ): insert a new, empty <td> element into a table row — DOM Level 2 HTML
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 |
|---|---|---|
|
|
|
Default horizontal alignment of cells in this section of the table |
|
|
|
Default alignment character for cells in this section |
|
|
|
Default alignment offset for cells in this section |
|
|
|
Default vertical alignment for cells in this section |
Name
TableSection.deleteRow( ): delete a row within a table section — DOM Level 2 HTML
Name
TableSection.insertRow( ): insert a new, empty row into this table section — DOM Level 2 HTML
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.
Name
Text: a run of text in an HTML or XML document — DOM Level 1 Core: Node → CharacterData → Text
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.
Name
Text.splitText( ): split a Text node in two — DOM Level 1 Core
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.
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, ornullif 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
defaultValueproperty. When the user types into this element, thevalueproperty is updated to match the user's input. If you set thevalueproperty explicitly, the string you specify is displayed in the Textarea object. Thisvalueproperty 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 |
|---|---|---|
|
|
|
Keyboard shortcut character |
|
|
|
The width in character columns |
|
|
|
Whether the Textarea is disabled |
|
|
|
Textarea name for form submission and element access. |
|
|
|
Whether the Textarea is noneditable |
|
|
|
Height of Textarea in lines |
|
|
|
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.onchange: event handler invoked when input value changes — DOM Level 0
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
UIEvent: details about user-interface events — DOM Level 2 Events: Event → UIEvent
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.
Name
UIEvent.initUIEvent( ): initialize the properties of a UIEvent object — DOM Level 2 Events
Synopsis
void initUIEvent(StringtypeArg, booleancanBubbleArg, booleancancelableArg, WindowviewArg, longdetailArg);
Name
Window: a web browser window or frame — JavaScript 1.0: Object → Global → Window
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
closedproperty is set totrue.-
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
Documentfor 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
Eventand 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. Theframes.lengthproperty contains the number of elements in theframes[]array. Note that frames referenced by theframes[]array may themselves contain frames and may have aframes[]array of their own.-
history A read-only reference to the History object of this window or frame. See
Historyfor 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
clientWidthandclientHeightproperties ofdocument.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
Locationfor 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 thenameattribute of a<frame>tag. The name of a window may be used as the value of atargetattribute of an<a>or<form>tag. Using thetargetattribute 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
Navigatorfor 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. Theopenerproperty 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 thescrollLeftandscrollTopproperties ofdocument.documentElementordocument.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,
parentrefers to the window itself. If this window is a frame, theparentproperty 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
Screenfor 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
screenLeftandscreenTop, while Firefox and Safari supportscreenXandscreenY.-
self A read-only reference to this window itself. This is a synonym for the
windowproperty.-
status A read/write string that specifies the current contents of the browser's status line. See
Window.statusfor 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
topproperty simply contains a reference to the window itself. If this window is a frame, thetopproperty refers to the top-level window that contains the frame. Contrast with theparentproperty.-
window The
windowproperty is identical to theselfproperty; 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 windoww.frames[i] // Frames of specified windoww
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 windoww
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 framef
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.
See Also
Document; Global in Part III, “Core JavaScript Reference” ; Chapter 14, Scripting Browser Windows
Name
Window.alert( ): display a message in a dialog box — JavaScript 1.0:
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.
Name
Window.blur( ): remove keyboard focus from a top-level window — JavaScript 1.1:
Name
Window.clearInterval( ): stop periodically executing code — JavaScript 1.2:
Name
Window.clearTimeout( ): cancel deferred execution — JavaScript 1.0:
Name
Window.close( ): close a browser window — JavaScript 1.0:
Name
Window.confirm( ): ask a yes-or-no question — JavaScript 1.0:
Synopsis
window.confirm(question)
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.
Name
Window.defaultStatus: the default status line text — JavaScript 1.0:
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.
Name
Window.focus( ): give keyboard focus to a window — JavaScript 1.1:
Name
Window.getComputedStyle( ): retrieve the CSS styles used to render an element — DOM Level 2 CSS:
Synopsis
CSS2Properties getComputedStyle(Elementelt, StringpseudoElt);
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.
Name
Window.moveBy( ): move a window to a relative position — JavaScript 1.2:
Name
Window.moveTo( ): move a window to an absolute position — JavaScript 1.2:
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:
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.
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)
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:
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.
Name
Window.onload: event handler invoked when a document finishes loading — JavaScript 1.0:
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.
See Also
Window.onunload; the section called “Manipulating the Document During Loading”, "Manipulating the Document
During Loading," Example 17-7, “Portable event registration for onload event handlers”, Chapter 17, Events and Event Handling
Name
Window.onresize: event handler invoked when a window is resized — JavaScript 1.2:
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:
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
targetattribute of<a>and<form>HTML tags. If this argument names a window that already exists, theopen( )method does not create a new window, but simply returns a reference to the named window. In this case, thefeaturesargument 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.
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.
Name
Window.prompt( ): get user input with a dialog box — JavaScript 1.0:
Synopsis
window.prompt(message,default)
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.
Name
Window.resizeBy( ): resize a window by a relative amount — JavaScript 1.2:
Name
Window.resizeTo( ): resize a window — JavaScript 1.2:
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:
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.
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.
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
delayhas 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
codeshould be executed.
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.
Name
Window.status: specify a transient status-line message — JavaScript 1.0:
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.
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 librariesProperties
-
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:
The value of
readyStatenever decreases, unlessabort( )oropen( )are called on a request that is already in progress. Every time the value of this property increases, theonreadystatechangeevent 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
readyStateis less than 3, this property is the empty string. WhenreadyStateis 3, this property returns whatever portion of the response has been received so far. IfreadyStateis 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
nullunless all three of the following conditions are true:readyStateis 4.The response includes a
Content-Typeheader 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
readyStateis 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
statusis 200 and "Not Found" whenstatusis 404. As with thestatusproperty, reading this property whenreadyStateis 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
readyStateproperty changes. It may also be invoked multiple times whilereadyStateis 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:
Call
open( )to specify the URL and method (usually "GET" or "POST") for the request. When you callopen( ), you also specify whether you want the request to be synchronous or asynchronous.If you specified an asynchronous request, set the
onreadystatechangeproperty to the function that will be notified of the progress of the request.Call
setRequestHeader( ), if needed, to specify additional request parameters.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 toopen( ), thesend( )method blocks until the response is complete andreadyStateis 4. Otherwise, youronreadystatechangeevent-handler function must wait until thereadyStateproperty reaches 4 (or at least 3).Once
send( )has returned for synchronous requests, orreadyStatehas reached 4 for asynchronous requests, you can use the server's response. First, check thestatuscode to ensure that the request was successful. If so, usegetResponseHeader( )orgetResponseHeaders( )to retrieve values from the response header, and use theresponseTextorresponseXMLproperties 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.getAllResponseHeaders( ): return unparsed HTTP response headers
Name
XMLHttpRequest.getResponseHeader( ): get the value of a named HTTP response header
Name
XMLHttpRequest.onreadystatechange: event handler function invoked when readyState changes
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, Stringurl, booleanasync, Stringusername, Stringpassword)
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 tosend( )will block until the response is fully received. If this argument istrueor is omitted, the request is asynchronous, and anonreadystatechangeevent 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.
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, ornullif no body is necessary. For any other method, this argument is unused and should benull. (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
bodyargument 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.
Name
XMLHttpRequest.setRequestHeader( ): add a HTTP request header to the request
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
|
Name
XMLSerializer: serializes XML documents and nodes — Firefox 1.0, Safari 2.01, Opera 7.60: Object → XMLSerializer
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.
Name
XPathExpression: a compiled XPath query — Firefox 1.0, Safari 2.01, Opera 9: Object → XPathExpression
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, shorttype, XPathResultresult)
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
nullto have theevaluate( )method create and return a new XPathResult object.
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( )orXPathExpression.evaluate( )to specify that any type of result is acceptable. TheresultTypeproperty is never set to this value.-
NUMBER_TYPE numberValueholds the result.-
STRING_TYPE stringValueholds the result.-
BOOLEAN_TYPE booleanValueholds 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 returnsnull. 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 returnsnull. The document must not be modified during this iteration.-
UNORDERED_NODE_SNAPSHOT_TYPE The result is a random-access list of nodes. The
snapshotLengthproperty specifies the length of the list, and thesnapshotItem( )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
singleNodeValueproperty refers to a node that matches the query ornullif no nodes matched. If more than one node matches the query,singleNodeValuemay be any one of the matching nodes.-
FIRST_ORDERED_NODE_TYPE singleNodeValueholds the first node in the document that matched the query, ornullif 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
resultTypeisBOOLEAN_TYPE.-
readonly boolean invalidIteratorState Is
trueifresultTypeis one of theITERATOR_TYPEconstants and the document has been modified, making the iterator invalid, because the result was returned.-
readonly float numberValue Holds the result value when
resultTypeisNUMBER_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
resultTypeisXPathResult.ANY_UNORDERED_NODE_TYPEorXPathResult.FIRST_UNORDERED_NODE_TYPE.-
rea
