home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam    

Book HomeMac OS X for Unix GeeksSearch this book

Chapter 25. W3C DOM Reference

This part of the book is a reference section that documents the interfaces, methods, and properties defined by the W3C Level 1 and Level 2 DOM standards. Intermediate and advanced programmers who are writing for the newest generation of standards-compliant web browsers will use this reference section, in conjunction with the core and client-side JavaScript references in Part III and Part IV. The introduction and sample reference page explain how to use and get the most out of this reference section. There are significant differences between this reference section and the other two, and you should read this introduction carefully so you can fully understand the reference information it contains.

Like the core and client-side references, this reference section is arranged alphabetically. The reference pages for the methods and properties of DOM interfaces are alphabetized by their full names, which include the names of the interfaces that define them. For example, if you want to read about the appendChild( ) method of the Node interface, you would look under "Node.appendChild," not just "appendChild."

To save space in this enlarged fourth edition of the book, properties in this reference section do not have reference pages of their own (all interfaces and methods do have their own reference pages, however). Instead, each property is completely documented in the reference page for the interface that defines it. For example, you can read about the tagName property of the Element interface in the "Element" reference page.

Sometimes you may find that you don't know the name of the interface that defines the method or property you want to look up, or you may not be sure which of the three reference sections to look up a class or interface in. Part VI of this book is a special index designed to help with these situations. Look up the name of a class, interface, method, or property, and it will tell you which reference section to look in and which class to look under in that section. For example, if you look up "Document," it will tell you that both the client-side and DOM reference sections have entries under that name. And if you look up the name "firstChild," it will tell you that firstChild is a property of Node, which you can read about in this DOM reference section.

Once you've found the reference page you're looking for, you shouldn't have much difficulty finding the information you need. Because the DOM standard is intended to work with languages other than JavaScript, however, it was written with typed languages (such as Java and C++) in mind. Although JavaScript is an untyped language, the property and method type information defined by the standard is still quite useful and is included in the reference pages in this section. This means that method and property synopses in this section use a syntax that is more like Java than like JavaScript. What follows is a sample reference page titled "Sample Entry" that demonstrates the structure of each reference page and explains how to interpret the information presented in each section. Even if you are already well familiar with the third edition of this book, take the time to read this page before diving into the DOM reference section.

Sample Entryhow to read DOM reference pages

Availability

Availability

Inherits from/Overrides

Inherits from

Title and Short Description

Every reference entry begins with a title block like that above. The entries are alphabetized by title. The short description, shown next to the title, gives you a quick summary of the item documented in the entry; it can help you quickly decide if you're interested in reading the rest of the page.

Availability

The information in the "Availability" section tells you what level and what module of the DOM standard defines the interface or method. Since properties do not have their own reference pages, they do not have availability information. If the availability of a property is different from the availability of the interface that defines it, this fact is noted in the description of the property.

Inherits from

DOM interfaces can inherit properties and methods from other interfaces. If a DOM interface inherits from another interface, the inheritance hierarchy is shown in the "Inherits from" section. For example, the "Inherits from" information for the HTMLElement interface looks like this:

Node Figure Element Figure HTMLElement

This indicates that HTMLElement inherits from the Element interface, which in turn inherits from the Node interface. When you see this section, you may also want to look up the other listed interfaces.

Subinterfaces

This section contains the opposite of the "Inherits from" information: it lists any interfaces that inherit from this one. For example, the "Subinterfaces" section of the reference page for the Element interface specifies that HTMLElement is a subinterface of Element and inherits Element's methods and properties.

Also Implements

The modular structure of the DOM standard means that some interfaces have been broken into multiple separate interfaces, so that implementations have to implement only the interfaces that are part of the modules they support. It is common for an object that implements one interface (such as Document) to also implement several other simple interfaces (such as DocumentCSS, DocumentEvent, and DocumentViews) that provide functionality specific to other modules. When an interface has minor interfaces that are intended to be implemented along with it, those minor interfaces are listed in this section.

Constants

Some DOM interfaces define a set of constants that serve as the values for a property or as the arguments to a method of that interface. The Node interface, for example, defines important constants to serve as the set of legal values for the nodeType property of all Document nodes. When an interface defines constants, they are listed and documented in this section. The listings include the type, the name, and the value (in that order) of each constant. See the Section section for a discussion of the syntax used in these listings. Note that constants are static properties of the interface itself, not of instances of that interface.

Properties

If the reference page documents an interface, this section lists and documents the properties defined by that interface. Each entry in the list specifies the name and type of the property and may also include other keywords that provide additional information about the property. Note that in this Java-style syntax, the name of the property comes last, and all the information that precedes the name provides type and other information about the property. For example, the HTMLTableElement and HTMLTableCellElement interfaces define properties that include the following:

HTMLTableCaptionElement caption
The caption property. It refers to an object of type HTMLTableCaptionElement.

readonly HTMLCollection rows
The rows property. It refers to an HTMLCollection object and is read-only: you can query the value of the property, but you cannot set it.

deprecated String align
The align property. It is a string, but it is deprecated and its use is discouraged.

readonly long cellIndex
The cellIndex property. It is a long integer value (see the Section section) and is read-only.

Methods

If the reference page documents an interface, this section lists the names of the interface's methods and provides a short description of each. Full documentation for each method is found in a separate reference page.

Synopsis

If the reference page documents a method, this section presents the method signature or synopsis. This section uses a Java-style syntax to specify (in order):

  • The type of the method return value, or void if the method does not return anything.

  • The name of the method.

  • The type and name (in that order) of each argument of the method. These are presented as a comma-separated list of argument types and names within parentheses. If the method does not take any arguments, you simply see the parentheses: ( ).

  • The types of exceptions, if any, that the method can throw.

For example, the "Synopsis" section of the Node.insertBefore( ) method looks like this:

Node insertBefore(Node newChild, 
                  Node refChild)
    throws DOMException;

You can glean the following information from this synopsis: the name of the method is "insertBefore"; it returns a Node object; the first argument is a Node object and specifies the "newChild" (presumably the one to be inserted); the second argument is also a Node object and specifies the "refChild" (presumably the node before which the other is inserted); and the method may, in some circumstances, throw an exception of type DOMException.

The subsections that follow the synopsis provide additional information about the arguments, return value, and exceptions of the method. See also the Section section for more information about the Java-style syntax used here to specify the types of method arguments.

Arguments

If a method has arguments, the "Synopsis" section is followed by an "Arguments" subsection that lists the names of the arguments and describes each one. Note that argument names are listed in italics, to indicate that they are not to be typed literally but instead represent some other value or JavaScript expression. To continue with the previous example, the "Arguments" section of Node.insertBefore( ) looks like this:

newChild
The node to be inserted into the tree. If it is a DocumentFragment, its children are inserted instead.

refChild
The child of this node before which newChild is to be inserted. If this argument is null, newChild is inserted as the last child of this node.

Returns

The "Synopsis" section specifies the data type of the method's return value, and the "Returns" subsection provides additional information. If the method has no return value (i.e., if it is listed in the "Synopsis" section as returning void), this section is omitted.

Throws

This section explains the kinds of exceptions the method can throw and under what circumstances it throws them.

DOM Types

DOM reference pages use a Java-style syntax for specifying the types of constants, properties, method return values, and method arguments. This section provides more information about that syntax. Note that the reference pages themselves do not have "DOM Types" sections!

The general syntax is:

modifiers type name

The name of the constant, property, method, or method argument always comes last and is preceded by type and other information. The modifiers used in this reference section (note that these are not actually legal Java modifiers) are:

readonly
Specifies that a property value can be queried but cannot be set.

deprecated
Specifies that a property is deprecated and its use should be avoided.

unsigned
Specifies that a numeric constant, property, return value, or method argument is unsigned; i.e., it may be zero or positive, but may not be negative.

The types of DOM constants, properties, method return values, and method arguments do not always correspond directly to the types supported by JavaScript. For example, some properties have a type of short which specifies a 16-bit integer. Although JavaScript only has a single numeric type, this reference section uses the DOM type simply because it provides more information about what range of numbers are legal. The DOM types you will encounter in this reference section are:

String
A core JavaScript String object.

Date
A core JavaScript Date object (this is not commonly used).

boolean
A boolean value: true or false.

short
A short (16-bit) integer. This type may have the unsigned modifier applied to it.

long
A long (64-bit) integer. This type may have the unsigned modifier applied to it.

float
A floating-point number. This type may not have the unsigned modifier applied to it.

void
This type is used for method return values only; it indicates that the method does not return any value.

Any other type
Any other types you see in this reference section are names of other DOM interfaces (for example, Document, DOMImplementation, Element, HTMLTableElement, and Node).

Description

Most reference pages contain a "Description" section, which is the basic description of the interface or method that is being documented. This is the heart of the reference page. If you are learning about an interface or method for the first time, you may want to skip directly to this section and then go back and look at previous sections such as "Synopsis," "Properties," and "Methods." If you are already familiar with an interface or method, you probably won't need to read this section and instead will just want to quickly look up some specific bit of information (such as the name of a property or the type of an argument from the "Properties" or "Arguments" sections).

In some pages, this section is no more than a short paragraph. In others, it may occupy a page or more. For some simple methods, the "Arguments," "Returns," and "Throws" sections document the method sufficiently by themselves, so the "Description" section is omitted.

Example

Reference pages for some commonly used interfaces and methods include an example in this section to illustrate typical usage of the interface or method. Most pages do not contain examples, however -- you'll find those in first half of this book.

See Also

Most reference pages conclude with cross-references to related reference pages that may be of interest. Most of these cross-references are to other reference pages in this DOM reference section. Some are to individual property descriptions contained within an interface reference page, however, and others are to related reference pages in the client-side reference section or to chapters in the first two parts of the book.

Reference pages that document interfaces (but not those that document methods) may have additional paragraphs at the end of the "See Also" section. These are cross-references that show how the interface is used. A "Type of" paragraph lists properties whose values are objects that implement the interface. A "Passed to" paragraph lists methods that take an argument that implements the interface. A "Returned by" paragraph lists methods that return an object that implements the interface. These cross-references show how you can obtain an object of this interface and what you can do with it once you have obtained it.

AbstractViewa window displaying a document

Availability

DOM Level 2 Views

Also Implements

ViewCSS
If the DOM implementation supports the CSS module, any object that implements the AbstractView interface also implements the ViewCSS interface. For convenience, the method defined by the ViewCSS interface is listed under "Methods."

Properties

readonly Document document
The Document object that is displayed by this View object. This Document object also implements the DocumentView interface.

Methods

getComputedStyle( ) [DOM Level 2 CSS]
This ViewCSS method returns a read-only CSSStyleDeclaration that represents the computed style information for a specific document element.

Description

In the DOM, a view is an object that displays a document in some way. The Window object of client-side JavaScript is such a view. This AbstractView interface is a very preliminary step toward standardizing some of the properties and methods of the Window object. It simply specifies that all View objects have a property named document that refers to the document they display. In addition, if an implementation supports CSS style sheets, all View objects also implement the ViewCSS interface and define a getComputedStyle( ) method for determining how an element is actually rendered in the view.

The document property gives every view a reference to the document it displays. The reverse is true also: every document has a reference to the view that displays it. If a DOM implementation supports the View module, the object that implements the Document interface also implements the DocumentView interface. This DocumentView interface defines a defaultView property that refers to the window in which the document is displayed.

This interface has the word "Abstract" in its name to emphasize the fact that it is merely the beginning of a standardized window interface. In order to be useful, future levels of the DOM standard will have to introduce a new interface that extends AbstractView and adds other properties or methods.

See Also

Reference

Type of

Document.defaultView

AbstractView.getComputedStyle( )retrieve the CSS styles used to render an element

Availability

DOM Level 2 CSS

Synopsis

CSSStyleDeclaration getComputedStyle(Element elt, 
                                     String pseudoElt);

Arguments

elt
The document element whose style information is desired.

pseudoElt
The CSS pseudoelement, or null if there is none.

Returns

A read-only CSSStyleDeclaration object (which typically also implements the CSS2Properties interface) that specifies the style information used to render the specified element in this view. Any length values queried from this object are always absolute or pixel values, not relative or percentage values.

Description

An element in a document may obtain style information from an inline style attribute and from any number of style sheets in the style-sheet "cascade." Before the element can actually be displayed in a view, its style must be "computed" by extracting style information from the appropriate parts of the cascade.

This method allows access to those computed styles. By contrast, the style property of an element gives you access only to the inline styles of an element and tells you nothing about style-sheet attributes that apply to the element. Note that this method also provides a way to determine the actual pixel coordinates at which an element is rendered in this view.

getComputedStyle( ) is actually defined by the ViewCSS interface. In any DOM implementation that supports the View and CSS modules, any object that implements AbstractView always implements ViewCSS also. So, for simplicity, this method has been listed with AbstractView.

In Internet Explorer, similar functionality is available through the nonstandard currentStyle property of each HTMLElement object.

See Also

CSS2Properties, CSSStyleDeclaration, Reference

Attran attribute of a document element

Availability

DOM Level 1 Core

Inherits from/Overrides

Node Figure Attr

Properties

readonly String name
The name of the attribute.

readonly Element ownerElement [DOM Level 2]
The Element object that contains this attribute, or null if the Attr object is not currently associated with any Element.

readonly boolean specified
true if the attribute was explicitly specified in the document source or set by a script. false if the attribute was 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( ) method of the Element interface.

Attr objects are nodes, and the value of an Attr is represented by the child nodes of the Attr node. In HTML documents, this is simply a single Text node. In XML documents, however, Attr nodes may have both Text and EntityReference children. The value property provides a shortcut for reading and writing the value of an attribute as a String.

In most cases, the easiest way to work with element attributes is with the getAttribute( ) and setAttribute( ) methods of the Element interface. These methods use strings for attribute names and values and avoid the use of Attr nodes altogether.

See Also

Element

Passed to

Element.removeAttributeNode( ), Element.setAttributeNode( ), Element.setAttributeNodeNS( )

Returned by

Document.createAttribute( ), Document.createAttributeNS( ), Element.getAttributeNode( ), Element.getAttributeNodeNS( ), Element.removeAttributeNode( ), Element.setAttributeNode( ), Element.setAttributeNodeNS( )

CSS2Propertiesconvenience properties for all CSS2 attributes

Availability

DOM Level 2 CSS2

Properties

This interface defines a large number of properties: one property for each CSS attribute defined by the CSS2 specification. The 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 complete set of properties is listed in the following table. 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, for the same reasons as a call to CSSStyleDeclaration.setProperty( ).

azimuth

background

backgroundAttachment

backgroundColor

backgroundImage

backgroundPosition

backgroundRepeat

border

borderBottom

borderBottomColor

borderBottomStyle

borderBottomWidth

borderCollapse

borderColor

borderLeft

borderLeftColor

borderLeftStyle

borderLeftWidth

borderRight

borderRightColor

borderRightStyle

borderRightWidth

borderSpacing

borderStyle

borderTop

borderTopColor

borderTopStyle

borderTopWidth

borderWidth

bottom

captionSide

clear

clip

color

content

counterIncrement

counterReset

cssFloat

cue

cueAfter

cueBefore

cursor

direction

display

elevation

emptyCells

font

fontFamily

fontSize

fontSizeAdjust

fontStretch

fontStyle

fontVariant

fontWeight

height

left

letterSpacing

lineHeight

listStyle

listStyleImage

listStylePosition

listStyleType

margin

marginBottom

marginLeft

marginRight

marginTop

markerOffset

marks

maxHeight

maxWidth

minHeight

minWidth

orphans

outline

outlineColor

outlineStyle

outlineWidth

overflow

padding

paddingBottom

paddingLeft

paddingRight

paddingTop

page

pageBreakAfter

pageBreakBefore

pageBreakInside

pause

pauseAfter

pauseBefore

pitch

pitchRange

playDuring

position

quotes

richness

right

size

speak

speakHeader

speakNumeral

speakPunctuation

speechRate

stress

tableLayout

textAlign

textDecoration

textIndent

textShadow

textTransform

top

unicodeBidi

verticalAlign

visibility

voiceFamily

volume

whiteSpace

widows

width

wordSpacing

zIndex

   

Description

This interface defines one property for each CSS attribute defined by the CSS2 specification. If the DOM implementation supports this interface (which is part of the "CSS2" feature), all CSSStyleDeclaration objects also implement CSS2Properties. Reading one of the properties defined by this interface is equivalent to calling getPropertyValue( ) for the corresponding CSS attribute, and setting the value of one of these properties is equivalent to calling setProperty( ) for the corresponding attribute. The properties defined by CSS2Properties include properties that correspond to CSS shortcut attributes, and CSS2Properties handles these shortcut properties correctly.

See Also

CSSStyleDeclaration

CSSPrimitiveValuea single CSS style value

Availability

DOM Level 2 CSS

Inherits from/Overrides

CSSValue Figure CSSPrimitiveValue

Constants

The following constants are the legal values for the primitiveType property. They specify the type of the value and, for numeric values, the units in which the value is represented.

unsigned short CSS_UNKNOWN = 0
The value is not recognized, and the implementation does not know how to parse it. The textual representation of the value is available through the cssText property.

unsigned short CSS_NUMBER = 1
A unitless number. Query with getFloatValue( ).

unsigned short CSS_PERCENTAGE = 2
A percentage. Query with getFloatValue( ).

unsigned short CSS_EMS = 3
A relative length measured in ems (the height of the current font). Query with getFloatValue( ).

unsigned short CSS_EXS = 4
A relative length measured in exs (the "x-height" of the current font). Query with getFloatValue( ).

unsigned short CSS_PX = 5
A length measured in pixels. Query with getFloatValue( ). Pixel lengths are relative measurements, in the sense that their size depends on the display resolution, and they cannot be converted to inches, millimeters, points, or other absolute lengths. However, pixels are also one of the most commonly used units, and they are treated as absolute values for the purposes of AbstractView.getComputedStyle( ), for example.

unsigned short CSS_CM = 6
An absolute length measured in centimeters. Query with getFloatValue( ).

unsigned short CSS_MM = 7
An absolute length measured in millimeters. Query with getFloatValue( ).

unsigned short CSS_IN = 8
An absolute length measured in inches. Query with getFloatValue( ).

unsigned short CSS_PT = 9
An absolute length measured in points (1/72 of an inch). Query with getFloatValue( ).

unsigned short CSS_PC = 10
An absolute length measured in picas (12 points). Query with getFloatValue( ).

unsigned short CSS_DEG = 11
An angle measured in degrees. Query with getFloatValue( ).

unsigned short CSS_RAD = 12
An angle measured in radians. Query with getFloatValue( ).

unsigned short CSS_GRAD = 13
An angle measured in grads. Query with getFloatValue( ).

unsigned short CSS_MS = 14
A time measured in milliseconds. Query with getFloatValue( ).

unsigned short CSS_S = 15
A time measured in seconds. Query with getFloatValue( ).

unsigned short CSS_HZ = 16
A frequency measured in hertz. Query with getFloatValue( ).

unsigned short CSS_KHZ = 17
A frequency measured in kilohertz. Query with getFloatValue( ).

unsigned short CSS_DIMENSION = 18
A unitless dimension. Query with getFloatValue( ).

unsigned short CSS_STRING = 19
A string. Query with getStringValue( ).

unsigned short CSS_URI = 20
A URI. Query with getStringValue( ).

unsigned short CSS_IDENT = 21
An identifier. Query with getStringValue( ).

unsigned short CSS_ATTR = 22
An attribute function. Query with getStringValue( ).

unsigned short CSS_COUNTER = 23
A counter. Query with getCounterValue( ).

unsigned short CSS_RECT = 24
A rectangle. Query with getRectValue( ).

unsigned short CSS_RGBCOLOR = 25
A color. Query with getRGBColorValue( ).

Properties

readonly unsigned short primitiveType
The type of this value. This property holds one of the constants defined in the previous section.

Methods

getCounterValue( )
For values of type CSS_COUNTER, returns the Counter object that represents the value.

getFloatValue( )
Returns a numeric value, converting it, if necessary, to the specified units.

getRectValue( )
For values of type CSS_RECT, returns the Rect object that represents the value.

getRGBColorValue( )
For values of type CSS_RGBCOLOR, returns the RGBColor object that represents the value.

getStringValue( )
Returns the value as a string.

setFloatValue( )
Sets a numeric value to the specified number of the specified units.

setStringValue( )
Sets a string value to the specified string of the specified type.

Description

This subinterface of CSSValue represents a single CSS value. Contrast it with the CSSValueList interface, which represents a list of CSS values. The word "primitive" in the name of this interface is misleading; this interface can represent some complex types of CSS values, such as counters, rectangles, and colors.

The primitiveType property holds one of the previously defined constants and specifies the type of the value. The various methods defined by this interface allow you to query values of various types and also to set numeric and string values.

See Also

Counter, CSSValue, CSSValueList, Rect, RGBColor

Type of

RGBColor.blue, RGBColor.green, RGBColor.red, Rect.bottom, Rect.left, Rect.right, Rect.top

CSSPrimitiveValue.getFloatValue( )get a numeric value, possibly converting units

Availability

DOM Level 2 CSS

Synopsis

float getFloatValue(unsigned short unitType) 
    throws DOMException;

Arguments

unitType
One of the CSSPrimitiveValue type constants that specifies the desired units for the returned value.

Returns

The floating-point numeric value of this CSSPrimitiveValue, expressed in the specified units.

Throws

This method throws a DOMException with a code of INVALID_ACCESS_ERR if this CSSPrimitiveValue holds a non-numeric value, or if the value cannot be converted to the requested type of units. (See the next section for more about unit conversion.)

Description

For CSSPrimitiveValue objects that hold numeric values, this method converts those values to the specified units and returns the converted values.

Only certain types of unit conversions are allowed. Lengths may be converted to lengths, angles to angles, times to times, and frequencies to frequencies. Obviously, however, a length measured in millimeters cannot be converted to a frequency measured in kilohertz. Also, not all lengths can be converted. Relative lengths (lengths measured in ems, exs, or pixels) can be converted to other relative lengths but cannot be converted to absolute lengths. Similarly, absolute lengths cannot be converted to relative lengths. Finally, percentage values cannot be converted to any other unit type, except for color percentage values, which express a percentage of 255 and can be converted to the CSS_NUMBER type.

CSSRulea rule in a CSS style sheet

Availability

DOM Level 2 CSS

Subinterfaces

CSSCharsetRule, CSSFontFaceRule, CSSImportRule, CSSMediaRule, CSSPageRule, CSSStyleRule, CSSUnknownRule

Constants

These constants represent the various types of rules that may appear in a CSS style sheet. They are the legal values of the type property, and they specify which of the above subinterfaces this object implements.

unsigned short UNKNOWN_RULE = 0;    // CSSUnknownRule
unsigned short STYLE_RULE = 1;      // CSSStyleRule
unsigned short CHARSET_RULE = 2;    // CSSCharsetRule
unsigned short IMPORT_RULE = 3;     // CSSImportRule
unsigned short MEDIA_RULE = 4;      // CSSMediaRule
unsigned short FONT_FACE_RULE = 5;  // CSSFontFaceRule
unsigned short PAGE_RULE = 6;       // CSSPageRule

Properties

String cssText
The textual representation of the rule. If you set this property, it may throw a DOMException with one of the following code values for one of the following reasons:

HIERARCHY_REQUEST_ERR
The specified rule is not legal at this location in the style sheet.

INVALID_MODIFICATION_ERR
The new value of the property is a rule of a different type than the original value.

NO_MODIFICATION_ALLOWED_ERR
The rule or the style sheet that contains it is read-only.

SYNTAX_ERR
The specified string is not legal CSS syntax.

readonly CSSRule parentRule
The containing rule of this rule, or null if this rule does not have a parent. An example of a CSS rule with a parent is a style rule within an @media rule.

readonly CSSStyleSheet parentStyleSheet
The CSSStyleSheet object that contains this rule.

readonly unsigned short type
The type of CSS rule this object represents. The legal values for this property are the previously listed constants. This CSSRule interface is never implemented directly, and the value of this property specifies which more specific subinterface is implemented by this object.

Description

This interface defines properties that are common to all types of rules in CSS style sheets. No object directly implements this interface; instead, they implement one of the more specific subinterfaces listed earlier. The most important subinterface is probably CSSStyleRule, which describes a CSS rule that defines a document style.

See Also

CSSStyleRule

Type of

CSSRule.parentRule, CSSStyleDeclaration.parentRule, CSSStyleSheet.ownerRule

Returned by

CSSRuleList.item( )

CSSStyleDeclarationa set of CSS style attributes and their values

Availability

DOM Level 2 CSS

Also Implements

If the implementation supports the "CSS2" feature in addition to the "CSS" feature (as most web browsers do), all objects that implement this interface also implement the CSS2Properties interface. CSS2Properties provides commonly used shortcut properties for setting and querying the values of CSS attributes. See CSS2Properties for details.

Properties

String cssText
The textual representation of the style attributes and their values. This property consists of the complete text of the style rule, minus the element selector and the curly braces that surround the attributes and values. Setting this property to an illegal value throws a DOMException with a code of SYNTAX_ERR. Setting it for a read-only style sheet or rule throws a DOMException with a code of NO_MODIFICATION_ALLOWED_ERR.

readonly unsigned long length
The number of style attributes in this style declaration.

readonly CSSRule parentRule
The CSSRule object that contains this CSSStyleDeclaration, or null if this style declaration is not part of a CSS rule (such as for CSSStyleDeclaration objects that represent inline HTML style attributes).

Methods

getPropertyCSSValue( )
Returns a CSSValue object that represents the value of the named CSS attribute, or null if that attribute is not explicitly set in this style declaration block or if the named style is a "shortcut" attribute.

getPropertyPriority( )
Returns the string "important" if the named CSS attribute is explicitly set in this declaration block and has the !important priority qualifier specified. If the attribute is not specified, or has no priority, returns the empty string.

getPropertyValue( )
Returns the value of the named CSS attribute as a string. Returns the empty string if the attribute is not specified in this declaration block.

item( )
Returns the name of the CSS attribute at the specified position in this style declaration block. In JavaScript, the CSSStyleDeclaration object can be treated as an array and indexed using square brackets instead. See also the length property.

removeProperty( )
Deletes a named CSS attribute from this declaration block.

setProperty( )
Sets a named CSS attribute to the specified string value and priority for this declaration block.

Description

This attribute represents a CSS style declaration block: a set of CSS attributes and their values, separated from each other by semicolons. The style declaration block is the portion of a style rule within curly braces in a CSS style sheet. The value of the HTML style attribute also constitutes a style declaration block.

The item( ) method and the length property allow you to loop through the names of all CSS attributes specified in this declaration block. In JavaScript, you can also simply treat the CSSStyleDeclaration object as an array and index it using square-bracket notation instead of calling the item( ) method explicitly. Once you have the names of the CSS attributes specified in this declaration, you can use other methods of this interface to query the values of those attributes. getPropertyValue( ) returns the value as a string, and getPropertyCSSValue( ) returns the attribute value as a CSSValue object. (Note that the DOM API refers to CSS style attributes as "properties." I use the term "attributes" here to avoid confusing them with JavaScript object properties.)

In most web browsers, every object that implements CSSStyleDeclaration also implements the CSS2Properties interface, which defines an object property for each CSS attribute defined by the CSS2 specification. You can read and write the values of these convenience properties instead of calling getPropertyValue( ) and setProperty( ).

See Also

CSS2Properties

Type of

CSSFontFaceRule.style, CSSPageRule.style, CSSStyleRule.style, HTMLElement.style

Returned by

Document.getOverrideStyle( ), AbstractView.getComputedStyle( )

CSSValuethe value of a CSS style attribute

Availability

DOM Level 2 CSS

Subinterfaces

CSSPrimitiveValue, CSSValueList

Constants

The following constants specify the valid values for the cssValueType property:

unsigned short CSS_INHERIT = 0
This constant represents the special value "inherit", which means that the actual value of the CSS style attribute is inherited. The cssText property is "inherit" in this case.

unsigned short CSS_PRIMITIVE_VALUE = 1
The value is a primitive value. This CSSValue object also implements the more specific CSSPrimitiveValue subinterface.

unsigned short CSS_VALUE_LIST = 2
The value is a compound value consisting of a list of values. This CSSValue object also implements the more specific CSSValueList subinterface and behaves as an array of CSSValue objects.

unsigned short CSS_CUSTOM = 3
This constant is defined to allow extensions to the CSS object model. It specifies that this CSSValue represents a value of some type that is not defined by the CSS or DOM standards. If you are working with an implementation that supports such extensions, the CSSValue object may also implement some other interface (such as the SVGColor interface defined by the Scalable Vector Graphics standard) that you can use.

Properties

String cssText
The textual representation of the value. Setting this property may throw a DOMException. A code of SYNTAX_ERR indicates that the new value does not follow legal CSS syntax. A code of INVALID_MODIFICATION_ERR specifies that you tried to set a value of a different type than the original value. A code of NO_MODIFICATION_ALLOWED_ERR indicates that the value is read-only.

readonly unsigned short cssValueType
The kind of value this object represents. The four legal values of this property are defined by the previously listed constants.

Description

This interface represents the value of a CSS attribute. The cssText property gives the value in textual form. If the cssValueType property is CSSValue.CSS_PRIMITIVE_VALUE, this CSSValue object also implements the more specific CSSPrimitiveValue interface. If cssValueType is CSSValue.CSS_VALUE_LIST, this CSSValue represents a list of values and also implements the CSSValueList interface.

See Also

CSSPrimitiveValue, CSSValueList

Returned by

CSSStyleDeclaration.getPropertyCSSValue( ), CSSValueList.item( )

Documentan HTML or XML document

Availability

DOM Level 1 Core

Inherits from/Overrides

Node Figure Document

Subinterfaces

HTMLDocument

Also Implements

DocumentCSS
If the implementation supports the CSS module, the object that implements this Document interface also implements the DocumentCSS interface and its getOverrideStyle( ) method.

DocumentEvent
If the implementation supports the Events module, the object that implements this Document interface also implements the DocumentEvent interface and its createEvent( ) method.

DocumentRange
If the implementation supports the Range module, the object that implements this Document interface also implements the DocumentRange interface and its createRange( ) method.

DocumentStyle
If the implementation supports the StyleSheets module, the object that implements this Document interface also implements the DocumentStyle interface and its styleSheets property.

DocumentTraversal
If the implementation supports the Traversal module, the object that implements this Document interface also implements the DocumentTraversal interface and its createNodeIterator( ) and createTreeWalker( ) methods.

DocumentView
If the implementation supports the Views module, the object that implements this Document interface also implements the DocumentView interface and its defaultView property.

Because these interfaces define commonly implemented additions to the Document interface, their properties and methods are listed and documented here, as if they were directly part of the Document interface.

Properties

readonly AbstractView defaultView [DOM Level 2 Views]
The default view of this document. In a web-browser environment, this property specifies the Window object (which implements the AbstractView interface) in which the document is displayed.

Note that this property is technically part of the DocumentView interface; it is defined by the Document object only in implementations that support the Views module.

readonly DocumentType doctype
For XML documents with a <!DOCTYPE> declaration, specifies a DocumentType node that represents the document's DTD. For HTML documents and for XML documents with no <!DOCTYPE>, this property is null. Note that the property is read-only, and the node to which it refers is also read-only.

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

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

readonly StyleSheetList styleSheets [DOM Level 2 StyleSheets]
A collection of objects representing all style sheets embedded in or linked into a document. In HTML documents, this includes style sheets defined with <link> and <style> tags.

Note that this property is technically part of the DocumentStyle interface; it is defined by the Document object only in implementations that support the StyleSheets module.

Methods

createAttribute( )
Creates a new Attr node with the specified name.

createAttributeNS( ) [DOM Level 2]
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( ) [DOM Level 2]
Creates a new Element node with the specified tag name and namespace.

createEntityReference( )
Creates a new EntityReference node that refers to an entity with the specified name. If the DocumentType object for this document defines an Entity with that name, the newly created EntityReference node is given the same read-only children that the Entity node has.

createEvent( ) [DOM Level 2 Events]
Creates a new synthetic Event object of the named type. Technically, this method is defined by the DocumentEvent interface; it is implemented by the Document object only in implementations that support the Events module.

createNodeIterator( ) [DOM Level 2 Traversal]
Creates a NodeIterator object. This method is technically part of the DocumentTraversal interface; it is implemented by the Document object only in implementations that support the Traversal module.

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

createRange( ) [DOM Level 2 Range]
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.

createTreeWalker( ) [DOM Level 2 Traversal]
Creates a TreeWalker object. This method is technically part of the DocumentTraversal interface; it is implemented by the Document object only in implementations that support the Traversal module.

getElementById( ) [DOM Level 2]
Returns a descendant Element of this document that has the specified value for its id attribute, or null if no such Element exists in the document.

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

getElementsByTagNameNS( ) [DOM Level 2]
Returns an array of all Element nodes that have the specified tag name and namespace.

getOverrideStyle( ) [DOM Level 2 CSS]
Gets the CSS override style information for the specified Element (and an optional named pseudoelement). This method is technically part of the DocumentCSS interface; it is implemented by the Document object only in implementations that support the CSS module.

importNode( ) [DOM Level 2]
Makes a copy of a node from some other document that is suitable for insertion into this document.

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 are used to 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.

Contrast this Document object to the Document object documented in the client-side reference section of this book. The Level 0 properties and methods of that client-side Document object are formally defined by the DOM standard in the HTMLDocument interface. See HTMLDocument in this reference section for the DOM equivalent of the traditional client-side JavaScript Document object.

The Document interface is defined by the Core module of the DOM Level 2 specification. A number of the other modules define "add-on" interfaces that are intended to be implemented by the same object that implements the Document interface. For example, if an implementation supports the CSS module, the object that implements this interface also implements the DocumentCSS interface. In JavaScript, the properties and methods of these add-on interfaces can be used as if they were defined by Document, and for that reason, those methods and properties are listed here. See the earlier Section section for a full list of the add-on interfaces for Document.

See Also

HTMLDocument

Type of

AbstractView.document, HTMLFrameElement.contentDocument, HTMLIFrameElement.contentDocument, HTMLObjectElement.contentDocument, Node.ownerDocument

Returned by

DOMImplementation.createDocument( )

Document.createEvent( )create an Event object

Availability

DOM Level 2 Events

Synopsis

Event createEvent(String eventType)
    throws DOMException;

Arguments

eventType
The name of the event module for which an Event object is desired. See the Section section for a list of valid event types.

Returns

A newly created Event object of the specified type.

Throws

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

Description

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

eventType argument

Event interface

Initialization method

HTMLEvents

Event

initEvent( )

MouseEvents

MouseEvent

initMouseEvent( )

UIEvents

UIEvent

initUIEvent( )

MutationEvents

MutationEvent

initMutationEvent( )

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 DocumentEvent interface. If an implementation supports the Events module, the Document object always implements the DocumentEvent interface and supports this method.

See Also

Event, MouseEvent, MutationEvent, UIEvent

Document.getElementById( )find an element with the specified unique ID

Availability

DOM Level 2 Core; in DOM Level 1, defined by HTMLDocument

Synopsis

Element getElementById(String elementId);

Arguments

elementId
The value of the id attribute of the desired element.

Returns

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

Description

This method searches the document for an Element node with an id attribute whose value is elementId, and returns that Element. If no such Element is found, it returns null. The value of the id attribute is intended to be unique within a document, and if this method finds more than one Element with the specified elementId, it may return one at random or it may return null.

In HTML documents, this method always searches for attributes named id. In XML documents, however, it searches for any attribute whose type is id, regardless of what the attribute name is. If XML attribute types are not known (because, for example, the XML parser could not locate the document's DTD), this method always returns null.

This is an important and commonly used method since it provides a simple way to obtain the Element object that represents a specific document element. Note that it provides functionality similar to the nonstandard document.all[] array defined by Internet Explorer 4 and later. Finally, note that the name of this method ends with "Id", not with "ID"; be careful not to misspell it.

See Also

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

Document.getElementsByTagName( )return all Element nodes with the specified name

Availability

DOM Level 1 Core

Synopsis

Node[] getElementsByTagName(String tagname);

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.

Returns

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

Description

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

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

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

Example

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

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

See Also

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

DocumentCSSsee Document

DocumentEventsee Document

DocumentRangesee Document

DocumentStylesee Document

DocumentTraversalsee Document

DocumentTypethe DTD of an XML document

Availability

DOM Level 1 XML

Inherits from/Overrides

Node Figure DocumentType

Properties

readonly NamedNodeMap entities
This NamedNodeMap is a list of Entity objects declared in the DTD and allows Entity objects to be queried by name. Note that XML parameter entities are not included. This NamedNodeMap is immutable -- its contents may not be altered.

readonly String internalSubset [DOM Level 2]
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 NamedNodeMap notations
A NamedNodeMap that contains Notation objects representing all notations declared in the DTD. It also allows Notation objects to be looked up by notation name. This NamedNodeMap is immutable -- its contents may not be altered.

readonly String publicId [DOM Level 2]
The public identifier of the external subset of the DTD, or null if none was specified.

readonly String systemId [DOM Level 2]
The system identifier of the external subset of the DTD, or null if none was 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.

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

See Also

Document, Entity, Notation

Type of

Document.doctype

Passed to

DOMImplementation.createDocument( )

Returned by

DOMImplementation.createDocumentType( )

DocumentViewsee Document

DOMExceptionsignals exceptions or errors for core DOM objects

Availability

DOM Level 1 Core

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. Entity, EntityReference, and Notation nodes, and all of their descendants, are read-only.

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, such as an Entity node or one of its descendants. 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 having to do with events and event handling cause an EventException object to be thrown, and exceptions involving the DOM Range module cause a RangeException to be thrown.

See Also

EventException, RangeException

DOMImplementation.createDocument( )create a new Document and the specified root element

Availability

DOM Level 2 Core

Synopsis

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

Arguments

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

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

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

Returns

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

Throws

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

INVALID_CHARACTER_ERR
qualifiedName contains an illegal character.

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

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

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

Description

This method creates a new 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. Use createHTMLDocument( ) to create a new HTML document.

See Also

DOMImplementation.createDocumentType( ), DOMImplementation.createHTMLDocument( )

DOMImplementation.hasFeature( )determine whether the implementation supports a feature

Availability

DOM Level 1 Core

Synopsis

boolean hasFeature(String feature, 
                   String version);

Arguments

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

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

Returns

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

Description

The W3C DOM standard is modular, and implementations are not required to implement all modules or features of the standard. This method is used to test 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 style sheets are implemented.

CSS

Interfaces that are specific to CSS style sheets 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 Traversal API
if (document.implementation &&
    document.implementation.hasFeature &&
    document.implementation.hasFeature("Traversal", "2.0")) {
  // If so, use it here...
}
else {
  // If not, traverse the document some other way
} 

See Also

Node.isSupported( )

DOMImplementationCSSsee DOMImplementation

Elementan HTML or XML element

Availability

DOM Level 1 Core

Inherits from/Overrides

Node Figure Element

Subinterfaces

HTMLElement

Properties

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

Methods

getAttribute( )
Returns the value of a named attribute as a string.

getAttributeNS( ) [DOM Level 2]
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( ) [DOM Level 2]
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( ) [DOM Level 2]
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( ) [DOM Level 2]
Returns true if this element has an attribute with the specified name, or false otherwise. Note that this method returns true if the named attribute is explicitly specified in the document source or if the document's DTD specifies a default value for the named attribute.

hasAttributeNS( ) [DOM Level 2]
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.

removeAttributeNS( ) [DOM Level 2]
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.

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.

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.

setAttributeNS( ) [DOM Level 2]
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.

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( ) [DOM Level 2]
Like setAttributeNode( ), but this method is suitable for use with nodes returned by Document.createAttributeNS( ). 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 getElementsByTagName( ) method provides a powerful way to locate element descendants of a given element that have a specified tag name. The various other methods of this interface provide access to the attributes of the element. If you give an element a unique identifier using the id attribute in your document source, you can then easily locate the Element node that represents that document element with the useful Document.getElementById( ) method. To create a new Element node for insertion into a document, use Document.createElement( ).

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'll 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.

See Also

HTMLElement, Node

Type of

Attr.ownerElement, Document.documentElement

Passed to

Document.getOverrideStyle( ), AbstractView.getComputedStyle( )

Returned by

Document.createElement( ), Document.createElementNS( ), Document.getElementById( )

Element.getAttribute( )return the string value of a named attribute

Availability

DOM Level 1 Core

Synopsis

String getAttribute(String name);

Arguments

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

Returns

The string value of the named attribute. If the attribute does not have a value specified in the document and does not have a default value specified by the document type, the return value is the empty string ("").

Description

getAttribute( ) returns the value of a named attribute of an element. In HTML documents, attribute values are always strings, and this method returns the complete attribute value. Note that the objects that represent HTML elements also implement the HTMLElement interface and one of its tag-specific subinterfaces. Therefore, all standard attributes of standard HTML tags are also available directly as properties of the Element object.

In XML documents, attribute values are not available directly as element properties and must be looked up by calling a method. For many XML documents, getAttribute( ) is a suitable method for doing this. Note, however that in XML attributes may contain entity references, and in order to obtain complete details about such attributes, you must use getAttributeNode( ) to obtain the Attr node whose subtree represents the complete attribute value. The Attr nodes for an element are also available in an attributes[] array inherited from the Node interface. For XML documents that use namespaces, you may need to use getAttributeNS( ) or getAttributeNodeNS( ).

Example

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

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

See Also

Element.getAttributeNode( ), Reference

Element.setAttribute( )create or change an attribute of an element

Availability

DOM Level 1 Core

Synopsis

void setAttribute(String name, 
                  String value) 
    throws DOMException;

Arguments

name
The name of the attribute that is to be created or modified.

value
The string value of the attribute.

Throws

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

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

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

Description

This method sets the specified attribute to the specified value. If no attribute by that name already exists, a new one is created. Note that Element objects that represent the tags of an HTML document also implement the HTMLElement interface and (usually) one of its tag-specific subinterfaces. As a shortcut, these interfaces define properties that correspond to the standard HTML attributes for each tag, and it is usually easier to set an HTML attribute simply by setting the appropriate property.

The value argument is a plain string. If you are working with an XML document and need to include an entity reference in an attribute value, use setAttributeNode( ).

Example

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

See Also

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

Element.setAttributeNS( )create or change an attribute with a namespace

Availability

DOM Level 2 Core

Synopsis

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

Arguments

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

qualifiedName
The name of the attribute, specified as a namespace prefix followed by a colon and a name within the namespace.

value
The new value of the attribute.

Throws

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

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

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

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

NOT_SUPPORTED_ERR
The DOM implementation does not support XML documents.

Description

This method is like setAttribute( ), except that the attribute to be created or set is specified by a namespace URI and a qualified name that consists of a namespace prefix, a colon, and a local name within the namespace. In addition to letting you change the value of an attribute, this method allows you to change the namespace prefix of an attribute.

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

See Also

Element.setAttribute( ), Element.setAttributeNode( )

ElementCSSInlineStylesee HTMLElement

Entityan entity in an XML DTD

Availability

DOM Level 1 XML

Inherits from/Overrides

Node Figure Entity

Properties

readonly String notationName
The notation name (for unparsed entities), or null if there is none (for parsed entities). See the notations property of DocumentType for a way to look up a Notation node by name.

readonly String publicId
The public identifier for this entity, or null if none was specified.

readonly String systemId
The system identifier for this entity, or null if none was specified.

Description

This infrequently used interface represents an entity in an XML document type definition (DTD). It is never used with HTML documents.

The name of the entity is specified by the nodeName property inherited from the Node interface. The entity content is represented by the child nodes of the Entity node. Note that Entity nodes and their children are not part of the document tree (and the parentNode property of an Entity is always null). Instead, a document may contain one or more references to an entity; see EntityReference for more information.

Entities are defined in the DTD of a document, either as part of an external DTD file or as part of an "internal subset" that defines local entities specific to the current document. The DocumentType interface has an entities property that allows Entity nodes to be looked up by name. This is the only way to obtain a reference to an Entity node; because they are part of the document type, Entity nodes never appear as part of the document itself.

Entity nodes and all of their descendants are read-only and cannot be edited or modified in any way.

See Also

DocumentType, EntityReference, Notation

EntityReferencea reference to an entity defined in an XML DTD

Availability

DOM Level 1 XML

Inherits from/Overrides

Node Figure EntityReference

Description

This infrequently used interface represents a reference from an XML document to an entity defined in the document's DTD. Character entities and predefined entities such as &lt; are always expanded in XML and HTML documents, and EntityReference nodes never appear in HTML documents, so programmers working exclusively with HTML documents never need to use this interface. Note also that some XML parsers expand all entity references. Documents created by such parsers do not contain EntityReference nodes.

This interface defines no properties or methods of its own. The inherited nodeName property specifies the name of the referenced entity. The entities property of the DocumentType interface provides a way to look up the Entity object with that name. Note, however, that the DocumentType may not contain an Entity node with the specified name (because, for example, nonvalidating XML parsers are not required to parse the "external subset" of the DTD). In this case, the EntityReference has no children. On the other hand, if the DocumentType does contain an Entity node with the specified name, the child nodes of the EntityReference are copies of the child nodes of the Entity node and represent the content of the entity. Like Entity nodes, EntityReference nodes and their descendants are read-only and cannot be edited or modified.

See Also

DocumentType

Returned by

Document.createEntityReference( )

Eventinformation about an event

Availability

DOM Level 2 Events

Subinterfaces

MutationEvent, UIEvent

Constants

These constants are the legal values of the eventPhase property; they represent the current phase of event propagation for this event:

unsigned short CAPTURING_PHASE = 1
The event is in its capturing phase.

unsigned short AT_TARGET = 2
The event is being handled by its target node.

unsigned short BUBBLING_PHASE = 3
The event is bubbling.

Properties

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

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

readonly EventTarget currentTarget
The Document node that is currently handling this event. During capturing and bubbling, this is different from target. Note that all nodes implement the EventTarget interface, and the currentTarget property may refer to any node; it is not restricted to Element nodes.

readonly unsigned short eventPhase
The current phase of event propagation. The three previous constants define the legal values for this property.

readonly EventTarget target
The target node for this event; i.e., the node that generated the event. Note that this may be any node; it is not restricted to Element nodes.

readonly Date timeStamp
The date and time at which the event occurred (or, technically, at which the Event object was created). Implementations are not required to provide valid time data in this field, and if they do not, the getTime( ) method of this Date object should return 0. See the Date object in the core reference section 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". See Table 19-3 in Chapter 19 for a complete list of event types defined by the DOM standard.

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 will be called, but the event will not be dispatched to any other nodes.

Description

This interface represents an event that occurred on some node of the document and contains details about the event. Various subinterfaces of Event define additional properties that provide details pertinent to specific types of events.

Many event types use a more specific subinterface of Event to describe the event that has occurred. However, the event types defined by the HTMLEvents module use the Event interface directly. These event types are: "abort", "blur", "change", "error", "focus", "load", "reset", "resize", "scroll", "select", "submit", and "unload".

See Also

EventListener, EventTarget, MouseEvent, UIEvent; Chapter 19

Passed to

EventTarget.dispatchEvent( )

Returned by

Document.createEvent( )

EventListeneran event handler function DOM Level 2 Events

Availability

Methods

handleEvent( )
In languages such as Java that do not allow functions to be passed as arguments to other functions, you define an event listener by defining a class that implements this interface and includes an implementation for this handleEvent( ) method. When an event occurs, the system calls this method and passes in an Event object that describes the event.

In JavaScript, however, you define an event handler simply by writing a function that accepts an Event object as its argument. The name of the function does not matter, and the function itself is used in place of an EventListener object. See the Section section.

Description

This interface defines the structure of an event listener or event handler. In languages such as Java, an event listener is an object that defines a method named handleEvent( ) that takes an Event object as its sole argument. In JavaScript, however, any function that expects a single Event argument, or a function that expects no argument, can serve as an event listener.

Example

// This function is an event listener for a "submit" event
function submitHandler(e) {
  // Call a form-validation function defined elsewhere
  if (!validate(e.target))
      e.preventDefault( );  // If validation fails, don't submit form
}

// We might register the event listener above like this
document.forms[0].addEventListener("submit", submitHandler, false);

See Also

Event, EventTarget; Chapter 19

Passed to

EventTarget.addEventListener( ), EventTarget.removeEventListener( )

EventTarget.addEventListener( )register an event handler

Availability

DOM Level 2 Events

Synopsis

void addEventListener(String type,
                      EventListener listener, 
                      boolean useCapture);

Arguments

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

listener
The event listener function that will be invoked when an event of the specified type is dispatched to this Document node.

useCapture
If true, the specified listener is to be invoked only during the capturing phase of event propagation. The more common value of false means that the listener will not be invoked during the capturing phase but instead will be 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 will be 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 Document node is duplicated with Node.cloneNode( ) or Document.importNode( ), the event listeners registered for the original node are not copied.

See Also

Event, EventListener; Chapter 19

HTMLAnchorElementa hyperlink or anchor in an HTML document

Availability

DOM Level 1 HTML

Inherits from/Overrides

Node Figure Element Figure HTMLElement Figure HTMLAnchorElement

Properties

This interface defines the properties in the following table, which correspond to the HTML attributes of the <a> tag.

Property

Attribute

Description

String accessKey

accesskey

Keyboard shortcut

String charset

charset

Encoding of the destination document

String coords

coords

Used inside <map> elements

String href

href

URL of the hyperlink

String hreflang

hreflang

Language of the linked document

String name

name

Name of the anchor

String rel

rel

Link type

String rev

rev

Reverse link type

String shape

shape

Used inside <map> elements

long tabIndex

tabindex

Link's position in tabbing order

String target

target

Name of the frame or window in which the destination document is to be displayed

String type

type

Content type of the destination document

Methods

blur( )
Takes keyboard focus away from the link.

focus( )
Scrolls the document so the anchor or link is visible and gives keyboard focus to the link.

Description

This interface represents an <a> tag in an HTML document. href, name, and target are the key properties, representing the most commonly used attributes of the tag.

HTMLAnchorElement objects can be obtained from the links and anchors HTMLCollection properties of the HTMLDocument interface.

Example

// Get the destination URL of first the hyperlink in the document
var url = document.links[0].href;
// Scroll the document so the anchor named "_bottom_" is visible
document.anchors['_bottom_'].focus( );

See Also

Link and Anchor objects in the client-side reference section

HTMLBodyElementthe <body> of an HTML document

Availability

DOM Level 1 HTML

Inherits from/Overrides

Node Figure Element Figure HTMLElement Figure HTMLBodyElement

Properties

deprecated String aLink
The value of the alink attribute. Specifies the color of "active" links; that is, the color of a link when the mouse has been pressed over it but has not yet been released.

deprecated String background
The value of the background attribute. Specifies the URL of an image to use as a background texture for the document.

deprecated String bgColor
The value of the bgcolor attribute. Specifies the background color of the document.

deprecated String link
The value of the link attribute. Specifies the normal color of unvisited hyperlinks.

deprecated String text
The value of the text attribute. Specifies the foreground color (the color of text) for the document.

deprecated String vLink
The value of the vlink attribute. Specifies the normal color of "visited" hyperlinks that have already been followed.

Description

The HTMLBodyElement interface represents the <body> tag of a document. All HTML documents have a <body> tag, even if it does not explicitly appear in the document source. You can obtain the HTMLBodyElement of a document through the body property of the HTMLDocument interface.

The properties of this object specify default colors and images for the document. Although these properties represent the values of <body> attributes, the Level 0 DOM made these same values accessible through properties (with different names) of the Document object. See the Document object in the client-side reference section of this book for details.

Although these color and image properties belong more appropriately to the HTMLBodyElement interface than they do to the Document object, note that they are all deprecated because the HTML 4 standard deprecates the <body> attributes that they represent. The preferred way to specify colors and images for a document is using CSS styles.

Example

document.body.text = "#ff0000";         // Display text in bright red
document.fgColor = "#ff0000";           // Same thing using old DOM Level 0 API
document.body.style.color = "#ff0000";  // Same thing using CSS styles

See Also

Document object in the client-side reference section

HTMLCollectionarray of HTML elements accessible by position or name

Availability

DOM Level 1 HTML

Properties

readonly unsigned long length
The number of elements in the collection.

Methods

item( )
Returns the element at the specified position in the collection. You can also simply specify the position within array brackets instead of calling this method explicitly.

namedItem( )
Returns the element from the collection that has the specified value for its id or name attribute, or null if there is no such element. You may 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 the elements by their position in the document or by their id or name attribute. In JavaScript, HTMLCollection objects behave like read-only arrays, and you may 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 interface (which standardizes the DOM Level 0 Document object) are HTMLCollection objects, which provide convenient access to document elements such as forms, images, and links. The HTMLCollection object also provides a convenient way to traverse the elements of an HTML form, the rows of an HTML table, the cells of a table row, and the areas of a client-side image map.

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.

Example

var c = document.forms;        // This is an HTMLCollection of form elements
var firstform = c[0];          // It can be used like a numeric array
var lastform = c[c.length-1];  // The length property gives the number of elements
var address = c["address"];    // It can be used like an associative array
var address = c.address;       // JavaScript allows this notation, too

See Also

NodeList

Type of

HTMLDocument.anchors, HTMLDocument.applets, HTMLDocument.forms, HTMLDocument.images, HTMLDocument.links, HTMLFormElement.elements, HTMLMapElement.areas, HTMLSelectElement.options, HTMLTableElement.rows, HTMLTableElement.tBodies, HTMLTableRowElement.cells, HTMLTableSectionElement.rows

HTMLDocumentthe root of an HTML document tree

Availability

DOM Level 1 HTML

Inherits from/Overrides

Node Figure Document Figure HTMLDocument

Properties

readonly HTMLCollection anchors
An array (HTMLCollection) of all anchors in the document. For compatibility with The Level 0 DOM, this array contains only <a> elements that have a name attribute specified; it does not include anchors created with an id attribute.

readonly HTMLCollection applets
An array (HTMLCollection) of all applets in a document. These include applets defined with an <object> tag and all <applet> tags.

HTMLElement body
A convenience property that refers to the HTMLBodyElement that represents the <body> tag of this document. For documents that define framesets, this property refers to the outermost <frameset> tag.

String cookie
Allows cookies to be queried and set for this document. See Document.cookie in the client-side reference section.

readonly String domain
The domain name of the server from which the document was loaded, or null if there is none. Contrast with the read/write Document.domain property in the client-side reference section.

readonly HTMLCollection forms
An array (HTMLCollection) of all HTMLFormElement objects in the document.

readonly HTMLCollection images
An array (HTMLCollection) of all <img> tags in the document. Note that for compatibility with the Level 0 DOM, images defined with an <object> tag are not included in this collection.

readonly HTMLCollection links
An array (HTMLCollection) of all hyperlinks in the document. These include all <a> tags that have an href attribute, and all <area> tags.

readonly String referrer
The URL of the document that linked to this document, or null if this document was not accessed through a hyperlink.

String title
The contents of the <title> tag for this document.

readonly String URL
The URL of the document.

Methods

close( )
Closes a document stream opened with the open( ) method, forcing any buffered output to be displayed.

getElementById( )
Returns the element with the specified id. In the Level 2 DOM, this method is inherited from the Document interface.

getElementsByName( )
Returns an array of nodes (a NodeList) of all elements in the document that have a specified value for their name attribute.

open( )
Opens a stream to which new document contents may be written. Note that this method erases any current document content.

write( )
Appends a string of HTML text to an open document.

writeln( )
Appends a string of HTML text followed by a newline character to an open document.

Description

This interface extends Document and defines HTML-specific properties and methods that provide compatibility with the DOM Level 0 Document object (see the Document object in the client-side reference section). Note that HTMLDocument does not have all the properties of the Level 0 Document object. The properties that specify document colors and background images have been renamed and moved to the HTMLBodyElement.

Finally, note that in the Level 1 DOM, HTMLDocument defines a 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 the Document.getElementById( ) entry in this reference section for details.

See Also

Document.getElementById( ), HTMLBodyElement; Document object in the client-side reference section

Returned by

HTMLDOMImplementation.createHTMLDocument( )

HTMLDocument.getElementById( )see Document.getElementById( )

HTMLDocument.open( )begin a new document, erasing the current one

Availability

DOM Level 1 HTML

Synopsis

void open( );

Description

This method erases the current HTML document and begins a new one, which may be written to with the write( ) and writeln( ) methods. After calling open( ) to begin a new document and write( ) to specify document content, you must always remember to call close( ) to end the document and force its content to be displayed.

This method should not be called by a script or event handler that is part of the document being overwritten, since the script or handler will itself be overwritten.

See Document.open( ) in the client-side reference section, but note that this standardized version of that method can be used only to create new HTML documents and does not accept the optional mimetype argument that the Level version does.

Example

var w = window.open("");          // Open a new window
var d = w.document;               // Get its HTMLDocument object
d.open();                         // Open the document for writing
d.write("<h1>Hello world</h1>");  // Output some HTML to the document
d.close();                        // End the document and display it

See Also

HTMLDocument.close( ), HTMLDocument.write( ); Document.open( ) in the client-side reference section

HTMLDOMImplementationsee DOMImplementation

HTMLElementthe base interface for all HTML elements

Availability

DOM Level 1 HTML

Inherits from/Overrides

Node Figure Element Figure HTMLElement

Also Implements

ElementCSSInlineStyle
If the implementation supports CSS style sheets, all objects that implement this interface also implement the ElementCSSInlineStyle interface. Because CSS support is quite common in web browsers, the style property defined by that interface is included here for convenience.

Subinterfaces

 

HTMLAnchorElement

 
 

HTMLAppletElement

 
 

HTMLAreaElement

 
 

HTMLBRElement

 
 

HTMLBaseElement

 
 

HTMLBaseFontElement

 
 

HTMLBodyElement

 
 

HTMLButtonElement

 
 

HTMLDListElement

 
 

HTMLDirectoryElement

 
 

HTMLDivElement

 
 

HTMLFieldSetElement

 
 

HTMLFontElement

 
 

HTMLFormElement

 
 

HTMLFrameElement

 
 

HTMLFrameSetElement

 
 

HTMLHRElement

 
 

HTMLHeadElement

 
 

HTMLHeadingElement

 
 

HTMLHtmlElement

 
 

HTMLIFrameElement

 
 

HTMLImageElement

 
 

HTMLInputElement

 
 

HTMLIsIndexElement

 
 

HTMLLIElement

 
 

HTMLLabelElement

 
 

HTMLLegendElement

 
 

HTMLLinkElement

 
 

HTMLMapElement

 
 

HTMLMenuElement

 
 

HTMLMetaElement

 
 

HTMLModElement

 
 

HTMLOListElement

 
 

HTMLObjectElement

 
 

HTMLOptGroupElement

 
 

HTMLOptionElement

 
 

HTMLParagraphElement

 
 

HTMLParamElement

 
 

HTMLPreElement

 
 

HTMLQuoteElement

 
 

HTMLScriptElement

 
 

HTMLSelectElement

 
 

HTMLStyleElement

 
 

HTMLTableCaptionElement

 
 

HTMLTableCellElement

 
 

HTMLTableColElement

 
 

HTMLTableElement

 
 

HTMLTableRowElement

 
 

HTMLTableSectionElement

 
 

HTMLTextAreaElement

 
 

HTMLTitleElement

 
 

HTMLUListElement

 
   

Properties

readonly CSS2Properties style
The value of the style attribute that specifies inline CSS styles for this element. This property is not actually defined directly by the HTMLElement interface; instead, it is defined by the ElementCSSInlineStyle interface. If a browser supports CSS style sheets, all of its HTMLElement objects implement ElementCSSInlineStyle and define this style property. The value of this property is an object that implements the CSSStyleDeclaration interface and the (more commonly used) CSS2Properties interface.

String className
The value of the class attribute of the element, which specifies the name of a CSS class. Note that this property is not named "class" because that name is a reserved word in JavaScript.

String dir
The value of the dir attribute of the element, which specifies the text direction for the document.

String id
The value of the id attribute. No two elements within the same document should have the same value for id.

String lang
The value of the lang attribute, which specifies the language code for the document.

String title
The value of the title attribute, which specifies descriptive text suitable for display in a "tooltip" for the element.

Description

This interface defines properties that represent the attributes shared by all HTML elements. All HTML elements implement this interface, and most implement a tag-specific subinterface that defines properties for each of that tag's attributes. In addition to the properties listed here, see the HTMLElement reference page in the client-side reference section for a list of DOM Level 0 event handler properties that are supported by all HTML elements in a document.

Some HTML tags do not allow any attributes other than the universal attributes allowed on all HTML tags and represented by the properties of HTMLElement. These tags do not have their own tag-specific subinterface, and elements of this type in the document tree are represented by an HTMLElement object. The tags without a tag-specific interface of their own are the following:

<abbr>

<acronym>

<address>

<b>

<bdo>

<big>

<center>

<cite>

<code>

<dd>

<dfn>

<dt>

<em>

<i>

<kbd>

<noframes>

<noscript>

<s>

<samp>

<small>

<span>

<strike>

<strong>

<sub>

<sup>

<tt>

<u>

<var>

As you can see from the earlier "Subinterfaces" section, there are many HTML tags that do have tag-specific subinterfaces. 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., className). When an HTML attribute name is a reserved word in Java or JavaScript, the property name is changed slightly. For example, the class attribute of all HTML tags becomes the className property of the HTMLElement interface because class is a reserved word. Similarly, 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 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. 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 define methods and interfaces that represent certain particularly important tags, such as the <body> tag. These interfaces are marked with a * in the table, and you can look them up in this reference section for further details.

HTML tag

DOM interface, properties, and methods

all tags

HTMLElement*: id, title, lang, dir, className

<a>

HTMLAnchorElement*: accessKey, charset, coords, href, hreflang, name, rel, rev, shape, [long] tabIndex, target, type, blur( ), focus( )

<applet>

HTMLAppletElement**: align**, alt**, archive**, code**, codeBase**, height**, hspace**, name**, object**, vspace**, width**

<area>

HTMLAreaElement: accessKey, alt, coords, href, [boolean] noHref, shape, [long] tabIndex, target

<base>

HTMLBaseElement: href, target

<basefont>

HTMLBaseFontElement**: color**, face**, size**

<blockquote>, <q>

HTMLQuoteElement: cite

<body>

HTMLBodyElement*: aLink**, background**, bgColor**, link**, text**, vLink**

<br>

HTMLBRElement: clear**

<button>

HTMLButtonElement: [readonly HTMLFormElement] form, accessKey, [boolean] disabled, name, [long] tabIndex, [readonly] type, value

<caption>

HTMLTableCaptionElement*: align**

<col>, <colgroup>

HTMLTableColElement*: align, ch, chOff, [long] span, vAlign, width

<del>, <ins>

HTMLModElement: cite, dateTime

<dir>

HTMLDirectoryElement**: [boolean] compact**

<div>

HTMLDivElement: align**

<dl>

HTMLDListElement: [boolean] compact**

<fieldset>

HTMLFieldSetElement: [readonly HTMLFormElement] form

<font>

HTMLFontElement**: color**, face**, size**

<form>

HTMLFormElement*: [readonly HTMLCollection] elements, [readonly long] length, name, acceptCharset, action, enctype, method, target, submit( ), reset( )

<frame>

HTMLFrameElement: frameBorder, longDesc, marginHeight, marginWidth, name, [boolean] noResize, scrolling, src, [readonly Document] contentDocument***

<frameset>

HTMLFrameSetElement: cols, rows

<h1>, <h2>, <h3>, <h4>, <h5>, <h6>

HTMLHeadingElement: align**

<head>

HTMLHeadElement: profile

<hr>

HTMLHRElement: align**, [boolean] noShade**, size**, width**

<html>

HTMLHtmlElement: version**

<iframe>

HTMLIFrameElement: align**, frameBorder, height, longDesc, marginHeight, marginWidth, name, scrolling, src, width, [readonly Document] contentDocument***

<img>

HTMLImageElement: align**, alt, [long] border**, [long] height, [long] hspace**, [boolean] isMap, longDesc, name, src, useMap, [long] vspace**, [long] width

<input>

HTMLInputElement*: defaultValue, [boolean] defaultChecked, [readonly HTMLFormElement] form, accept, accessKey, align**, alt, [boolean] checked, [boolean] disabled, [long] maxLength, name, [boolean] readOnly, size, src, [long] tabIndex, type, useMap, value, blur( ), focus( ), select( ), click( )

<ins>

See <del>

<isindex>

HTMLIsIndexElement**: [readonly HTMLFormElement] form, prompt**

<label>

HTMLLabelElement: [readonly HTMLFormElement] form, accessKey, htmlFor

<legend>

HTMLLegendElement: [readonly HTMLFormElement] form, accessKey, align**

<li>

HTMLLIElement: type**, [long] value**

<link>

HTMLLinkElement: [boolean] disabled, charset, href, hreflang, media, rel, rev, target, type

<map>

HTMLMapElement: [readonly HTMLCollection of HTMLAreaElement] areas, name

<menu>

HTMLMenuElement**: [boolean] compact**

<meta>

HTMLMetaElement: content, httpEquiv, name, scheme

<object>

HTMLObjectElement: code, align**, archive, border**, codeBase, codeType, data, [boolean] declare, height, hspace**, name, standby, [long] tabIndex, type, useMap, vspace**, width, [readonly Document] contentDocument***

<ol>

HTMLOListElement: [boolean] compact**, [long] start**, type**

<optgroup>

HTMLOptGroupElement: [boolean] disabled, label

<option>

HTMLOptionElement*: [readonly HTMLFormElement] form, [boolean] defaultSelected, [readonly] text, [readonly long] index, [boolean] disabled, label, [boolean] selected, value

<p>

HTMLParagraphElement: align**

<param>

HTMLParamElement: name, type, value, valueType

<pre>

HTMLPreElement: [long] width**

<q>

See <blockquote>

<script>

HTMLScriptElement: text, htmlFor, event, charset, [boolean] defer, src, type

<select>

HTMLSelectElement*: [readonly] type, [long] selectedIndex, value, [readonly long] length, [readonly HTMLFormElement] form, [readonly HTMLCollection of HTMLOptionElement] options, [boolean] disabled, [boolean] multiple, name, [long] size, [long] tabIndex, add( ), remove( ), blur( ), focus( )

<style>

HTMLStyleElement: [boolean] disabled, media, type

<table>

HTMLTableElement*: [HTMLTableCaptionElement] caption, [HTMLTableSectionElement] tHead, [HTMLTableSectionElement] tFoot, [readonly HTMLCollection of HTMLTableRowElement] rows, [readonly HTMLCollection of HTMLTableSectionElement] tBodies, align**, bgColor**, border, cellPadding, cellSpacing, frame, rules, summary, width, createTHead( ), deleteTHead( ), createTFoot( ), deleteTFoot( ), createCaption( ), deleteCaption( ), insertRow( ), deleteRow( )

<tbody>, <tfoot>, <thead>

HTMLTableSectionElement*: align, ch, chOff, vAlign, [readonly HTMLCollection of HTMLTableRowElement] rows, insertRow( ), deleteRow( )

<td>, <th>

HTMLTableCellElement*: [readonly long] cellIndex, abbr, align, axis, bgColor**, ch, chOff, [long] colSpan, headers, height**, [boolean] noWrap**, [long] rowSpan, scope, vAlign, width**

<textarea>

HTMLTextAreaElement*: defaultValue, [readonly HTMLFormElement] form, accessKey, [long] cols, [boolean] disabled, name, [boolean] readOnly, [long] rows, [long] tabIndex, [readonly] type, value, blur( ), focus( ), select( )

<tfoot>

See <tbody>

<th>

See <td>

<thead>

See <tbody>

<title>

HTMLTitleElement: text

<tr>

HTMLTableRowElement*: [readonly long] rowIndex, [readonly long] sectionRowIndex, [readonly HTMLCollection of HTMLTableCellElement] cells, align, bgColor**, ch, chOff, vAlign, insertCell( ), deleteCell( )

<ul>

HTMLUListElement: [boolean] compact**, type**

* Indicates interfaces documented in this book.

** Indicates deprecated elements and attributes.

*** Indicates attributes added in HTML DOM Level 2 working draft.

See Also

HTMLElement in the client-side reference section

Type of

HTMLDocument.body

Passed to

HTMLSelectElement.add( )

Returned by

HTMLTableElement.createCaption( ), HTMLTableElement.createTFoot( ), HTMLTableElement.createTHead( ), HTMLTableElement.insertRow( ), HTMLTableRowElement.insertCell( ), HTMLTableSectionElement.insertRow( )

HTMLFormElementa <form> in an HTML document

Availability

DOM Level 1 HTML

Inherits from/Overrides

Node Figure Element Figure HTMLElement Figure HTMLFormElement

Properties

readonly HTMLCollection elements
An array (HTMLCollection) of all elements in the form.

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

In addition to the properties above, HTMLFormElement also defines the properties in the following table, which correspond directly to HTML attributes.

Property

Attribute

Description

String acceptCharset

acceptcharset

Character sets the server can accept

String action

action

URL of the form handler

String enctype

enctype

Encoding of the form

String method

method

HTTP method used for form submission

String name

name

Name of the form

String target

target

Frame or window name for form submission results

Methods

reset( )
Resets all form elements to their default values.

submit( )
Submits the form.

Description

This interface 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.

See the Form object in the client-side reference section for more details.

See Also

Form object in the client-side reference section

Type of

HTMLButtonElement.form, HTMLFieldSetElement.form, HTMLInputElement.form, HTMLIsIndexElement.form, HTMLLabelElement.form, HTMLLegendElement.form, HTMLObjectElement.form, HTMLOptionElement.form, HTMLSelectElement.form, HTMLTextAreaElement.form

HTMLInputElementan input element in an HTML form

Availability

DOM Level 1 HTML

Inherits from/Overrides

Node Figure Element Figure HTMLElement Figure HTMLInputElement

Properties

String accept
A comma-separated list of MIME types that specify the types of files that may be uploaded when this is a FileUpload element. Mirrors the accept attribute.

String accessKey
The keyboard shortcut (which must be a single character) that a browser may use to transfer keyboard focus to this input element. Mirrors the accesskey attribute.

deprecated String align
The vertical alignment of this element with respect to the surrounding text, or the left or right float for the element. Mirrors the align attribute.

String alt
Alternate text to be displayed by browsers that cannot render this input element. Particularly useful when type is image. Mirrors the alt attribute.

boolean checked
For Radio and Checkbox input elements, specifies whether the element is "checked" or not. Setting this property changes the visual appearance of the input element. Mirrors the checked attribute.

boolean defaultChecked
For Radio and Checkbox elements, holds the initial value of the checked attribute as it appears in the document source. When the form is reset, the checked property is restored to the value of this property. Changing the value of this property changes the value of the checked property and the current checked state of the element.

String defaultValue
For Text, Password, and FileUpload elements, holds the initial value displayed by the element. When the form is reset, the element is restored to this value. Changing the value of this property also changes the value property and the currently displayed value.

boolean disabled
If true, the input element is disabled and is unavailable for user input. Mirrors the disabled attribute.

readonly HTMLFormElement form
The HTMLFormElement object representing the <form> element that contains this input element, or null if the input element is not within a form.

long maxLength
For Text or Password elements, specifies the maximum number of characters that the user will be allowed to enter. Note that this is not the same as the size property. Mirrors the maxlength attribute.

String name
The name of the input element, as specified by the name attribute.

boolean readOnly
If true, and this is a Text or Password element, the user is not allowed to enter text into the element. Mirrors the readonly attribute.

String size
For Text and Password elements, specifies the width of the element in characters. Mirrors the size attribute. See also maxLength.

String src
For input elements with a type of image, specifies the URL of the image to be displayed. Mirrors the src attribute.

long tabIndex
The position of this input element in the tabbing order. Mirrors the tabindex attribute.

String type
The type of the input element. The various types and their meanings are listed in the table in the "Description" section. Mirrors the type attribute.

String useMap
For elements with a type of image, 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 server-side script when the form is submitted. For Text, Password, and FileUpload elements, this property is the text contained by the input element. For Button, Submit, and Reset elements, this is the text that appears in the button. For security reasons, the value property of FileUpload elements may be read-only. Similarly, the value returned by this property for Password elements may not contain the user's actual input.

Methods

blur( )
Takes keyboard focus away from the element.

click( )
If this input element is a Button, a Checkbox, or a Radio, Submit, or Reset button, this method simulates a mouse-click on the element.

focus( )
Transfers keyboard focus to this input element.

select( )
If this input element is a Text, Password, or FileUpload element, 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 will be deleted and replaced with the newly typed character.

Description

This interface represents an <input> element that defines an HTML input element (typically in an HTML form). An HTMLInputElement can represent various types of input elements, depending on the value of its type property. The allowed values for this property and their meanings are shown in the following table.

Type

Input element type

button

Push button

checkbox

Checkbox element

file

FileUpload element

hidden

Hidden element

image

Graphical Submit button

password

Masked-text entry field for passwords

radio

Mutually exclusive Radio button

reset

Reset button

text (default value)

Single-line text entry field

submit

Submit button

See Chapter 15 for more information about HTML forms and form elements. Note also that each distinct type of form input element has its own reference page in the client-side reference section of this book.

See Also

HTMLFormElement, HTMLOptionElement, HTMLSelectElement, HTMLTextAreaElement; Chapter 15; the Input object in the client-side reference section, and also its subclasses (Button, Checkbox, FileUpload, Hidden, Password, Radio, Reset, Submit, and Text)

HTMLOptionElementan <option> in an HTML form

Availability

DOM Level 1 HTML

Inherits from/Overrides

Node Figure Element Figure HTMLElement Figure HTMLOptionElement

Properties

boolean defaultSelected
The initial value of the selected attribute of the <option> element. If the form is reset, the selected property is reset to the value of this property. Setting this property also sets the value of the selected property.

boolean disabled
If true, this option is disabled and the user is not allowed to select it. Mirrors the disabled attribute.

readonly HTMLFormElement form
A reference to the <form> element that contains this element.

readonly long index
The position of this <option> element within the <select> element that contains it.

String label
The text to be displayed for the option. Mirrors the label attribute. If this property is not specified, the plain-text content of the <option> element is used instead.

boolean selected
The current state of this option: if true, the option is selected. The initial value of this property comes from the selected attribute.

readonly String text
The plain text contained within the <option> element. This text appears as the label for the option.

String value
The value submitted with the form if this option is selected when form submission occurs. Mirrors the value attribute.

Description

This interface describes an <option> element within a <select> element.

See Also

HTMLFormElement, HTMLInputElement, HTMLSelectElement; Option and Select objects in the client-side reference section; Chapter 15

HTMLSelectElementa <select> element in an HTML form

Availability

DOM Level 1 HTML

Inherits from/Overrides

Node Figure Element Figure HTMLElement Figure HTMLSelectElement

Properties

boolean disabled
If true, the <select> element is disabled and the user may not interact with it. Mirrors the disabled attribute.

readonly HTMLFormElement form
The <form> element that contains this one.

readonly long length
The number of <option> elements contained by this <select> element. Same as options.length.

boolean multiple
If true, the <select> element allows multiple options to be selected. Otherwise, the selections are mutually exclusive and only one may be selected at a time. Mirrors the multiple attribute.

String name
The name of this form element. Mirrors the name attribute.

readonly HTMLCollection options
An array (HTMLCollection) of HTMLOptionElement objects that represent the <option> elements contained in this <select> element, in the order in which they appear.

long selectedIndex
The position of the selected option in the options array. If no options are selected, this property is -1. If multiple options are selected, this property returns the index of the first selected option.

long size
The number of options to display at once. If this property is 1, the <select> element will typically be displayed using a drop-down menu or list. If it is greater than 1, the <select> is typically displayed using a fixed-size list control, with a scrollbar if necessary. Mirrors the size attribute.

long tabIndex
The position of this element in the tabbing order. Mirrors the tabindex attribute.

readonly String type
If multiple is true, this property is "select-multiple". Otherwise, it is "select-one".

Methods

add( )
Inserts a new HTMLOptionElement into the options array, either by appending it at the end of the array or by inserting it before another specified option.

blur( )
Takes keyboard focus away.

focus( )
Transfers keyboard focus to this element.

remove( )
Removes the <option> element at the specified position.

Description

This interface represents a <select> element in an HTML form. The options property provides convenient access to the set of <option> elements it contains, and the add( ) and remove( ) methods provide an easy way to modify the set of options.

See Also

HTMLFormElement, HTMLOptionElement; Option and Select objects in the client-side reference section; Chapter 15

HTMLTableElementa <table> in an HTML document

Availability

DOM Level 1 HTML

Inherits from/Overrides

Node Figure Element Figure HTMLElement Figure HTMLTableElement

Properties

HTMLTableCaptionElement caption
A reference to the <caption> element for the table, or null if there is none.

readonly HTMLCollection rows
An array (HTMLCollection) of HTMLTableRowElement 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 HTMLTableSectionElement objects that represent all the <tbody> sections in this table.

HTMLTableSectionElement tFoot
The <tfoot> element of the table, or null if there is none.

HTMLTableSectionElement tHead
The <thead> element of the table, or null if there is none.

In addition to the properties just listed, this interface defines the properties in the following table to represent the HTML attributes of the <table> element.

Property

Attribute

Description

deprecated String align

align

Horizontal alignment of table in document

deprecated String bgColor

bgcolor

Table background color

String border

border

Width of border around table

String cellPadding

cellpadding

Space between cell contents and border

String cellSpacing

cellspacing

Space between cell borders

String frame

frame

Which table borders to draw

String rules

rules

Where to draw lines within the table

String summary

summary

Summary description of table

String width

width

Table width

Methods

createCaption( )
Returns the existing <caption> for the table, or creates (and inserts) a new one if none already exists.

createTFoot( )
Returns the existing <tfoot> element for the table, or creates (and inserts) a new one if none already exists.

createTHead( )
Returns the existing <thead> element for the table, or creates (and inserts) a new one if none already exists.

deleteCaption( )
Deletes the <caption> element from the table, if it has one.

deleteRow( )
Deletes the row at the specified position in the table.

deleteTFoot( )
Deletes the <tfoot> element from the table, if it has one.

deleteTHead( )
Deletes the <thead> element from the table, if one exists.

insertRow( )
Inserts a new, empty <tr> element into the table at the specified position.

Description

This interface 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 they could also be duplicated with core DOM methods.

See Also

HTMLTableCaptionElement, HTMLTableCellElement, HTMLTableColElement, HTMLTableRowElement, HTMLTableSectionElement

HTMLTextAreaElementa <textarea> element in an HTML form DOM Level 1 HTML

Availability

Inherits from/Overrides

Node Figure Element Figure HTMLElement Figure HTMLTextAreaElement

Properties

String accessKey
A keyboard shortcut (a single character) that the web browser can use to transfer keyboard focus to this element. Mirrors the accesskey attribute.

long cols
The width of this element in character columns. Mirrors the cols attribute.

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.

boolean disabled
If true, this element is disabled and the user cannot interact with it. Mirrors the disabled attribute.

readonly HTMLFormElement form
The HTMLFormElement that represents the <form> element containing this text area, or null if this element is not inside a form.

String name
The name of this <textarea> element, as specified by the name attribute.

boolean readOnly
If true, this element is read-only and the user cannot edit any of the displayed text. Mirrors the readonly attribute.

long rows
The height of the text area in text rows. Mirrors the rows attribute.

long tabIndex
The position of this element in the tabbing order. Mirrors the tabindex attribute.

readonly String type
The type of this element, for compatibility with HTMLInputElement objects. This property always has the value "textarea".

String value
The text currently displayed in the text area.

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.

Description

This interface represents a <textarea> element that creates a multiline text-input field in an HTML form. The initial contents of the text area are specified between the <textarea> and </textarea> tags. The user may edit this value and query and set the text with the value property (or by modifying the Text node child of this element).

See Also

HTMLFormElement, HTMLInputElement; Textarea in the client-side reference section; Chapter 15

MediaLista style sheet's list of media types

Availability

DOM Level 2 StyleSheets

Properties

readonly unsigned long length
The length of the array; the number of media types in the list.

String mediaText
A comma-separated text representation of the complete media list. Setting this property may throw a DOMException with a code of SYNTAX_ERR if the new value contains a syntax err, or a code of NO_MODIFICATION_ALLOWED_EXCEPTION if the media list is read-only.

Methods

appendMedium( )
Adds a new media type to the end of the list.

deleteMedium( )
Removes the specified media type from the list.

item( )
Returns the media type at the specified position in the list, or null if the index is invalid. In JavaScript, you can also treat the MediaList object as an array and index it using normal square-bracket array notation instead of calling this method.

Description

This interface represents a list or array of media types for a style sheet. length specifies the number of elements in the list, and item( ) allows a specific media type to be retrieved by position. appendMedium( ) and deleteMedium( ) allow entries to be appended to and deleted from the list. JavaScript allows a MediaList object to be treated as an array, and you can use square-bracket notation instead of calling item( ).

The HTML 4 standard defines the following media types (they are case-sensitive, and must be written in lowercase letters): screen, tty, tv, projection, handheld, print, braile, aural, and all. The screen type is most relevant to documents being displayed in web browsers on desktop or laptop computers. The print type is used for styles intended for printed documents.

See Also

Type of

StyleSheet.media

MediaList.appendMedium( )add a new media type to the list

Availability

DOM Level 2 StyleSheets

Synopsis

void appendMedium(String newMedium)
    throws DOMException;

Arguments

newMedium
The name of the new media type to append. See the MediaList reference page for the set of valid media type names.

Throws

This method may throw a DOMException with a code of NO_MODIFICATION_ALLOWED_ERR if the media list is read-only, or INVALID_CHARACTER_ERR if the specified newMedium argument contains illegal characters.

Description

This method appends the specified newMedium to the end of the MediaList. If the MediaList already contains the specified media type, it is first removed from its current position and then appended at the end of the list.

MediaList.deleteMedium( )remove a media type from the list

Availability

DOM Level 2 StyleSheets

Availability

Synopsis

void deleteMedium(String oldMedium)
    throws DOMException;

Arguments

oldMedium
The name of the media type to remove from the list. See the MediaList reference page for the set of valid media type names.

Throws

This method throws a DOMException with a code of NOT_FOUND_ERR if the list does not contain the specified oldMedium media type, or NO_MODIFICATION_ALLOWED_ERR if the media list is read-only.

Description

This method deletes the specified media type from this MediaList, or throws an exception if the list does not contain the specified type.

MouseEventdetails about a mouse event

Availability

DOM Level 2 Events

Inherits from/Overrides

Event Figure UIEvent Figure 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.

Netscape 6.0 and 6.01 use the values 1, 2, and 3 instead of 0, 1, and 2. This is fixed in Netscape 6.1.

readonly long clientX, clientY
Numbers that specify the X and Y coordinates of the mouse pointer relative to the "client area," or browser window. Note that these coordinates do not take document scrolling into account; if an event occurs at the very top of the window, clientY is 0 regardless of how far down the document has been scrolled. These properties are defined for all types of mouse events.

readonly boolean ctrlKey
Whether the Ctrl key was held down when the event occurred. Defined for all types of mouse events.

readonly boolean metaKey
Whether the Meta key was held down when the event occurred. Defined for all types of mouse events.

readonly EventTarget relatedTarget
Refers to a node that is related to the target node of the event. For mouseover events, it is the node the mouse left when it moved over the target. For mouseout events, it is the node the mouse entered when leaving the target. relatedTarget is undefined for other types of mouse events.

readonly long screenX, screenY
Numbers that specify the X and Y coordinates of the mouse pointer relative to the upper-left corner of the user's monitor. These properties are defined for all types of mouse events.

readonly boolean shiftKey
Whether the Shift key was held down when the event occurred. Defined for all types of mouse events.

Methods

initMouseEvent( )
Initializes the properties of a newly created MouseEvent object.

Description

This interface defines the type of Event object that is passed to events of types click, mousedown, mousemove, mouseout, mouseover, and mouseup. Note that in addition to the properties listed here, this interface also inherits the properties of the UIEvent and Event interfaces.

See Also

Event, UIEvent; Chapter 19

MutationEventdetails about a document change

Availability

DOM Level 2 Events

Inherits from/Overrides

Event Figure MutationEvent

Constants

The following constants represent the set of possible values for the attrChange property:

unsigned short MODIFICATION = 1
An Attr node was modified.

unsigned short ADDITION = 2
An Attr node was added.

unsigned short REMOVAL = 3
An Attr node was removed.

Properties

readonly unsigned short attrChange
How the attribute was changed, for DOMAttrModified events. The three possible values are defined in the "Constants" section.

readonly String attrName
The name of the attribute that was changed for DOMAttrModified events.

readonly String newValue
The new value of the Attr node for DOMAttrModified events, or the new text value of a Text, Comment, CDATASection, or ProcessingInstruction node for DOMCharacterDataModified events.

readonly String prevValue
The previous value of an Attr node for DOMAttrModified events, or the previous value of a Text, Comment, CDATASection, or ProcessingInstruction node for DOMCharacterDataModified events.

readonly Node relatedNode
The relevant Attr node for DOMAttrModified events, or the parent of the node that was inserted or removed for DOMNodeInserted and DOMNodeRemoved events.

Methods

initMutationEvent( )
Initializes the properties of a newly created MutationEvent object.

Description

This interface defines the type of Event object that is passed to events of types listed here (note that none of these event types are cancelable with Event.preventDefault( )):

DOMAttrModified
Generated when an attribute of a document element is added, removed, or changed. The target of the event is the element that contains the attribute, and the event bubbles up from there.

DOMCharacterDataModified
Generated when the character data of a Text, Comment, CDATASection, or ProcessingInstruction node changes. The event target is the node that changed, and the event bubbles up from there.

DOMNodeInserted
Generated after a node is added as a child of another node. The target of the event is the node that was inserted, and the event bubbles up the tree from there. The relatedNode property specifies the new parent of the inserted node. This event is not generated for any descendants of the inserted node.

DOMNodeInsertedIntoDocument
Generated after a node is inserted into the document tree, as well as for nodes that are inserted directly into the tree and nodes that are indirectly inserted when an ancestor is inserted. The target of this event is the node that is inserted. Because events of this type may be targeted at every node in a subtree, they do not bubble.

DOMNodeRemoved
Generated immediately before a node is removed from its parent. The target of the event is the node being removed, and the event bubbles up the document tree from there. The relatedNode property holds the parent node from which the node is being removed.

DOMNodeRemovedFromDocument
Generated immediately before a node is removed from the document tree. Separate events are generated for the node that is directly removed and for each of its descendant nodes. The target of the event is the node that is about to be removed. Events of this type do not bubble.

DOMSubtreeModified
Generated as a kind of summary event when a call to a DOM method causes multiple mutation events to be fired. The target of this event is the most deeply nested common ancestor of all changes that occurred in the document, and it bubbles up the document tree from that point. If you are not interested in the details of the changes but merely want to be notified which portions of the document have changed, you may prefer to register listeners for this type of event.

NamedNodeMapa collection of nodes indexed by name or position

Availability

DOM Level 1 Core

Properties

readonly unsigned long length
The number of nodes in the array.

Methods

getNamedItem( )
Looks up a named node.

getNamedItemNS( ) [DOM Level 2]
Looks up a node specified by namespace and name.

item( )
Obtains the node at a specified position within the NamedNodeMap. In JavaScript, you can also do this by using the node position as an array index.

removeNamedItem( )
Deletes a named node from the NamedNodeMap.

removeNamedItemNS( ) [DOM Level 2]
Deletes a node specified by name and namespace from the NamedNodeMap.

setNamedItem( )
Adds a new node to (or replaces an existing node in) the NamedNodeMap. The nodeName property of the Node object is used as the name of the node.

setNamedItemNS( ) [DOM Level 2]
Adds a new node to (or replaces an existing node in) the NamedNodeMap. The namespaceURI and localName properties of the Node object are used as the node name.

Description

The NamedNodeMap interface defines a collection of nodes that may be looked up by their nodeName property or, for nodes that use namespaces, by their namespaceURI or localName properties.

The most notable use of the NamedNodeMap interface is the attributes property of the Node interface: a collection of Attr nodes that may be looked up by attribute name. Many of the methods of NamedNodeMap are similar to the methods of Element for manipulating attributes. Element attributes are usually most easily manipulated through the methods of the Element interface, and the NamedNodeMap interface is not commonly used.

NamedNodeMap objects are "live," which means that they immediately reflect any changes to the document tree. For example, if you obtain a NamedNodeMap that represents the attributes of an element and then add a new attribute to that element, the new attribute is available through the NamedNodeMap.

See Also

NodeList

Type of

DocumentType.entities, DocumentType.notations, Node.attributes

Nodea node in a document tree

Availability

DOM Level 1 Core

Subinterfaces

Attr, CharacterData, Document, DocumentFragment, DocumentType, Element, Entity, EntityReference, Notation, ProcessingInstruction

Also Implements

EventTarget
If the DOM implementation supports the Events module, every node in the document tree also implements the EventTarget interface and may have event listeners registered on it. The methods defined by the EventTarget interface are not included here; see the "EventTarget" and EventListener reference pages for details.

Constants

All Node objects implement one of the subinterfaces listed above. Every Node object has a nodeType property that specifies which of the subinterfaces 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 4, 5, or 6.

Node.ELEMENT_NODE = 1;                 // Element
Node.ATTRIBUTE_NODE = 2;               // Attr
Node.TEXT_NODE = 3;                    // Text
Node.CDATA_SECTION_NODE = 4;           // CDATASection
Node.ENTITY_REFERENCE_NODE = 5;        // EntityReference
Node.ENTITY_NODE = 6;                  // Entity
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
Node.NOTATION_NODE = 12;               // Notation

Properties

readonly NamedNodeMap attributes
If this node is an element, specifies the attributes of that element. attributes is a NamedNodeMap object that allows attributes to be queried by name or by number and returns them in the form of Attr objects. In practice, it is almost always easier to use the getAttribute( ) method of the Element interface to obtain an attribute value as a string. Note that the returned NamedNodeMap object is "live": any changes to the attributes of this element are immediately visible through it.

readonly Node[] childNodes
Contains the child nodes of the current node. This property should never be null: for nodes with no children, childNodes is an array with length zero. This property is technically a NodeList object, but it behaves just like an array of Node objects. Note that the returned NodeList object is "live": any changes to this element's list of children are immediately visible through the NodeList.

readonly Node firstChild
The first child of this node, or null if the node has no children.

readonly Node lastChild
The last child of this node, or null if the node has no children.

readonly String localName [DOM Level 2]
In XML documents that use namespaces, specifies the local part of the element or attribute name. This property is never used with HTML documents. See also the namespaceURI and prefix properties.

readonly String namespaceURI [DOM Level 2]
In XML documents that use namespaces, specifies the URI of the namespace of an Element or Attribute node. This property is never used with HTML documents. See also the localName and prefix properties.

readonly Node nextSibling
The sibling node that immediately follows this one in the childNodes[] array of the parentNode, or null if there is no such node.

readonly String nodeName
The name of the node. For Element nodes, specifies the tag name of the element, which can also be retrieved with the tagName property of the Element interface. For other types of nodes, the value depends on the node type. See the upcoming table in the Section 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 those 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, holds the text content. For other node types, the value depends on the nodeType, as shown in the upcoming table.

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 node (or container node) of this node, or null if there is no parent. Note that Document and Attr nodes never have parent nodes. Also, nodes that have been removed from the document or are newly created and have not yet been inserted into the document tree have a parentNode of null.

String prefix [DOM Level 2]
For XML documents that use namespaces, specifies the namespace prefix of an Element or Attribute node. This property is never used with HTML documents. See also the localName and namespaceURL properties. Setting this property can cause an exception if the new value contains illegal characters, is malformed, or does not match the namespaceURI property.

readonly Node previousSibling
The sibling node that immediately precedes this one in the childNodes[] array of the parentNode, or null if there is no such node.

Methods

appendChild( )
Adds a node to the document tree by appending it to the childNodes[] array of this node. If the node is already in the document tree, it is removed and then reinserted at its new position.

cloneNode( )
Makes a copy of this node, or of the node and all its descendants.

hasAttributes( ) [DOM Level 2]
Returns true if this node is an Element and has any attributes.

hasChildNodes( )
Returns true if this node has any children.

insertBefore( )
Inserts a node into the document tree immediately before the specified child of this node. If the node being inserted is already in the tree, it is removed and reinserted at its new location.

isSupported( ) [DOM Level 2]
Returns true if the specified version number of a named feature is supported by this node.

normalize( )
"Normalizes" all Text node descendants of this node by deleting empty Text nodes and merging adjacent Text nodes.

removeChild( )
Removes (and returns) the specified child node from the document tree.

replaceChild( )
Removes (and returns) the specified child node from the document tree, replacing it with another node.

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. 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 interface, 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 compare to the constant Node.ELEMENT_NODE
    var tagname = n.tagName;  // If the node is an Element, this is the tag name
} 

The nodeName and nodeValue properties specify additional information about a node, but their value depends on nodeType, as shown in the following table. Note that subinterfaces typically define specialized properties (such as the tagName property of Element nodes and the data property of Text nodes) for obtaining this information.

nodeType

nodeName

nodeValue

ELEMENT_NODE

The element's tag name

null

ATTRIBUTE_NODE

The attribute name

The attribute value

TEXT_NODE

#text

The text of the node

CDATA_SECTION_NODE

#cdata-section

The text of the node

ENTITY_REFERENCE_NODE

The name of the referenced entity

null

ENTITY_NODE

The entity name

null

PROCESSING_INSTRUCTION_NODE

The target of the PI

The remainder of the PI

COMMENT_NODE

#comment

The text of the comment

DOCUMENT_NODE

#document

null

DOCUMENT_TYPE_NODE

The document type name

null

DOCUMENT_FRAGMENT_NODE

#document-fragment

null

NOTATION_NODE

The notation name

null

See Also

Document, Element, Text; Chapter 17

Node.appendChild( )insert a node as the last child of this node

Availability

DOM Level 1 Core

Synopsis

Node appendChild(Node newChild) 
    throws DOMException;

Arguments

newChild
The node to be inserted into the document. If the node is a DocumentFragment, it is not directly inserted, but each of its children are.

Returns

The node that was added.

Throws

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

HIERARCHY_REQUEST_ERR
The node does not allow children, or it does not allow children of the specified type, or newChild is an ancestor of this node (or is this node itself ).

WRONG_DOCUMENT_ERR
The ownerDocument property of newChild is not the same as the ownerDocument property of this node.

NO_MODIFICATION_ALLOWED_ERR
This node is read-only and does not allow children to be appended, or the node being appended is already part of the document tree and its parent is read-only and does not allow children to be removed.

Description

This method adds the node newChild to the document, inserting it as the last child of this node. If newChild is already in the document tree, it is removed from the tree and then reinserted at its new location. If newChild is a DocumentFragment node, it is not inserted itself; instead, all its children are appended, in order, to the end of this node's childNodes[] array. Note that a node from (or created by) one document cannot be inserted into a different document. That is, the ownerDocument property of newChild must be the same as the ownerDocument property of this node.

Example

The following function inserts a new paragraph at the end of the document:

function appendMessage(message) {
    var pElement = document.createElement("P");
    var messageNode = document.createTextNode(message);
    pElement.appendChild(messageNode);    // Add text to paragraph
    document.body.appendChild(pElement);  // Add paragraph to document body
}

See Also

Node.insertBefore( ), Node.removeChild( ), Node.replaceChild( )

Node.insertBefore( )insert a node into the document tree before the specified node

Availability

DOM Level 1 Core

Synopsis

Node insertBefore(Node newChild, 
                  Node refChild) 
    throws DOMException;

Arguments

newChild
The node to be inserted into the tree. If it is a DocumentFragment, its children are inserted instead.

refChild
The child of this node before which newChild is to be inserted. If this argument is null, newChild is inserted as the last child of this node.

Returns

The node that was inserted.

Throws

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

HIERARCHY_REQUEST_ERR
This node does not support children, or it does not allow children of the specified type, or newChild is an ancestor of this node (or is this node itself ).

WRONG_DOCUMENT_ERR
The ownerDocument property of newChild and this node are different.

NO_MODIFICATION_ALLOWED_ERR
This node is read-only and does not allow insertions or the parent of newChild is read-only and does not allow deletions.

NOT_FOUND_ERR
refChild is not a child of this node.

Description

This method inserts the node newChild into the document tree as a child of this node. The new node is positioned within this node's childNodes[] array so that it comes immediately before the refChild node. If refChild is null, newChild is inserted at the end of childNodes[], just as with the appendChild( ) method. Note that it is illegal to call this method with a refChild that is not a child of this node.

If newChild is already in the document tree, it is removed from the tree and then reinserted at its new position. If newChild is a DocumentFragment node, it is not inserted itself; instead, each of its children is inserted, in order, at the specified location.

Example

The following function inserts a new paragraph at the beginning of a document:

function insertMessage(message) {
    var paragraph = document.createElement("p");  // Create a <p> Element
    var text = document.createTextNode(message);  // Create a Text node
    paragraph.appendChild(text);                  // Add text to the paragraph
    // Now insert the paragraph before the first child of the body
    document.body.insertBefore(paragraph, document.body.firstChild)
}

See Also

Node.appendChild( ), Node.removeChild( ), Node.replaceChild( )

Node.replaceChild( )replace a child node with a new node

Availability

DOM Level 1 Core

Synopsis

Node replaceChild(Node newChild, 
                  Node oldChild) 
    throws DOMException;

Arguments

newChild
The replacement node.

oldChild
The node to be replaced.

Returns

The node that was removed from the document and replaced.

Throws

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

HIERARCHY_REQUEST_ERR
This node does not allow children, or does not allow children of the specified type, or newChild is an ancestor of this node (or is this node itself ).

WRONG_DOCUMENT_ERR
newChild and this node have different values for ownerDocument.

NO_MODIFICATION_ALLOWED_ERR
This node is read-only and does not allow replacement, or newChild is the child of a node that does not allow removals.

NOT_FOUND_ERR
oldChild is not a child of this node.

Description

This method replaces one node of the document tree with another. oldChild is the node to be replaced, and must be a child of this node. newChild is the node that takes its place in the childNodes[] array of this node.

If newChild is already part of the document, it is first removed from the document before being reinserted at its new position. If newChild is a DocumentFragment, it is not inserted itself; instead each of its children is inserted, in order, at the position formerly occupied by oldChild.

Example

The following code replaces a node n with a <b> element and then inserts the replaced node into the <b> element, which reparents the node and makes it appear in bold:

// Get the first child node of the first paragraph in the document
var n = document.getElementsByTagName("p")[0].firstChild;
var b = document.createElement("b");  // Create a <b> element
n.parentNode.replaceChild(b, n);      // Replace the node with <b>
b.appendChild(n);                     // Reinsert the node as a child of <b>

See Also

Node.appendChild( ), Node.insertBefore( ), Node.removeChild( )

NodeFiltera function to filter the nodes of a document tree

Availability

DOM Level 2 Traversal

Constants

The following three constants are the legal return values for node filter functions. Note that they are static properties of the object named NodeFilter, not properties of individual node filter functions:

short FILTER_ACCEPT = 1
Accept this node. A NodeIterator or TreeWalker will return this node as part of its document traversal.

short FILTER_REJECT = 2
Reject this node. A NodeIterator or TreeWalker will behave as if this node does not exist. Furthermore, this return value tells a TreeWalker to ignore all children of this node.

short FILTER_SKIP = 3
Skip this node. A NodeIterator or TreeWalker will not return this node, but it will recursively consider its children as part of document traversal.

The following constants are bit flags that can be set in the whatToShow argument to the createNodeIterator( ) and createTreeWalker( ) methods of the Document object. Each constant corresponds to one of the types of Document nodes (see the "Node" reference page for a list of node types) and specifies that a NodeIterator or TreeWalker should consider nodes of that type during its traversal of the document. Multiple constants can be combined using the logical OR operator |. SHOW_ALL is a special value with all bits set: it indicates that all nodes should be considered, regardless of their type.

unsigned long SHOW_ALL = 0xFFFFFFFF;
unsigned long SHOW_ELEMENT = 0x00000001;
unsigned long SHOW_ATTRIBUTE = 0x00000002;
unsigned long SHOW_TEXT = 0x00000004;
unsigned long SHOW_CDATA_SECTION = 0x00000008;
unsigned long SHOW_ENTITY_REFERENCE = 0x00000010;
unsigned long SHOW_ENTITY = 0x00000020;
unsigned long SHOW_PROCESSING_INSTRUCTION = 0x00000040;
unsigned long SHOW_COMMENT = 0x00000080;
unsigned long SHOW_DOCUMENT = 0x00000100;
unsigned long SHOW_DOCUMENT_TYPE = 0x00000200;
unsigned long SHOW_DOCUMENT_FRAGMENT = 0x00000400;
unsigned long SHOW_NOTATION = 0x00000800;

Methods

acceptNode( )
In languages such as Java that do not allow functions to be passed as arguments, you define a node filter by defining a class that implements this interface and includes an implementation for this function. The function is passed a node and must return one of the constants FILTER_ACCEPT, FILTER_REJECT, or FILTER_SKIP. In JavaScript, however, you create a node filter simply by defining a function (with any name) that accepts a node argument and returns one of the three filter constants. See the following sections for details and an example.

Description

A node filter is an object that can examine a Document node and tell a NodeIterator or TreeWalker whether to include the node in its document traversal. In JavaScript, a node filter is simply a function that takes a single node argument and returns one of the three FILTER_ constants defined earlier. There is no NodeFilter interface; there is simply an object named NodeFilter that has properties that define those constants. To use a node filter, you pass it to the createNodeIterator( ) or createTreeWalker( ) method of the Document object. Your node filter function will then be called to evaluate nodes when you use the resulting NodeIterator or TreeWalker object to traverse the document.

Node filter functions should ideally be written so that they do not themselves alter the document tree and do not throw any exceptions. Also, node filters are not allowed to base their filtering decisions on the history of past invocations of those filters.

Example

You might define and use a node filter function as follows:

// Define a node filter that filters out everything but <h1> and <h2> elements
var myfilter = function(n) {  // Filter node n
    if ((n.nodeName == "H1") || (n.nodeName == "H2"))
        return NodeFilter.FILTER_ACCEPT;
    else
        return NodeFilter.FILTER_SKIP;
}

// Now create a NodeIterator that uses the filter
var ni = document.createNodeIterator(document.body,  // Traverse the document body
                                     NodeFilter.SHOW_ELEMENT,  // Elements only
                                     myfilter,  // Filter by tag name
                                     false);  // No entity expansion

See Also

NodeIterator, TreeWalker

Type of

NodeIterator.filter, TreeWalker.filter

Passed to

Document.createNodeIterator( ), Document.createTreeWalker( )

NodeIteratoriterate through a filtered sequence of Document nodes

Availability

DOM Level 2 Traversal

Properties

readonly boolean expandEntityReferences
Whether this NodeIterator traverses the children of EntityReference nodes (in XML documents). The value is specified as an argument to Document.createNodeIterator( ) when the NodeIterator is first created.

readonly NodeFilter filter
The node filter function that was specified for this NodeIterator in the call to Document.createNodeIterator( ).

readonly Node root
The root node at which the NodeIterator begins iterating. The value of this property is specified in the call to Document.createNodeIterator( ).

readonly unsigned long whatToShow
A set of bit flags (see NodeFilter for a list of valid flags) that specifies what types of Document nodes this NodeIterator will consider. If a bit is not set in this property, the corresponding node type will always be ignored by this NodeIterator. Note that the value of this property is specified in the call to Document.createNodeIterator( ).

Methods

detach( )
"Detaches" this NodeIterator from its document so that the implementation no longer needs to modify the NodeIterator when the document is modified. Call this method when you are done using a NodeIterator. After detach( ) has been called, any calls to other NodeIterator methods will cause exceptions.

nextNode( )
Returns the next node in the filtered sequence of nodes represented by this NodeIterator, or null if the NodeIterator has already returned the last node.

previousNode( )
Returns the previous node in the filtered sequence of nodes represented by this NodeIterator, or null if there is no previous node.

Description

A NodeIterator represents the sequence of Document nodes that results from traversing a document subtree in document source order and filtering the nodes using a two-stage process. Create a NodeIterator object with Document.createNodeIterator( ). Use the nextNode( ) and previousNode( ) methods to iterate forward and backward through the sequence of nodes. Call detach( ) when you are done with a NodeIterator, unless you are sure that the NodeIterator will be garbage collected before the document is modified. Note that the properties of this interface are all read-only copies of the arguments passed to Document.createNodeIterator( ).

To be returned by the nextNode( ) or previousNode( ) methods, a node must pass two filtration steps. First, the node type must be one of the types specified by the whatToShow property. See NodeFilter for a list of constants that can be combined to specify the whatToShow argument to Document.createNodeIterator( ). Next, if the filter property is not null, each node that passes the whatToShow test is passed to the filter function specified by the filter property. If this function returns NodeFilter.FILTER_ACCEPT, the node is returned. If it returns NodeFilter.FILTER_REJECT or NodeFilter.FILTER_SKIP, the NodeIterator skips the node. Note that when a node is rejected by either of these filtration steps, it is only the node itself that is rejected; the children of the node are not automatically rejected and are subject to the same filtration steps.

NodeIterator objects remain valid even if the document tree they are traversing is modified. The nextNode( ) and previousNode( ) methods return nodes based on the current state of the document, not the state of the document that existed when the NodeIterator was created.

See Also

NodeFilter, TreeWalker; Chapter 17

Returned by

Document.createNodeIterator( )

NodeLista read-only array of nodes

Availability

DOM Level 1 Core

Properties

readonly unsigned long length
The number of nodes in the array.

Methods

item( )
Returns the specified element of the array.

Description

The NodeList interface defines a read-only ordered list (i.e., an array) of Node objects. The length property specifies how many nodes are in the list, and the item( ) method allows you to obtain the node at a specified position in the list. The elements of a NodeList are always valid Node objects: NodeLists never contain null elements.

In JavaScript, NodeList objects behave like JavaScript arrays, and you can query an element from the list using square-bracket array notation instead of calling the item( ) method. However, you cannot assign new nodes to a NodeList using square brackets. Since it is always easier to think of a NodeList object as a read-only JavaScript array, this book uses the notation Node[] (i.e., a Node array) instead of NodeList. See Element.getElementsByTagName( ), for example, which is listed as returning a Node[] 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, 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 will be removed from your NodeList. Be careful when you are looping through the elements of a NodeList if the body of your loop makes changes to the document tree (such as deleting nodes) that may affect the contents of the NodeList!

See Also

NamedNodeMap

Type of

Node.childNodes

Returned by

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

Rangerepresents a contiguous range of a document

Availability

DOM Level 2 Range

Constants

These constants specify how the boundary points of two Range objects are to be 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
Compare the start of the specified range to the start of this range.

unsigned short START_TO_END = 1
Compare the start of the specified range to the end of this range.

unsigned short END_TO_END = 2
Compare the end of the specified range to the end of this range.

unsigned short END_TO_START = 3
Compare the end of the specified range to the start of this range.

Properties

The Range interface defines the following properties. Note that all of these properties are read-only. You cannot change the start or end points of a range by setting properties; you must call setEnd( ) or setStart( ) instead. Note also that after you call the detach( ) method of a Range object, any subsequent attempt to read any of these properties throws a DOMException with a code of INVALID_STATE_ERR.

readonly boolean collapsed
true if the start and the end of the range are at the same point in the document -- that is, if the range is empty or "collapsed."

readonly Node commonAncestorContainer
The most deeply nested Document node that contains (i.e., is an ancestor of ) both the start and end points of the range.

readonly Node endContainer
The Document node that contains the end point of the range.

readonly long endOffset
The end point position 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 previously defined constants.

deleteContents( )
Deletes the region of the document represented by this range.

detach( )
Tells the implementation that this range will no longer be used and that it can stop keeping track of it. If you call this method for a range, subsequent method calls or property lookups on that range throw a DOMException with a code of INVALID_STATE_ERR.

extractContents( )
Deletes the region of the document represented by this range, but returns the contents of that region as a DocumentFragment object. This method is like a combination of cloneContents( ) and deleteContents( ).

insertNode( )
Inserts the specified node into the document at the start point of the range.

selectNode( )
Sets the boundary points of this range so that it contains the specified node and all of its descendants.

selectNodeContents( )
Sets the boundary points of this range so that it contains all the descendants of the specified node but not the node itself.

setEnd( )
Sets the end point of this range to the specified node and offset.

setEndAfter( )
Sets the end point of this range to immediately after the specified node.

setEndBefore( )
Sets the end point of this range to immediately before the specified node.

setStart( )
Sets the start position of this range to the specified offset within the specified node.

setStartAfter( )
Sets the start position of this range to immediately after the specified node.

setStartBefore( )
Sets the start position of this range to immediately before the specified node.

surroundContents( )
Inserts the specified node into the document at the start position of the range and then reparents all the nodes within the range so that they become descendants of the newly inserted node.

toString( )
Returns the plain-text content of the document region described by this range.

Description

A Range object represents a contiguous range or region of a document, such as the region that the user might select with a mouse drag in a web browser window. If an implementation supports the Range module, 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 an 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-type 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-style 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.

For further details, read the reference pages for each of the Range methods and see the discussion of the Range API in Chapter 17.

See Also

Document.createRange( ), DocumentFragment; Chapter 17

Passed to

Range.compareBoundaryPoints( )

Returned by

Document.createRange( ), Range.cloneRange( )

Range.compareBoundaryPoints( )compare positions of two ranges

Availability

DOM Level 2 Range

Synopsis

short compareBoundaryPoints(unsigned short how, 
                            Range sourceRange)
    throws DOMException;

Arguments

how
Specifies how to perform the comparison (i.e., which boundary points to compare). Legal values are the constants defined by the Range interface.

sourceRange
The range that is to be compared to this range.

Returns

-1 if the specified boundary point of this range is before the specified boundary point of sourceRange, 0 if the two specified boundary points are the same, or 1 if the specified boundary point of this range is after the specified boundary point of sourceRange.

Throws

If sourceRange represents a range of a different document than this range does, this method throws a DOMException with a code of WRONG_DOCUMENT_ERR.

Description

This method compares a boundary point of this range to a boundary point of the specified sourceRange and returns a value that specifies their relative order in the document source. The how argument specifies which boundary points of each range are to be compared. The legal values for this argument, and their meanings, are as follows:

Range.START_TO_START
Compare the start points of the two Range nodes.

Range.END_TO_END
Compare the end points of the two Range nodes.

Range.START_TO_END
Compare the start point of sourceRange to the end point of this range.

Range.END_TO_START
Compare the end point of sourceRange to the start point of this range.

The return value of this method is a number that specifies the relative position of this range to the specified sourceRange. Therefore, you might expect the range constants for the how argument to specify the boundary point for this range first and the boundary point for sourceRange second. Counterintuitively, however, the Range.START_TO_END constant specifies a comparison of the end point of this range with the start point of the specified sourceRange. Similarly, the Range.END_TO_START constant specifies a comparison of the start point of this range with the end point of the specified range.

Range.insertNode( )insert a node at the start of a range

Availability

DOM Level 2 Range

Synopsis

void insertNode(NodenewNode) 
    throws RangeException, 
           DOMException;

Arguments

newNode
The node to be inserted into the document.

Throws

This method throws a RangeException with a code of INVALID_NODE_TYPE_ERR if newNode is an Attr, Document, Entity, or Notation node.

This method also throws a DOMException with one of the following code values under the following conditions:

HIERARCHY_REQUEST_ERR
The node that contains the start of the range does not allow children, or it does not allow children of the specified type, or newNode is an ancestor of that node.

NO_MODIFICATION_ALLOWED_ERR
The node that contains the start of the range, or any of its ancestors, is read-only.

WRONG_DOCUMENT_ERR
newNode is part of a different document than the range is.

Description

This method inserts the specified node (and all its descendants) into the document at the start position of this range. When this method returns, this range includes the newly inserted node. If newNode is already part of the document, it is removed from its current position and then reinserted at the start of the range. If newNode is a DocumentFragment node, it is not inserted itself, but all of its children are inserted, in order, at the start of the range.

If the node that contains the start of the range is a Text node, it is split into two adjacent nodes before the insertion takes place. If newNode is a Text node, it is not merged with any adjacent Text nodes after it is inserted. To merge adjacent nodes, call Node.normalize( ).

See Also

DocumentFragment, Node.normalize( )

Range.surroundContents( )surround range contents with the specified node

Availability

DOM Level 2 Range

Synopsis

void surroundContents(Node newParent)
    throws RangeException, 
           DOMException;

Arguments

newParent
The node that is to become the new parent of the contents of this range.

Throws

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

DOMException.HIERARCHY_REQUEST_ERR
The container node of the start of the range does not allow children or does not allow children of the type of newParent, or newParent is an ancestor of that container node.

DOMException.NO_MODIFICATION_ALLOWED_ERR
An ancestor of a boundary point of the range is read-only and does not allow insertions.

DOMException.WRONG_DOCUMENT_ERR
newParent and this range were created using different Document objects.

RangeException.BAD_BOUNDARYPOINTS_ERR
The range partially selects a node (other than a Text node), so the region of the document it represents cannot be surrounded.

RangeException.INVALID_NODE_TYPE_ERR
newParent is a Document, DocumentFragment, DocumentType, Attr, Entity, or Notation node.

Description

This method reparents the contents of this range to newParent and then inserts newParent into the document at the start position of the range. It is useful to place a region of document content within a <b> 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.

StyleSheeta style sheet of any type

Availability

DOM Level 2 StyleSheets

Subinterfaces

CSSStyleSheet

Properties

boolean disabled
If true, the style sheet is disabled and is not applied to the document. If false, the style sheet is enabled and is applied to the document (unless the media property specifies that the style sheet should not be applied to documents of this type).

readonly String href
The URL of a style sheet that is linked into the document, or null for inline style sheets.

readonly MediaList media
A list of media types for which this style sheet should be applied. If no media information is supplied for the style sheet, this property is a valid MediaList object that has a length of 0.

readonly Node ownerNode
The Document node that links the style sheet into the document, or the node that contains an inline style sheet. In HTML documents, this property refers to a <link> or <style> element. For style sheets that are included within other style sheets rather than directly in the document, this property is null.

readonly StyleSheet parentStyleSheet
The style sheet that included this one, or null if this style sheet was included directly in the document. See also "CSSStyleSheet.ownerRule."

readonly String title
The title of the style sheet, if one is specified. A title may be specified by the title attribute of a <style> or <link> tag that is the ownerNode of this style sheet.

readonly String type
The type of this style sheet, as a MIME type. CSS style sheets have a type of "text/css".

Description

This interface represents a style sheet that is associated with this document. If this is a CSS style sheet, the object that implements this StyleSheet interface also implements the CSSStyleSheet subinterface and defines properties and methods that allow you to examine and set the CSS rules that comprise the style sheet. See CSSStyleSheet for details.

If a DOM implementation supports style sheets, you can obtain a complete list of the style sheets associated with a document through the Document.styleSheets property. Furthermore, the HTML <style> and <link> elements and XML style-sheet ProcessingInstruction nodes implement the LinkStyle interface and provide a reference to the StyleSheet through a property named sheet.

See Also

CSSStyleSheet, Document.styleSheets, LinkStyle

Type of

LinkStyle.sheet, StyleSheet.parentStyleSheet

Returned by

StyleSheetList.item( )

TreeWalkertraverse a filtered document subtree

Availability

DOM Level 2 Traversal

Properties

Node currentNode
The current position of this TreeWalker and the node relative to which all of the TreeWalker traversal methods operate. This is the node most recently returned by one of those traversal methods or, if none of those methods have been called yet, it is the same as the root property.

Note that this is a read/write property, and you can set it to any valid Document node -- even one that is not a descendant of the original root node or one that would be rejected by the filters used by this TreeWalker. If you change the value of this property, the traversal methods operate relative to the new node you specify. Attempting to set this property to null throws a DOMException with a code of NOT_SUPPORTED_ERR.

readonly boolean expandEntityReferences
This read-only property specifies whether this TreeWalker object expands entity references it encounters while traversing XML documents. The value of this property is set by the call to Document.createTreeWalker( ).

readonly NodeFilter filter
The node filter function, if any, that was specified for this TreeWalker in the call to Document.createTreeWalker( ). If no node filter is in use, this property is null.

readonly Node root
This read-only property specifies the root node at which the TreeWalker begins traversal. It is the initial value of the currentNode property and is specified in the call to Document.createTreeWalker( ).

readonly unsigned long whatToShow
This read-only property is a set of bit flags (see NodeFilter for a list of valid flags) that specifies the types of Document nodes this TreeWalker will consider. If a bit is not set in this property, the corresponding node type will always be ignored by this TreeWalker. Note that the value of this property is specified in the call to Document.createTreeWalker( ).

Methods

firstChild( )
Returns the first child of the current node that is not filtered out, or null.

lastChild( )
Returns the last child of the current node that is not filtered out, or null.

nextNode( )
Returns the next node (in document source order) that is not filtered out, or null.

nextSibling( )
Returns the next sibling of the current node that is not filtered out, or null.

parentNode( )
Returns the parent or nearest ancestor of the current node that is not filtered out, or null.

previousNode( )
Returns the previous node (in document source order) that is not filtered out, or null.

previousSibling( )
Returns the nearest previous sibling of the current node that is not filtered out, or null.

Description

A TreeWalker filters a specified document subtree and defines methods that allow programs to traverse the filtered tree (which may have a significantly different structure than the original document tree). Create a TreeWalker object with the createTreeWalker( ) method of the Document object. Once a TreeWalker is created, you can use its firstChild( ) and nextSibling( ) methods to traverse the filtered subtree it represents in the same way that you might use the firstChild and nextSibling properties of the Node interface to traverse an unfiltered document tree.

A TreeWalker applies the same two filtration steps that a NodeIterator does. The various traversal methods defined by TreeWalker will return only nodes that pass both filters. First, the node type must be one of the types specified by the whatToShow property. See NodeFilter for a list of constants that can be combined to specify the whatToShow argument to Document.createTreeWalker( ). Second, if the filter property is not null, each node that passes the whatToShow test is passed to the filter function specified by the filter property. If this function returns NodeFilter.FILTER_ACCEPT, the node is returned. If it returns NodeFilter.FILTER_REJECT, the node and all of its descendants are skipped by the TreeWalker (this differs from NodeIterator filtration, in which descendants are never automatically rejected). If the node filter function returns NodeFilter.FILTER_SKIP, the TreeWalker ignores the node but does consider its descendants.

Unlike NodeIterators, TreeWalkers are not modified when the underlying document is modified. The current node of a TreeWalker remains unchanged, even if that node is removed from the document. (And, in this case, the TreeWalker can be used to traverse the tree of deleted nodes, if any, that surround that current node.)

Example

// A NodeFilter that rejects <font> tags and any element with a
// class="sidebar" attribute and any descendants of such an element
var filter = function(n) {
    if (n.nodeName == "FONT") return NodeFilter.FILTER_SKIP;
    if (n.nodeType == Node.ELEMENT_NODE && n.className == "sidebar")
        return NodeFilter.FILTER_REJECT;
    return NodeFilter.FILTER_ACCEPT;
}

// Create a TreeWalker using the filter above
var tw = document.createTreeWalker(document.body,  // Walk HTML document body
                                   // Consider all nodes except comments
                                   ~NodeFilter.SHOW_COMMENT,
                                   filter,  // Use filter above
                                   false);  // Don't expand entity references

// Here's a recursive function that traverses a document using a TreeWalker
function traverse(tw) {
    // Remember the current node
    var currentNode = tw.currentNode;

    // Loop through the children of the current node of the TreeWalker
    for(var c = tw.firstChild( ); c != null; c = tw.nextSibling( )) {
        process(c);    // Do something to process the child
        traverse(tw);  // And recursively process its children
    }

    // Put the TreeWalker back in the state we found it in
    tw.currentNode = currentNode;
}

See Also

NodeFilter, NodeIterator; Chapter 17

Returned by

Document.createTreeWalker( )

ViewCSSsee AbstractView



Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.







??????????????@Mail.ru