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 Entry | how to read DOM reference pages |
Availability
Inherits from
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.
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.
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 Element 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.
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.
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.
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.
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:
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.
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.
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:
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.
This section explains the kinds of exceptions the method can throw and under what circumstances it throws them.
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:
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:
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.
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.
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.
AbstractView | a window displaying a document |
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.
Document.defaultView
AbstractView.getComputedStyle( ) | retrieve the CSS styles used to render an element |
CSSStyleDeclaration getComputedStyle(Element elt, String pseudoElt);
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.
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.
Attr | an attribute of a document element |
Node Attr
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.
Element.removeAttributeNode( ), Element.setAttributeNode( ), Element.setAttributeNodeNS( )
Document.createAttribute( ), Document.createAttributeNS( ), Element.getAttributeNode( ), Element.getAttributeNodeNS( ), Element.removeAttributeNode( ), Element.setAttributeNode( ), Element.setAttributeNodeNS( )
CDATASection | a CDATA section in an XML document |
Node CharacterData Text CDATASection
This infrequently used interface represents a CDATA section in an XML document. Programmers working with HTML documents never encounter nodes of this type and do not need to use this interface.
CDATASection is a subinterface of Text and does not define any properties or methods of its own. The textual content of the CDATA section is available through the nodeValue property inherited from Node or through the data property inherited from CharacterData. Although CDATASection nodes can often be treated in the same way as Text nodes, note that the Node.normalize( ) method does not merge adjacent CDATA sections.
Document.createCDATASection( )
CharacterData | common functionality for Text and Comment nodes |
Node CharacterData
Comment, Text
CharacterData is the superinterface for Text and Comment nodes. Documents never contain CharacterData nodes; they contain only Text and Comment nodes. Since both of these node types have similar functionality, however, that functionality has been defined here so that both Text and Comment can inherit it.
CharacterData.appendData( ) | append a string to a Text or Comment node |
void appendData(String arg) throws DOMException;
This method throws a DOMException with a code of NO_MODIFICATION_ALLOWED_ERR if called on a node that is read-only.
This method appends the string arg to the end of the data property for this node.
CharacterData.deleteData( ) | delete characters from a Text or Comment node |
void deleteData(unsigned long offset, unsigned long count) throws DOMException;
This method may throw a DOMException with one of the following code values:
This method deletes characters from this Text or Comment node, starting with the character at the position offset and continuing for count characters. If offset plus count is greater than the number of characters in the Text or Comment node, all characters from offset to the end of the string are deleted.
CharacterData.insertData( ) | insert a string into a Text or Comment node |
void insertData(unsigned long offset, String arg) throws DOMException;
This method may throw a DOMException with one of the following code values in the following circumstances:
This method inserts the specified string arg into the text of a Text or Comment node at the specified position offset.
CharacterData.replaceData( ) | replace characters of a Text or Comment node with a string |
void replaceData(unsigned long offset, unsigned long count, String arg) throws DOMException;
This method may throw a DOMException with one of the following code values in the following circumstances:
This method replaces count characters starting at position offset with the contents of the string arg. If the sum of offset and count is greater than the length of the Text or Comment node, all characters from offset on are replaced.
CharacterData.substringData( ) | extract a substring from a Text or Comment node |
String substringData(unsigned long offset, unsigned long count) throws DOMException;
A string that consists of count characters of the Text or Comment node starting with the character at position offset.
This method may throw a DOMException with one of the following code values:
This method extracts the substring that starts at position offset and continues for count characters from the text of a Text or Comment node. This method is useful only when the amount of text contained by the node is larger than the maximum number of characters that can fit in a string in a browser's JavaScript implementation. In this case, a JavaScript program cannot use the data property of the Text or Comment node directly and must instead work with shorter substrings of the node's text. This situation is unlikely to arise in practice.
Comment | an HTML or XML comment |
Node CharacterData Comment
A Comment node represents a comment in an HTML or XML document. The content of the comment (i.e., the text between <!-- and -->) is available through the data property inherited from the CharacterData interface or through the nodeValue property inherited from the Node interface. This content may be manipulated using the various methods inherited from CharacterData.
Document.createComment( )
Counter | a CSS counter( ) or counters( ) specification |
This interface represents a CSS counter( ) or counters( ) value. Consult a CSS reference for more information.
CSSPrimitiveValue.getCounterValue( )
CSS2Properties | convenience properties for all CSS2 attributes |
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 |
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.
CSSCharsetRule | an @charset rule in a CSS style sheet |
CSSRule CSSCharsetRule
This interface represents an @charset rule in a CSS style sheet. Consult a CSS reference for details.
CSSFontFaceRule | an @font-face rule in a CSS style sheet |
CSSRule CSSFontFaceRule
This interface represents an @font-face rule in a CSS style sheet. Consult a CSS reference for details.
CSSImportRule | an @import rule in a CSS style sheet |
CSSRule CSSImportRule
This interface represents an @import rule in a CSS style sheet. The styleSheet property represents the imported style sheet.
CSSMediaRule | an @media rule in a CSS style sheet |
CSSRule CSSMediaRule
This interface represents an @media rule, and all of its nested rules, in a CSS style sheet. It defines methods that allow you to insert and delete nested rules. Consult a CSS reference for details.
CSSMediaRule.deleteRule( ) | delete a rule in an @media block |
void deleteRule(unsigned long index) throws DOMException;
This method throws a DOMException with one of the following code values in the following circumstances:
This method deletes the rule at the specified position in the cssRules array.
CSSMediaRule.insertRule( ) | insert a new rule into an @media block |
unsigned long insertRule(String rule, unsigned long index) throws DOMException;
The value of the index argument.
This method throws a DOMException with one of the following code values in the following circumstances:
This method inserts the specified rule into the cssRules array at the specified index.
CSSPageRule | an @page rule in a CSS style sheet |
CSSRule CSSPageRule
This interface represents an @page rule in a CSS style sheet, which is typically used to specify the page layout for printing. Consult a CSS reference for details.
CSSPrimitiveValue | a single CSS style value |
CSSValue CSSPrimitiveValue
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.
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.
Counter, CSSValue, CSSValueList, Rect, RGBColor
RGBColor.blue, RGBColor.green, RGBColor.red, Rect.bottom, Rect.left, Rect.right, Rect.top
CSSPrimitiveValue.getCounterValue( ) | return a Counter value |
Counter getCounterValue( ) throws DOMException;
The Counter object that represents the value of this CSSPrimitiveValue.
This method throws a DOMException with a code of INVALID_ACCESS_ERR if the primitiveType property is not CSS_COUNTER.
This method returns a Counter object that represents a CSS counter. There is no corresponding setCounterValue( ), but you can modify the value by setting the properties of the returned Counter object.
CSSPrimitiveValue.getFloatValue( ) | get a numeric value, possibly converting units |
float getFloatValue(unsigned short unitType) throws DOMException;
The floating-point numeric value of this CSSPrimitiveValue, expressed in the specified units.
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.)
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.
CSSPrimitiveValue.getRectValue( ) | return a Rect value |
Rect getRectValue( ) throws DOMException;
The Rect object that represents the value of this CSSPrimitiveValue.
This method throws a DOMException with a code of INVALID_ACCESS_ERR if the primitiveType property is not CSS_RECT.
This method returns a Rect object that represents a CSS rectangle. There is no corresponding setRectValue( ) method, but you can modify the value by setting the properties of the returned Rect object.
CSSPrimitiveValue.getRGBColorValue( ) | get the RGBColor value |
RGBColor getRGBColorValue( ) throws DOMException;
The RGBColor object that represents the value of this CSSPrimitiveValue.
This method throws a DOMException with a code of INVALID_ACCESS_ERR if the primitiveType property is not CSS_RGBCOLOR.
This method returns an RGBColor object that represents a color. There is no corresponding setRGBColorValue( ) method, but you can modify the value by setting the properties of the returned RGBColor object.
CSSPrimitiveValue.getStringValue( ) | query a CSS string value |
String getStringValue( ) throws DOMException;
The string value of this CSSPrimitiveValue.
This method throws a DOMException with a code of INVALID_ACCESS_ERR if the primitiveType property is not CSS_STRING, CSS_URI, CSS_IDENT, or CSS_ATTR.
CSSPrimitiveValue.setFloatValue( ) | set the numeric value |
void setFloatValue(unsigned short unitType, float floatValue) throws DOMException;
This method throws a DOMException with a code of NO_MODIFICATION_ALLOWED_ERR if the CSS attribute with which this value is associated is read-only. It throws a DOMException with a code of INVALID_ACCESS_ERR if that CSS attribute does not allow numeric values or does not allow values with the specified unitType.
This method specifies the unit type and numeric value for this CSSPrimitiveValue.
CSSPrimitiveValue.setStringValue( ) | set the string value |
void setStringValue(unsigned short stringType, String stringValue) throws DOMException;
This method throws a DOMException with a code of NO_MODIFICATION_ALLOWED_ERR if the CSS attribute with which this value is associated is read-only. It throws a DOMException with a code of INVALID_ACCESS_ERR if that CSS attribute does not allow string values or does not allow values with the specified stringType.
This method sets the string value and string type for this CSSPrimitiveValue.
CSSRule | a rule in a CSS style sheet |
CSSCharsetRule, CSSFontFaceRule, CSSImportRule, CSSMediaRule, CSSPageRule, CSSStyleRule, CSSUnknownRule
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
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.
CSSRule.parentRule, CSSStyleDeclaration.parentRule, CSSStyleSheet.ownerRule
CSSRuleList.item( )
CSSRuleList | an array of CSSRule objects |
This interface defines a read-only ordered list (i.e., an array) of CSSRule objects. The length property specifies the number of rules in the list, and the item( ) method allows you to retrieve the rule at a specified position. In JavaScript, CSSRuleList 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. (Note, however, that you cannot assign new nodes into a CSSRuleList using square brackets.)
CSSMediaRule.cssRules, CSSStyleSheet.cssRules
CSSRuleList.item( ) | get the CSSRule at the specified position |
CSSRule item(unsigned long index);
The CSSRule object at the specified position, or null if index is not a valid position.
CSSStyleDeclaration | a set of CSS style attributes and their values |
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.
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( ).
CSSFontFaceRule.style, CSSPageRule.style, CSSStyleRule.style, HTMLElement.style
Document.getOverrideStyle( ), AbstractView.getComputedStyle( )
CSSStyleDeclaration.getPropertyCSSValue( ) | return a CSS attribute value as an object |
CSSValue getPropertyCSSValue(String propertyName);
A CSSValue object that represents the value of the named attribute if it is explicitly specified in this style declaration, or null if the named attribute is not specified. This method also returns null if propertyName specifies a CSS shorthand attribute, since shorthand attributes specify more than one value and cannot be represented with CSSValue objects.
CSSStyleDeclaration.getPropertyPriority( ) | get the priority of a CSS attribute |
String getPropertyPriority(String propertyName);
The string "important" if the named CSS attribute is explicitly specified in this declaration block and has the !important priority modifier. Returns the empty string otherwise.
CSSStyleDeclaration.getPropertyValue( ) | get the value of a CSS attribute as a string |
String getPropertyValue(String propertyName);
The string value of the named CSS attribute, or the empty string if that attribute is not explicitly set in this declaration block.
This method returns the value of the named CSS attribute as a string. Unlike getPropertyCSSValue( ), this method works with shortcut attributes as well as regular attributes. See also the various convenience properties of the CSS2Properties interface.
CSSStyleDeclaration.item( ) | get the CSS attribute name at the specified position |
String item(unsigned long index);
The name of the CSS attribute at index, or the empty string if index is negative or greater than or equal to the length property.
The CSSStyleDeclaration interface represents a collection of CSS style attributes and their values. This method allows you to query the name of the CSS attribute by position and, in conjunction with the length property, allows you to iterate through the set of CSS attributes specified in this style declaration. Note that the order of CSS attributes as returned by this method does not necessarily correspond to the order in which they appear in the document or style sheet source.
As an alternative to this item( ) method, JavaScript allows you to simply treat a CSSStyleDeclaration object as an array of CSS attribute names and use standard square-bracket array syntax to obtain the attribute name at a specified position.
CSSStyleDeclaration.removeProperty( ) | delete a CSS attribute specification |
String removeProperty(String propertyName) throws DOMException;
The value of the named CSS attribute as a string, or the empty string if the named attribute is not explicitly specified in this style declaration.
If this style declaration is read-only, this method throws a DOMException with a code of NO_MODIFICATION_ALLOWED_ERR.
This method deletes a named attribute from this style declaration block and returns the value of the attribute.
CSSStyleDeclaration.setProperty( ) | set a CSS style attribute |
void setProperty(String propertyName, String value, String priority) throws DOMException;
This method throws a DOMException with a code of SYNTAX_ERR if the specified value argument is malformed. It throws a DOMException with a code of NO_MODIFICATION_ALLOWED_ERR if the style declaration or the attribute being set is read-only.
This method adds the named CSS attribute with its value and priority to this style declaration, or, if the declaration already contains a value for the named attribute, it simply sets the value and priority for that existing attribute.
Using setProperty( ) to add a new CSS attribute to a style declaration may insert the new attribute at any position and may, in fact, totally shuffle the order of all existing attributes. Therefore, you should not use setProperty( ) while you are iterating through the set of attribute names with the item( ) method.
CSSStyleRule | a style rule in a CSS style sheet |
CSSRule CSSStyleRule
This interface represents a style rule in a CSS style sheet. Style rules are the most common and important kinds of rules in style sheets: they specify style information that is to be applied to a specific set of document elements. selectorText is the string representation of the element selector for this rule, and style is a CSSStyleDeclaration object that represents the set of style names and values to apply to the selected elements.
CSSStyleSheet | a CSS style sheet |
CSS StyleSheet CSSStyleSheet
This interface represents a CSS style sheet. The cssRules property lists the rules contained in the style sheet, and the insertRule( ) and deleteRule( ) methods allow you to add and delete rules from that list.
CSSImportRule.styleSheet, CSSRule.parentStyleSheet
DOMImplementation.createCSSStyleSheet( )
CSSStyleSheet.deleteRule( ) | delete a rule from a style sheet |
void deleteRule(unsigned long index) throws DOMException;
This method throws a DOMException with a code of INDEX_SIZE_ERR if index is negative or greater than or equal to cssRules.length. It throws a DOMException with a code of NO_MODIFICATION_ALLOWED_ERR if this style sheet is read-only.
This method deletes the rule at the specified index from the cssRules array.
CSSStyleSheet.insertRule( ) | insert a rule into a style sheet |
unsigned long insertRule(String rule, unsigned long index) throws DOMException;
The value of the index argument.
This method throws a DOMException with one of the following code values in the following circumstances:
This method inserts (or appends) a new CSS rule at the specified index of the cssRules array of this style sheet.
CSSUnknownRule | an unrecognized rule in a CSS style sheet |
CSS CSSRule CSSUnknownRule
This interface represents a rule in a CSS style sheet that the browser did not recognize and could not parse (typically because it is defined by a version of the CSS standard that the browser does not support). Note that this interface does not define any properties or methods of its own. The text of the unrecognized rule is available through the inherited cssText property.
CSSValue | the value of a CSS style attribute |
CSSPrimitiveValue, CSSValueList
The following constants specify the valid values for the cssValueType property:
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.
CSSPrimitiveValue, CSSValueList
CSSStyleDeclaration.getPropertyCSSValue( ), CSSValueList.item( )
CSSValueList | a CSSValue that holds an array of CSSValue objects |
CSSValue CSSValueList
This interface represents an array of CSSValue objects and is itself a type of CSSValue. The item( ) method can be used to retrieve the CSSValue object at a specified position, but in JavaScript, it is easier to simply index the array using standard square-bracket notation.
The order of CSSValue objects in a CSSValueList array is the order in which they appear in the CSS style declaration. Some CSS attributes whose value is a CSSValueList may also have the value none. This special value translates into a CSSValueList object with a length of 0.
CSSValueList.item( ) | get the CSSValue at the specified position |
CSSValue item(unsigned long index);
The CSSValue object at the specified position in this CSSValueList, or null if index is negative or is greater than or equal to length.
Document | an HTML or XML document |
Node Document
HTMLDocument
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.
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.
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.
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.
AbstractView.document, HTMLFrameElement.contentDocument, HTMLIFrameElement.contentDocument, HTMLObjectElement.contentDocument, Node.ownerDocument
DOMImplementation.createDocument( )
Document.createAttribute( ) | create a new Attr node |
Attr createAttribute(String name) throws DOMException;
A newly created Attr node with its nodeName property set to name.
This method throws a DOMException with a code of INVALID_CHARACTER_ERR if name contains an illegal character.
Document.createAttributeNS( ) | create an Attr with a name and namespace |
Attr createAttributeNS(String namespaceURI, String qualifiedName) throws DOMException;
A newly created Attr node with the specified name and namespace.
This method may throw a DOMException with one of the following code values in the following circumstances:
createAttributeNS( ) is just like createAttribute( ) except that the created Attr node has a name and namespace instead of just a name. This method is useful only with XML documents that use namespaces.
Document.createCDATASection( ) | create a new CDATASection node |
CDATASection createCDATASection(Stringdata) throws DOMException;
A newly created CDATASection node, with the specified data as its contents.
If the document is an HTML document, this method throws a DOMException with a code of NOT_SUPPORTED_ERR because HTML documents do not allow CDATASection nodes.
Document.createComment( ) | create a new Comment node DOM Level 1 Core |
Comment createComment(String data);
A newly created Comment node, with the specified data as its text.
Document.createDocumentFragment( ) | create a new, empty DocumentFragment node |
DocumentFragment createDocumentFragment( );
A newly created DocumentFragment node with no children.
Document.createElement( ) | create a new Element node |
Element createElement(String tagName) throws DOMException;
A newly created Element node with the specified tag name.
This method throws a DOMException with a code of INVALID_CHARACTER_ERR if tagName contains an illegal character.
Document.createElementNS( ) | create a new Element node using a namespace |
Element createElementNS(String namespaceURI, String qualifiedName) throws DOMException;
A newly created Element node, with the specified tag name and namespace.
This method may throw a DOMException with one of the following code values in the following circumstances:
createElementNS( ) is just like createElement( ) except that the created Element node has a name and namespace instead of just a name. This method is useful only with XML documents that use namespaces.
Document.createEntityReference( ) | create a new EntityReference node |
EntityReference createEntityReference(String name) throws DOMException;
A new EntityReference node that references an entity with the specified name.
This method may throw a DOMException with one of the following code values:
This method creates and returns an EntityReference node that refers to an entity with the specified name. Note that it always throws an exception if this is an HTML document, because HTML does not allow entity references. If this document has a DocumentType node, and if that DocumentType defines an Entity object with the specified name, the returned EntityReference has the same children as the referenced Entity node.
Document.createEvent( ) | create an Event object |
Event createEvent(String eventType) throws DOMException;
A newly created Event object of the specified type.
This method throws a DOMException with a code of NOT_SUPPORTED_ERR if the implementation does not support events of the requested type.
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.
Document.createNodeIterator( ) | create a NodeIterator for this document |
NodeIterator createNodeIterator(Node root, unsigned long whatToShow, NodeFilter filter, boolean entityReferenceExpansion) throws DOMException;
A newly created NodeIterator object.
This method throws a DOMException with a code of NOT_SUPPORTED_ERR if the root argument is null.
This method creates and returns a new NodeIterator object to iterate over the subtree rooted at the root node, using the specified filters.
This method is not actually part of the Document interface but is instead defined by the DocumentTraversal interface. If an implementation supports the Traversal module, the Document object always implements DocumentTraversal and defines this method.
Document.createProcessingInstruction( ) | create a ProcessingInstruction node |
ProcessingInstruction createProcessingInstruction(String target, String data) throws DOMException;
A newly created ProcessingInstruction node.
This method may throw a DOMException with one of the following code values in the following circumstances:
Document.createRange( ) | create a Range object |
Range createRange( );
A newly created Range object with both boundary points set to the beginning of the document.
This method creates a Range object that can be used to represent a region of this document or of a DocumentFragment associated with this document.
Note that this method is actually defined not by the Document interface but by the DocumentRange interface. If an implementation supports the Range module, the Document object always implements DocumentRange and defines this method.
Document.createTextNode( ) | create a new Text node |
Text createTextNode(String data);
A newly created Text node that represents the specified data string.
Document.createTreeWalker( ) | create a TreeWalker for this document |
TreeWalker createTreeWalker(Node root, unsigned long whatToShow, NodeFilter filter, boolean entityReferenceExpansion) throws DOMException;
A newly created TreeWalker object.
This method throws a DOMException with a code of NOT_SUPPORTED_ERR if the root argument is null.
This method creates and returns a new TreeWalker object to traverse the subtree rooted at the root node, using the specified filters.
This method is not actually part of the Document interface but is instead defined by the DocumentTraversal interface. If an implementation supports the Traversal module, the Document object always implements DocumentTraversal and defines this method.
Document.getElementById( ) | find an element with the specified unique ID |
DOM Level 2 Core; in DOM Level 1, defined by HTMLDocument
Element getElementById(String elementId);
The Element node that represents the document element with the specified id attribute, or null if no such element is found.
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.
Document.getElementsByTagName( ), Element.getElementsByTagName( ), HTMLDocument.getElementsByName( )
Document.getElementsByTagName( ) | return all Element nodes with the specified name |
Node[] getElementsByTagName(String tagname);
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.
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.
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 }
Document.getElementById( ), Element.getElementsByTagName( ), HTMLDocument.getElementsByName( )
Document.getElementsByTagNameNS( ) | return all Element nodes with a specified name and namespace |
Node[] getElementsByTagNameNS(String namespaceURI, String localName);
A read-only array (technically, a NodeList) of all Element nodes in the document tree that have the specified namespace and local name.
This method works just like getElementsByTagName( ) except that it searches for elements by namespace and name. It is useful only with XML documents that use namespaces.
Document.getOverrideStyle( ) | get the override style for a specified element |
CSSStyleDeclaration getOverrideStyle(Element elt, String pseudoElt);
A CSSStyleDeclaration object that represents the override style information for the specified element and pseudoelement. The returned object typically also implements the more commonly used CSS2Properties interfaces.
This method returns a CSSStyleDeclaration object (which typically also implements CSS2Properties) for a specified element and optional pseudoelement. You may make use of this returned object to make changes to the displayed style of the specified element without disturbing the inline style of that element and without modifying the style sheets of the document. Conceptually, the returned value represents a style declaration within an "override" style sheet that takes precedence over all other style sheets and inline styles (except for !important declarations in the user style sheet).
Note that this method is defined not by the Document interface but by the DocumentCSS interface. If an implementation supports the CSS module, the Document object always implements DocumentCSS and defines this method.
CSSStyleDeclaration, CSS2Properties, AbstractView.getComputedStyle( ), Reference
Document.importNode( ) | copy a node from another document for use in this document |
Node importNode(Node importedNode, boolean deep) throws DOMException;
A copy of importedNode (and possibly all of its descendants) with its ownerDocument set to this document.
This method throws a DOMException with a code of NOT_SUPPORTED_ERR if importedNode is a Document or DocumentType node, since those types of nodes cannot be imported.
This method is passed a node defined in another document and returns a copy of the node that is suitable for insertion into this document. If deep is true, all descendants of the node are also copied. The original node and its descendants are not modified in any way. The returned copy has its ownerDocument property set to this document but has a parentNode of null since it has not yet been inserted into the document. EventListener functions registered on the original node or tree are not copied.
When an Element node is imported, only the attributes that are explicitly specified in the source document are imported with it. When an Attr node is imported, its specified property is automatically set to true.
DocumentCSS | see Document |
DocumentEvent | see Document |
DocumentFragment | adjacent nodes and their subtrees |
Node DocumentFragment
The DocumentFragment interface represents a portion -- or fragment -- of a document. More specifically, it represents one or more adjacent Document nodes and all of the descendants of each. DocumentFragment nodes are never part of a document tree, and the inherited parentNode property is always null. DocumentFragment nodes exhibit a special behavior that makes them quite useful, however: when a request is made to insert a DocumentFragment into a document tree, it is not the DocumentFragment node itself that is inserted but each of the children of the DocumentFragment instead. This makes DocumentFragment useful as a temporary placeholder for nodes that you wish to insert, all at once, into a document. DocumentFragment is also particularly useful for implementing document cut, copy, and paste operations, particularly when combined with the Range interface.
You can create a new, empty DocumentFragment with Document.createDocumentFragment( ), or you can use Range.extractContents( ) or Range.cloneContents( ) to obtain a DocumentFragment that contains a fragment of an existing document.
Document.createDocumentFragment( ), Range.cloneContents( ), Range.extractContents( )
DocumentRange | see Document |
DocumentStyle | see Document |
DocumentTraversal | see Document |
DocumentType | the DTD of an XML document |
Node DocumentType
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.
Document.doctype
DOMImplementation.createDocument( )
DOMImplementation.createDocumentType( )
DocumentView | see Document |
DOMException | signals exceptions or errors for core DOM objects |
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.
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.
DOMImplementation | methods independent of any particular document |
The DOMImplementation interface and its HTMLDOMImplementation and DOMImplementationCSS subinterfaces are placeholders for methods that are not specific to any particular Document object but rather are "global" to an implementation of the DOM. You can obtain a reference to the DOMImplementation object through the implementation property of any Document object.
Document.implementation
DOMImplementation.createCSSStyleSheet( ) | create a CSSStyleSheet object |
CSSStyleSheet createCSSStyleSheet(String title, String media) throws DOMException;
A CSSStyleSheet object.
A DOMException with a code of SYNTAX_ERR if the media argument is malformed.
This method creates a new CSSStyleSheet object. Note, however, that as of Level 2, the DOM standard does not yet define any way to associate a newly created CSSStyleSheet object with a document.
createCSSStyleSheet( ) is defined not by the DOMImplementation interface but by its DOMImplementationCSS subinterface. If an implementation supports the "CSS" feature, its DOMImplementation object implements this method.
DOMImplementation.createDocument( ) | create a new Document and the specified root element |
Document createDocument(String namespaceURI, String qualifiedName, DocumentType doctype) throws DOMException;
A Document object with its documentElement property set to a root Element node of the specified type.
This method may throw a DOMException with the following code values in the following circumstances:
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.
DOMImplementation.createDocumentType( ), DOMImplementation.createHTMLDocument( )
DOMImplementation.createDocumentType( ) | create a DocumentType node |
DocumentType createDocumentType(String qualifiedName, String publicId, String systemId) throws DOMException;
A new DocumentType object with an ownerDocument property of null.
This method may throw a DOMException with one of the following code values:
This method creates a new DocumentType node. This method specifies only an external subset of the document type. As of Level 2, the DOM standard does not provide any way for specifying an internal subset, and the returned DocumentType does not define any Entity or Notation nodes. This method is useful only with XML documents and may not be supported by HTML-only implementations.
DOMImplementation.createHTMLDocument( ) | create a skeletal HTML document |
HTMLDocument createHTMLDocument(String title);
The new HTMLDocument object.
This method creates a new HTMLDocument object with a skeletal document tree that includes the specified title. The documentElement property of the returned object is an <html> element, and this root element has <head> and <body> tags as its children. The <head> element in turn has a <title> child, which has the specified title string as its child.
createHTMLDocument( ) is defined not by the DOMImplementation interface but by its HTMLDOMImplementation subinterface. If an implementation supports the "HTML" feature, its DOMImplementation object implements this method.
DOMImplementation.hasFeature( ) | determine whether the implementation supports a feature |
boolean hasFeature(String feature, String version);
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.
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. |
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 }
DOMImplementationCSS | see DOMImplementation |
Element | an HTML or XML element |
Node Element
HTMLElement
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.
Attr.ownerElement, Document.documentElement
Document.getOverrideStyle( ), AbstractView.getComputedStyle( )
Document.createElement( ), Document.createElementNS( ), Document.getElementById( )
Element.getAttribute( ) | return the string value of a named attribute |
String getAttribute(String name);
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 ("").
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( ).
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;
Element.getAttributeNode( ) | return the Attr node for the named attribute |
Attr getAttributeNode(String name);
An Attr node whose descendants represent the value of the named attribute, or null if this element has no such attribute.
getAttributeNode( ) returns an Attr node that represents the value of a named attribute. Note that this Attr node can also be obtained through the attributes property inherited from the Node interface.
The attribute value is represented by the descendants of the Attr nodes. In HTML documents, an Attr node has a single Text node child, and it is always easier to query an attribute value by calling getAttribute( ), which returns the value as a string. getAttributeNode( ) is necessary only when you are working with XML documents that contain entity references in their attribute values.
Element.getAttribute( ), Element.getAttributeNodeNS( ), Reference
Element.getAttributeNodeNS( ) | return the Attr node for an attribute with a namespace |
Attr getAttributeNodeNS(String namespaceURI, String localName);
The Attr node whose descendants represent the value of the specified attribute, or null if this element has no such attribute.
This method works like getAttributeNode( ), except that the attribute is specified by the combination of a namespace URI and a local name defined within that namespace. This method is useful only with XML documents that use namespaces.
Element.getAttributeNS( ) | get the value of an attribute that uses namespaces |
String getAttributeNS(String namespaceURI, String localName);
The string value of the named attribute. If the attribute is not explicitly specified in the document and does not have a default value specified by the document type, this method returns the empty string.
This method works just like the getAttribute( ) method, except that the attribute is specified by a combination of namespace URI and local name within that namespace. This method is useful only with XML documents that use namespaces.
Element.getElementsByTagName( ) | find descendant elements with a specified tag name |
Node[] getElementsByTagName(String name);
An array (technically, a NodeList) of Element objects that are descendants of this element and have the specified tag name.
This method traverses all descendants of this element and returns an array (really a NodeList object) of Element nodes representing all document elements with the specified tag name. The elements in the returned array appear in the same order in which they appear in the source document.
Note that the Document interface also has a getElementsByTagName( ) method that works just like this one but that traverses the entire document, rather than just the descendants of a single element. Do not confuse this method with HTMLDocument.getElementsByName( ), which searches for elements based on the value of their name attributes rather than by their tag names.
You can find all <div> tags in a document with code like the following:
var divisions = document.body.getElementsByTagName("div");
And you can find all <p> tags within the a <div> tag with code like this:
var paragraphs = divisions[0].getElementsByTagname("p");
Document.getElementById( ), Document.getElementsByTagName( ), HTMLDocument.getElementsByName( )
Element.getElementsByTagNameNS( ) | return descendant elements with the specified name and namespace |
Node[] getElementsByTagNameNS(String namespaceURI, String localName);
An array (technically, a NodeList) of Element objects that are descendants of this element and have the specified name and namespace.
This method works like getElementsByTagName( ), except that the tag name of the desired elements is specified as a combination of a namespace URI and a local name defined within that namespace. This method is useful only with XML documents that use namespaces.
Document.getElementsByTagNameNS( ), Element.getElementsByTagName( )
Element.hasAttribute( ) | determine whether this element has a specified attribute |
boolean hasAttribute(String name);
true if this element has a specified or default value for the named attribute, and false otherwise.
This method determines whether an element has an attribute with the specified name, but does not return the value of that attribute. Note that hasAttribute( ) returns true if the named attribute is explicitly specified in the document and also if the named attribute has a default value specified by the document type.
Reference , Element.getAttribute( ), Element.setAttribute( )
Element.hasAttributeNS( ) | determine whether this element has a specified attribute |
boolean hasAttributeNS(String namespaceURI, String localName);
true if this element has an explicitly specified value or a default value for the specified attribute; false otherwise.
This method works like hasAttribute( ), except that the attribute to be checked for is specified by namespace and name. This method is useful only with XML documents that use namespaces.
Element.removeAttribute( ) | delete a named attribute of an element |
void removeAttribute(String name);
This method may throw a DOMException with a code of NO_MODIFICATION_ALLOWED_ERR if this element is read-only and does not allow its attributes to be removed.
removeAttribute( ) deletes a named attribute from this element. If the named attribute has a default value specified by the document type, subsequent calls to getAttribute( ) will return that default value. Attempts to remove nonexistent attributes or attributes that are not specified but have a default value are silently ignored.
Element.removeAttributeNode( ) | remove an Attr node from an element |
Attr removeAttributeNode(Attr oldAttr) throws DOMException;
The Attr node that was removed.
This method may throw a DOMException with the following code values:
This method removes (and returns) an Attr node from the set of attributes of an element. If the removed attribute has a default value specified by the DTD, a new Attr is added representing this default value. If is often simpler to use removeAttribute( ) instead of this method.
Element.removeAttributeNS( ) | delete an attribute specified by name and namespace |
void removeAttributeNS(String namespaceURI, String localName);
This method may throw a DOMException with a code of NO_MODIFICATION_ALLOWED_ERR if this element is read-only and does not allow its attributes to be removed.
removeAttributeNS( ) works just like removeAttribute( ), except that the attribute to be removed is specified by name and namespace instead of simply by name. This method is useful only with XML documents that use namespaces.
Element.getAttributeNS( ), Element.removeAttribute( ), Element.setAttributeNS( )
Element.setAttribute( ) | create or change an attribute of an element |
void setAttribute(String name, String value) throws DOMException;
This method may throw a DOMException with the following code values:
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( ).
// 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"); }
Element.getAttribute( ), Element.removeAttribute( ), Element.setAttributeNode( )
Element.setAttributeNode( ) | add a new Attr node to an Element |
Attr setAttributeNode(Attr newAttr) throws DOMException;
The Attr node that was replaced by newAttr, or null if no attribute was replaced.
This method may throw a DOMException with a code of the following values:
This method adds a new Attr node to the set of attributes of an Element node. If an attribute with the same name already exists for the Element, newAttr replaces that attribute, and the replaced Attr node is returned. If no such attribute already exists, this method defines a new attribute for the Element.
It is usually easier to use setAttribute( ) instead of setAttributeNode( ). However, you should use setAttributeNode( ) when you need to define an attribute whose value contains an entity reference for an XML document.
Element.setAttributeNodeNS( ) | add a namespace Attr node to an Element |
Attr setAttributeNodeNS(Attr newAttr) throws DOMException;
The Attr node that was replaced by newAttr, or null if no attribute was replaced.
This method throws exceptions for the same reasons as setAttributeNode( ). It may also throw a DOMException with a code of NOT_SUPPORTED_ERR to signal that the method is not implemented because the current implementation does not support XML documents and namespaces.
This method works just like setAttributeNode( ), except that it is designed for use with Attr nodes that represent attributes specified by namespace and name.
This method is useful only with XML documents that use namespaces. It may be unimplemented (i.e., throw a NOT_SUPPORTED_ERR) on browsers that do not support XML documents.
Attr, Element.setAttributeNS( ), Element.setAttributeNode( )
Element.setAttributeNS( ) | create or change an attribute with a namespace |
void setAttributeNS(String namespaceURI, String qualifiedName, String value) throws DOMException;
This method may throw a DOMException with the following code values:
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.
ElementCSSInlineStyle | see HTMLElement |
Entity | an entity in an XML DTD |
Node Entity
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.
EntityReference | a reference to an entity defined in an XML DTD |
Node EntityReference
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 < 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.
Document.createEntityReference( )
Event | information about an event |
MutationEvent, UIEvent
These constants are the legal values of the eventPhase property; they represent the current phase of event propagation for this event:
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".
EventListener, EventTarget, MouseEvent, UIEvent; Chapter 19
EventTarget.dispatchEvent( )
Document.createEvent( )
Event.initEvent( ) | initialize the properties of a new Event |
void initEvent(String eventTypeArg, boolean canBubbleArg, boolean cancelableArg);
This method initializes the type, bubbles, and cancelable properties of a synthetic Event object created by Document.createEvent( ). This method may be called on newly created Event objects only before they have been dispatched with the EventTarget.dispatchEvent( ) method.
Event.preventDefault( ) | cancel default action of an event |
void preventDefault( );
This method tells the web browser not to perform the default action (if any) associated with this event. For example, if the type property is "submit", any event handler called during any phase of event propagation can prevent the form submission by calling this method. Note that if the cancelable property of an Event object is false, either there is no default action or there is a default action that cannot be prevented. In either case, calling this method has no effect.
Event.stopPropagation( ) | do not dispatch an event any further |
void stopPropagation( );
This method stops the propagation of an event and prevents it from being dispatched to any other Document nodes. It may be called during any phase of event propagation. Note that this method does not prevent other event handlers on the same Document node from being called, but it does prevent the event from being dispatched to any other nodes.
EventException | signals an event-specific exception or error |
The following constant defines the one legal value for the code property of an EventException object. Note that this constant is a static property of EventException, not a property of individual exception objects.
An EventException is thrown by certain event-related methods to signal a problem of some sort. (In the DOM Level 2 specification, an exception of this type is thrown only by EventTarget.dispatchEvent( )).
EventListener | an event handler function DOM Level 2 Events |
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.
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.
// 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);
Event, EventTarget; Chapter 19
EventTarget.addEventListener( ), EventTarget.removeEventListener( )
EventTarget | event listener registration methods |
In DOM implementations that support events (i.e., those that support the "Events" feature), all nodes in the document tree implement this interface and maintain a set or list of event listener functions for each node. The addEventListener( ) and removeEventListener( ) methods allow listener functions to be added and removed from this set.
Event, EventListener; Chapter 19
Event.currentTarget, Event.target, MouseEvent.relatedTarget
MouseEvent.initMouseEvent( )
EventTarget.addEventListener( ) | register an event handler |
void addEventListener(String type, EventListener listener, boolean useCapture);
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.
EventTarget.dispatchEvent( ) | dispatch a synthetic event to this node |
boolean dispatchEvent(Event evt) throws EventException;
false if the preventDefault( ) method of evt was called at any time during the propagation of the event, or true otherwise.
This method throws an EventException with its code property set to EventException.UNSPECIFIED_EVENT_TYPE_ERR if the Event object evt was not initialized or if its type property was null or the empty string.
This method dispatches a synthetic event created with Document.createEvent( ) and initialized with the initialization method defined by the Event interface or one of its subinterfaces. The node on which this method is called becomes the target of the event, but the event first propagates down the document tree during the capturing phase, and then, if the bubbles property of the event is true, it bubbles up the document tree after being handled at the event target itself.
Document.createEvent( ), Event.initEvent( ), MouseEvent.initMouseEvent( )
EventTarget.removeEventListener( ) | delete an event listener |
v oid removeEventListener(String type, EventListener listener, boolean useCapture);
This method removes the specified event listener function. The type and useCapture arguments must be the same as they were in the corresponding call to addEventListener( ). If no event listener is found that matches the specified arguments, this method does nothing.
Once an event listener function has been removed by this method, it will no longer be invoked for the specified type of event on this node. This is true even if the event listener is removed by another event listener registered for the same type of event on the same node.
HTMLAnchorElement | a hyperlink or anchor in an HTML document |
Node Element HTMLElement HTMLAnchorElement
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 |
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.
// 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( );
Link and Anchor objects in the client-side reference section
HTMLAnchorElement.blur( ) | take keyboard focus away from a hyperlink |
void blur( );
For web browsers that allow hyperlinks to have the keyboard focus, this method takes keyboard focus away from a hyperlink.
HTMLAnchorElement.focus( ) | make a link or anchor visible and give it keyboard focus |
void focus( );
This method scrolls the document so the specified anchor or hyperlink is visible. If the element is a hyperlink and the browser allows hyperlinks to have keyboard focus, this method also gives keyboard focus to the element.
HTMLBodyElement | the <body> of an HTML document |
Node Element HTMLElement HTMLBodyElement
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.
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
Document object in the client-side reference section
HTMLCollection | array of HTML elements accessible by position or name |
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.
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
HTMLDocument.anchors, HTMLDocument.applets, HTMLDocument.forms, HTMLDocument.images, HTMLDocument.links, HTMLFormElement.elements, HTMLMapElement.areas, HTMLSelectElement.options, HTMLTableElement.rows, HTMLTableElement.tBodies, HTMLTableRowElement.cells, HTMLTableSectionElement.rows
HTMLCollection.item( ) | get an element by position |
Node item(unsigned long index);
The element at the specified index, or null if index is less than zero or greater than or equal to the length property.
The item( ) method returns a numbered element from an HTMLCollection. In JavaScript, it is easier to treat the HTMLCollection as an array and to index it using array notation.
var c = document.images; // This is an HTMLCollection var img0 = c.item(0); // You can use the item( ) method this way var img1 = c[1]; // But this notation is easier and more common
HTMLCollection.namedItem( ) | get an element by name |
Node namedItem(String name);
An element with the specified name, or null if no elements in the HTMLCollection have that name.
This method finds and returns an element from the HTMLCollection that has the specified name. If any element has an id attribute whose value is the specified name, that element is returned. If no such element is found, an element whose name attribute has the specified value is returned. If no such element exists, namedItem( ) returns null.
Note that any HTML element may be given an id attribute, but only certain HTML elements -- such as forms, form elements, images, and anchors -- may have a name attribute.
In JavaScript, it is easier to treat the HTMLCollection as an associative array and to specify name between square brackets using array notation.
var forms = document.forms; // An HTMLCollection of forms var address = forms.namedItem("address"); // Finds <form name="address"> var payment = forms["payment"] // Simpler syntax: finds <form name="payment"> var login = forms.login; // Also works: finds <form name="login">
HTMLDocument | the root of an HTML document tree |
Node Document HTMLDocument
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.
Document.getElementById( ), HTMLBodyElement; Document object in the client-side reference section
HTMLDOMImplementation.createHTMLDocument( )
HTMLDocument.close( ) | close an open document and display it |
void close( );
This method closes a document stream that was opened with the open( ) method and forces any buffered output to be displayed. See the Document.close( ) entry in the client-side reference section for full details.
HTMLDocument.open( ); Document.close( ) in the client-side reference section
HTMLDocument.getElementById( ) | see Document.getElementById( ) |
HTMLDocument.getElementsByName( ) | find elements with the specified name attribute |
Node[] getElementsByName(String elementName);
An array (really a NodeList) of elements that have a name attribute of the specified value. If no such elements are found, the returned NodeList is empty and has a length of 0.
This method searches an HTML document tree for Element nodes that have a name attribute of the specified value and returns a NodeList (which you can treat as an array) containing all matching elements. If there are no matching elements, a NodeList with length 0 is returned.
Do not confuse this method with the Document.getElementById( ) method, which finds a single Element based on the unique value of an id attribute, or with the Document.getElementsByTagName( ) method, which returns a NodeList of elements with the specified tag name.
Document.getElementById( ), Document.getElementsByTagName( )
HTMLDocument.open( ) | begin a new document, erasing the current one |
void open( );
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.
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
HTMLDocument.close( ), HTMLDocument.write( ); Document.open( ) in the client-side reference section
HTMLDocument.write( ) | append HTML text to an open document |
void write(String text);
This method appends the specified HTML text to the document, which must have been opened with the open( ) method and must not yet have been closed with close( ).
See Document.write( ) in the client-side reference section for complete details, but note that this standardized version of that Level 0 method accepts only a single string argument, not an arbitrary number of arguments.
HTMLDocument.open( ); Document.write( ) in the client-side reference section
HTMLDocument.writeln( ) | append HTML text and a newline to an open document |
void writeln(String text);
This method is like HTMLDocument.write( ), except that it follows the appended text with a newline character, which can be useful when writing the content of a <pre> tag, for example.
Document.writeln( ) in the client-side reference section
HTMLDOMImplementation | see DOMImplementation |
HTMLElement | the base interface for all HTML elements |
Node Element HTMLElement
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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> |
* Indicates interfaces documented in this book.
** Indicates deprecated elements and attributes.
*** Indicates attributes added in HTML DOM Level 2 working draft.
HTMLElement in the client-side reference section
HTMLDocument.body
HTMLSelectElement.add( )
HTMLTableElement.createCaption( ), HTMLTableElement.createTFoot( ), HTMLTableElement.createTHead( ), HTMLTableElement.insertRow( ), HTMLTableRowElement.insertCell( ), HTMLTableSectionElement.insertRow( )
HTMLFormElement | a <form> in an HTML document |
Node Element HTMLElement HTMLFormElement
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 |
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.
Form object in the client-side reference section
HTMLButtonElement.form, HTMLFieldSetElement.form, HTMLInputElement.form, HTMLIsIndexElement.form, HTMLLabelElement.form, HTMLLegendElement.form, HTMLObjectElement.form, HTMLOptionElement.form, HTMLSelectElement.form, HTMLTextAreaElement.form
HTMLFormElement.reset( ) | reset the elements of a form to their default values |
void reset( );
This method resets each of the elements of a form to its default value. The results of calling this method are like the results of a user clicking on a Reset button, except that the onreset event handler of the form is not invoked.
Form.reset( ) in the client-side reference section
HTMLFormElement.submit( ) | submit a form |
void submit( );
This method submits the values of the form elements to the form handler specified by the form's action property. It submits a form in the same way that a user's clicking on a Submit button does, except that the onsubmit event handler of the form is not triggered.
Form.submit( ) in the client-side reference section
HTMLInputElement | an input element in an HTML form |
Node Element HTMLElement HTMLInputElement
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.
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)
HTMLInputElement.blur( ) | take keyboard focus away from this element |
void blur( );
This method takes keyboard focus away from this form element.
HTMLInputElement.click( ) | simulate a mouse-click on a form element |
void click( );
This method simulates a mouse-click on a Button, Checkbox, Radio, Reset, or Submit form element. It does not trigger the onclick event handler for the input element.
When called on Button elements, it may (or may not) produce the visual appearance of a button-click, but it has no other effect since it does not trigger the onclick event handler for the button. For Checkbox elements, it toggles the checked property. It makes unchecked Radio elements become checked but leaves checked elements alone. When called on Reset and Submit elements, the click( ) method causes the form to be reset or submitted.
HTMLInputElement.focus( ) | give keyboard focus to this element |
void focus( );
This method transfers keyboard focus to this element so the user can interact with it without first clicking on it.
HTMLInputElement.select( ) | select the contents of a Text element |
void select( );
This method selects any text displayed in Text, Password, and FileUpload elements. In most browsers, this means that the user's next keystroke will replace the current text rather than being appended to it.
HTMLOptionElement | an <option> in an HTML form |
Node Element HTMLElement HTMLOptionElement
This interface describes an <option> element within a <select> element.
HTMLFormElement, HTMLInputElement, HTMLSelectElement; Option and Select objects in the client-side reference section; Chapter 15
HTMLSelectElement | a <select> element in an HTML form |
Node Element HTMLElement HTMLSelectElement
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.
HTMLFormElement, HTMLOptionElement; Option and Select objects in the client-side reference section; Chapter 15
HTMLSelectElement.add( ) | insert an <option> element |
void add(HTMLElement element, HTMLElement before) throws DOMException;
This method throws a DOMException with a code of NOT_FOUND_ERR if the before argument specifies an object that is not a member of the options array.
This method adds a new <option> element to this <select> element. element is an HTMLOptionElement that represents the <option> element to be added. before specifies the HTMLOptionElement before which element is to be added. If before is part of an OPTGROUP, element is always inserted as part of that same group. If before is null, element becomes the last child of the <select> element.
Select object in the client-side reference section
HTMLSelectElement.blur( ) | take keyboard focus away from this element |
void blur( );
This method takes keyboard focus away from this element.
HTMLSelectElement.focus( ) | give keyboard focus to this element |
void focus( );
This method transfers keyboard focus to this <select> element so the user can interact with it using the keyboard instead of the mouse.
HTMLSelectElement.remove( ) | remove an <option> |
void remove(long index);
This method removes the <option> element at the specified position in the options array. If the specified index is less than zero or greater than or equal to the number of options, the remove( ) method ignores it and does nothing.
Select object in the client-side reference section
HTMLTableCaptionElement | a <caption> in an HTML table |
Node Element HTMLElement HTMLTableCaptionElement
A <caption> element in an HTML table.
HTMLTableElement.caption
HTMLTableCellElement | a <td> or <th> cell in an HTML table |
Node Element HTMLElement HTMLTableCellElement
In addition to the cellIndex property, this interface defines the properties in the following table, which correspond directly to the HTML attributes of the <td> and <th> elements.
Property |
Attribute |
Description |
---|---|---|
String abbr |
abbr |
See HTML specification |
String align |
align |
Horizontal alignment of cell |
String axis |
axis |
See HTML specification |
deprecated String bgColor |
bgcolor |
Background color of cell |
String ch |
char |
Alignment character |
String chOff |
choff |
Alignment character offset |
long colSpan |
colspan |
Columns spanned by cell |
String headers |
headers |
id values for headers for this cell |
deprecated String height |
height |
Cell height in pixels |
deprecated boolean noWrap |
nowrap |
Don't word-wrap cell |
long rowSpan |
rowspan |
Rows spanned by cell |
String scope |
scope |
Scope of this header cell |
String vAlign |
valign |
Vertical alignment of cell |
deprecated String width |
width |
Cell width in pixels |
This interface represents <td> and <th> elements in HTML tables.
HTMLTableColElement | a <col> or <colgroup> in an HTML table |
Node Element HTMLElement HTMLTableColElement
This interface defines the properties in the following table, each of which corresponds to an HTML attribute of a <col> or <colgroup> element.
Property |
Attribute |
Description |
---|---|---|
String align |
align |
Default horizontal alignment |
String ch |
char |
Default alignment character |
String chOff |
choff |
Default alignment offset |
long span |
span |
Number of columns represented by this element |
String vAlign |
valign |
Default vertical alignment |
String width |
width |
Width of the column(s) |
This interface represents a <col> or <colgroup> element in an HTML table.
HTMLTableElement | a <table> in an HTML document |
Node Element HTMLElement HTMLTableElement
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 |
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.
HTMLTableCaptionElement, HTMLTableCellElement, HTMLTableColElement, HTMLTableRowElement, HTMLTableSectionElement
HTMLTableElement.createCaption( ) | get or create a <caption> |
HTMLElement createCaption( );
An HTMLTableCaptionElement object representing the <caption> element for this table. If the table already has a caption, this method simply returns it. If the table does not have an existing <caption>, this method creates a new (empty) one and inserts it into the table before returning it.
HTMLTableElement.createTFoot( ) | get or create a <tfoot> |
HTMLElement createTFoot( );
An HTMLTableSectionElement representing the <tfoot> element for this table. If the table already has a footer, this method simply returns it. If the table does not have an existing footer, this method creates a new (empty) <tfoot> element and inserts it into the table before returning it.
HTMLTableElement.createTHead( ) | get or create a <thead> |
HTMLElement createTHead( );
An HTMLTableSectionElement representing the <thead> element for this table. If the table already has a header, this method simply returns it. If the table does not have an existing header, this method creates a new (empty) <thead> element and inserts it into the table before returning it.
HTMLTableElement.deleteCaption( ) | delete the <caption> of a table |
void deleteCaption( );
If this table has a <caption> element, this method removes it from the document tree. Otherwise, it does nothing.
HTMLTableElement.deleteRow( ) | delete a row of a table |
void deleteRow(long index) throws DOMException;
This method throws a DOMException with a code of INDEX_SIZE_ERR if index is less than zero or is greater than or equal to the number of rows in the table.
This method deletes the row at the specified position from the table. Rows are numbered in the order in which they appear in the document source. Rows in <thead> and <tfoot> sections are numbered along with all other rows in the table.
HTMLTableElement.deleteTFoot( ) | delete the <tfoot> of a table |
void deleteTFoot( );
If this table has a <tfoot> element, this method removes it from the document tree. If the table has no footer, this method does nothing.
HTMLTableElement.deleteTHead( ) | delete the <thead> of a table |
void deleteTHead( );
If this table has a <thead> element, this method deletes it; otherwise, it does nothing.
HTMLTableElement.insertRow( ) | add a new, empty row to the table |
HTMLElement insertRow(long index) throws DOMException;
An HTMLTableRowElement that represents the newly inserted row.
This method throws a DOMException with a code of INDEX_SIZE_ERR if index is less than zero or greater than the number of rows in the table.
This method creates a new HTMLTableRowElement representing a <tr> tag and inserts it into the table at the specified position.
The new row is inserted in the same section and immediately before the existing row at the position specified by index. If index is equal to the number of rows in the table, the new row is appended to the last section of the table. If the table is initially empty, the new row is inserted into a new <tbody> section that is itself inserted into the table.
You can use the convenience method HTMLTableRowElement.insertCell( ) to add content to the newly created row.
HTMLTableRowElement | a <tr> element in an HTML table |
Node Element HTMLElement HTMLTableRowElement
In addition to the properties just listed, this interface also defines the properties in the following table, which correspond to the HTML attributes of the <tr> element.
Property |
Attribute |
Description |
---|---|---|
String align |
align |
Default horizontal alignment of cells in this row |
deprecated String bgColor |
bgcolor |
Background color of this row |
String ch |
char |
Alignment character for cells in this row |
String chOff |
choff |
Alignment character offset for cells in this row |
String vAlign |
valign |
Default vertical alignment for cells in this row |
This interface represents a row in an HTML table.
HTMLTableRowElement.deleteCell( ) | delete a cell in a table row |
void deleteCell(long index) throws DOMException;
This method throws a DOMException with a code of INDEX_SIZE_ERR if index is less than zero or is greater than or equal to the number of cells in the row.
This method deletes the cell at the specified position in the table row.
HTMLTableRowElement.insertCell( ) | insert a new, empty <td> element into a table row |
HTMLElement insertCell(long index) throws DOMException;
An HTMLTableCellElement object that represents the newly created and inserted <td> element.
This method throws a DOMException with a code of INDEX_SIZE_ERR if index is less than zero or is greater than the number of cells in the row.
This method creates a new <td> element and inserts it into the row at the specified position. The new cell is inserted immediately before the cell that is currently at the position specified by index. If index is equal to the number of cells in the row, the new cell is appended at the end of the row.
Note that this convenience method inserts <td> data cells only. If you need to add a header cell into a row, you must create and insert the <th> element using Document.createElement( ) and Node.insertBefore( ) or related methods.
HTMLTableSectionElement | a header, footer, or body section of a table |
Node Element HTMLElement HTMLTableSectionElement
In addition to the rows property, this interface defines the properties in the following table, which represent the attributes of the underlying HTML element.
Property |
Attribute |
Description |
---|---|---|
String align |
align |
Default horizontal alignment of cells in this section of the table |
String ch |
char |
Default alignment character for cells in this section |
String chOff |
choff |
Default alignment offset for cells in this section |
String vAlign |
valign |
Default vertical alignment for cells in this section |
This interface represents a <tbody>, <thead>, or <tfoot> section of an HTML table.
HTMLTableElement.tFoot, HTMLTableElement.tHead
HTMLTableSectionElement.deleteRow( ) | delete a row within a table section |
void deleteRow(long index) throws DOMException;
This method throws a DOMException with a code of INDEX_SIZE_ERR if index is less than zero or is greater than or equal to the number of rows in this section.
This method deletes the row at the specified position within this section. Note that for this method index specifies a row's position within its section, not within the entire table.
HTMLTableSectionElement.insertRow( ) | insert a new, empty row into this table section |
HTMLElement insertRow(long index) throws DOMException;
An HTMLTableRowElement that represents the newly created and inserted <tr> element.
This method throws a DOMException with a code of INDEX_SIZE_ERR if index is less than zero or is greater than the number of rows in this section.
This method creates a new <tr> element and inserts it into this table section at the specified position. If index equals the number of rows currently in the section, the new row is appended at the end of the section. Otherwise, the new row is inserted immediately before the row that is currently at the position specified by index. Note that for this method, index specifies a row position within a single table section, not within the entire table.
HTMLTextAreaElement | a <textarea> element in an HTML form DOM Level 1 HTML |
Node Element HTMLElement HTMLTextAreaElement
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).
HTMLFormElement, HTMLInputElement; Textarea in the client-side reference section; Chapter 15
HTMLTextAreaElement.blur( ) | take keyboard focus away from this element |
void blur( );
This method takes keyboard focus away from this element.
HTMLTextAreaElement.focus( ) | give keyboard focus to this element |
void focus( );
This method transfers keyboard focus to this element so the user can edit the displayed text without having to first click on the text area.
HTMLTextAreaElement.select( ) | select the text in this element |
void select( );
This method selects all the text displayed by this <textarea> element. In most browsers, this means that the text is highlighted and that new text entered by the user will replace the highlighted text instead of being appended to it.
LinkStyle | a style sheet associated with a node |
In DOM implementations that support the StyleSheets module, this interface is implemented by any Document node that links to a style sheet or defines an inline style sheet. The sheet property then provides a way to obtain the StyleSheet object associated with the node.
In HTML documents, the <style> and <link> elements implement this interface. Those elements are represented by the HTMLStyleElement and HTMLLinkElement interfaces, which do not have their own entries in this reference. See HTMLElement for more information about those interfaces.
In XML documents, style sheets are included with a processing instruction. See ProcessingInstruction for more information.
MediaList | a style sheet's list of media types |
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.
StyleSheet.media
MediaList.appendMedium( ) | add a new media type to the list |
void appendMedium(String newMedium) throws DOMException;
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.
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 |
DOM Level 2 StyleSheets
void deleteMedium(String oldMedium) throws DOMException;
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.
This method deletes the specified media type from this MediaList, or throws an exception if the list does not contain the specified type.
MediaList.item( ) | index an array of media types |
String item(unsigned long index);
The media type (a string) at the specified position within the MediaList, or null if index is negative or is greater than or equal to length. Note that in JavaScript, it is usually simpler to treat a MediaList object as an array and index it using square-bracket array notation instead of calling this method.
MouseEvent | details about a mouse event |
Event UIEvent MouseEvent
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.
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.
MouseEvent.initMouseEvent( ) | initialize the properties of a MouseEvent object |
void initMouseEvent(String typeArg, boolean canBubbleArg, boolean cancelableArg, AbstractView viewArg, long detailArg, long screenXArg, long screenYArg, long clientXArg, long clientYArg, boolean ctrlKeyArg, boolean altKeyArg, boolean shiftKeyArg, boolean metaKeyArg, unsigned short buttonArg, EventTarget relatedTargetArg);
The many arguments to this method specify the initial values of the properties of this MouseEvent object, including the properties inherited from the Event and UIEvent interfaces. The name of each argument clearly indicates the property for which it specifies the value, so they are not listed individually here.
This method initializes the various properties of a newly created MouseEvent object. It may be called only on a MouseEvent object created with Document.createEvent( ) and only before that MouseEvent is passed to EventTarget.dispatchEvent( ).
MutationEvent | details about a document change |
Event MutationEvent
The following constants represent the set of possible values for the attrChange property:
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( )):
MutationEvent.initMutationEvent( ) | initialize the properties of a new MutationEvent |
void initMutationEvent(String typeArg, boolean canBubbleArg, boolean cancelableArg, Node relatedNodeArg, String prevValueArg, String newValueArg, String attrNameArg, unsigned short attrChangeArg);
The various arguments to this method specify the initial values of the properties of this MutationEvent object, including the properties inherited from the Event interface. The name of each argument clearly indicates the property for which it specifies the value, so the arguments are not listed individually here.
This method initializes the various properties of a newly created MutationEvent object. It may be called only on a MutationEvent object created with Document.createEvent( ) and only before that MouseEvent is passed to EventTarget.dispatchEvent( ).
NamedNodeMap | a collection of nodes indexed by name or position |
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.
DocumentType.entities, DocumentType.notations, Node.attributes
NamedNodeMap.getNamedItem( ) | look up a node by name |
Node getNamedItem(String name);
The named node, or null if no node with that name was found.
NamedNodeMap.getNamedItemNS( ) | look up a node by name and namespace |
Node getNamedItemNS(String namespaceURI, String localName);
The element of the NamedNodeMap that has the specified namespaceURI and localName properties, or null if there is no such node.
getNamedItemNS( ) looks up an element of a NamedNodeMap by namespace and local name. It is useful only with XML documents that use namespaces.
NamedNodeMap.item( ) | return an element of a NamedNodeMap by position |
Node item(unsigned long index);
The node at the specified position, or null if index is less than zero or greater than or equal to the length of the NamedNodeMap.
This method returns a numbered element of a NamedNodeMap. In JavaScript, NamedNodeMap objects behave like read-only arrays, and you can use the node position as an array index within square brackets instead of calling this method.
Although the NamedNodeMap interface allows you to iterate through its nodes by position, it does not represent an ordered collection of nodes. Any changes made to the NamedNodeMap (such as by removeNamedItem( ) or setNamedItem( )) may result in a complete reordering of the elements. Thus, you must not modify a NamedNodeMap while you are iterating through its elements.
NamedNodeMap.removeNamedItem( ) | delete a node specified by name |
Node removeNamedItem(String name) throws DOMException;
The node that was removed.
This method throws a DOMException with a code of NO_MODIFICATION_ALLOWED_ERR if the NamedNodeMap is read-only and does not allow deletions, or a code of NOT_FOUND_ERR if no node with the specified name exists in the NamedNodeMap.
Deletes a named node from a NamedNodeMap. Note that if the NamedNodeMap represents the set of attributes for an Element, removing the Attr node for an attribute that was explicitly set in the document may cause the removed Attr to be automatically replaced by a new Attr node representing the default value (if any exists) of the attribute.
NamedNodeMap.removeNamedItemNS( ) | delete a node specified by namespace and name |
Node removeNamedItemNS(String namespaceURI, String localName) throws DOMException;
The node that was removed.
This method throws exceptions for the same reason as removeNamedItem( ).
This method works just like removeNamedItem( ), except that the node to be removed is specified by namespace and local name rather than just by name. This method is typically useful only with XML documents that use namespaces.
NamedNodeMap.setNamedItem( ) | add a node to or replace a node in a NamedNodeMap |
Node setNamedItem(Node arg) throws DOMException;
The node that was replaced, or null if no node was replaced.
This method may throw a DOMException with one of the following code values:
setNamedItem( ) adds the specified node to a NamedNodeMap and allows it to be looked up using the value of the node's nodeName property. If the NamedNodeMap already contains a node with that name, that node is replaced and becomes the return value of the method.
NamedNodeMap.setNamedItemNS( ) | add a node to a NamedNodeMap using namespaces |
Node setNamedItemNS(Node arg) throws DOMException;
The node that was replaced, or null if no node was replaced.
This method throws exceptions for the same reasons as setNamedItem( ). It may also throw a DOMException with a code of NOT_SUPPORTED_ERR if it is called in an implementation that does not support XML documents or XML namespaces.
This method works like setNamedItem( ), except that the node added to the NamedNodeMap can later be looked up by its namespaceURI and localName properties instead of by its nodeName property. This method is useful only with XML documents that use namespaces. Note that this method may be unsupported (i.e., may throw an exception) in implementations that do not support XML documents.
Node | a node in a document tree |
Attr, CharacterData, Document, DocumentFragment, DocumentType, Element, Entity, EntityReference, Notation, ProcessingInstruction
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
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 |
Node.appendChild( ) | insert a node as the last child of this node |
Node appendChild(Node newChild) throws DOMException;
The node that was added.
This method may throw a DOMException with one of the following code values in the following circumstances:
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.
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 }
Node.insertBefore( ), Node.removeChild( ), Node.replaceChild( )
Node.cloneNode( ) | duplicate a node and, optionally, all of its descendants |
Node cloneNode(boolean deep);
A copy of this node.
The cloneNode( ) method makes and returns a copy of the node on which it is called. If passed the argument true, it recursively clones all descendants of the node as well. Otherwise, it clones only the node and none of its children. The returned node is not part of the document tree, and its parentNode property is null. When an Element node is cloned, all of its attributes are also cloned. Note, however, that EventListener functions registered on a node are not cloned.
Node.hasAttributes( ) | determine whether a node has attributes |
boolean hasAttributes( );
true if this node has one or more attributes; false if it has none. Note that only Element nodes can have attributes.
Node.hasChildNodes( ) | determine whether a node has children |
boolean hasChildNodes( );
true if this node has one or more children; false if it has none.
Node.childNodes
Node.insertBefore( ) | insert a node into the document tree before the specified node |
Node insertBefore(Node newChild, Node refChild) throws DOMException;
The node that was inserted.
This method may throw a DOMException with the following code values:
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.
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) }
Node.appendChild( ), Node.removeChild( ), Node.replaceChild( )
Node.isSupported( ) | determine if a node supports a feature |
boolean isSupported(String feature, String version);
true if the node supports the specified version of the specified feature, and false if it does not.
The W3C DOM standard is modular, and implementations are not required to implement all modules or features of the standard. This method tests whether the implementation of this node supports the specified version of the named feature. See the Section reference page for a list of values for the feature and version arguments.
Node.normalize( ) | merge adjacent Text nodes and remove empty ones |
void normalize( );
This method traverses all descendants of this node and "normalizes" the document by removing any empty Text nodes and merging all adjacent Text nodes into a single node. This can sometimes be useful to simplify the tree structure after node insertions or deletions.
Node.removeChild( ) | remove (and return) the specified child of this node |
Node removeChild(Node oldChild) throws DOMException;
The node that was removed.
This method may throw a DOMException with the following code values in the following circumstances:
This method removes the specified child from the childNodes[] array of this node. It is an error to call this method with a node that is not a child. removeChild( ) returns the oldChild node after removing it. oldChild continues to be a valid node and may be reinserted into the document later.
You can delete the last child of the document body with this code:
document.body.removeChild(document.body.lastChild);
Node.appendChild( ), Node.insertBefore( ), Node.replaceChild( )
Node.replaceChild( ) | replace a child node with a new node |
Node replaceChild(Node newChild, Node oldChild) throws DOMException;
The node that was removed from the document and replaced.
This method may throw a DOMException with the following code values:
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.
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>
Node.appendChild( ), Node.insertBefore( ), Node.removeChild( )
NodeFilter | a function to filter the nodes of a document tree |
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:
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;
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.
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
NodeIterator.filter, TreeWalker.filter
Document.createNodeIterator( ), Document.createTreeWalker( )
NodeIterator | iterate through a filtered sequence of Document nodes |
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.
NodeFilter, TreeWalker; Chapter 17
Document.createNodeIterator( )
NodeIterator.detach( ) | free a NodeIterator object |
void detach( );
DOM implementations keep track of all NodeIterator objects created for a document, because they may need to modify the state of the NodeIterator when certain Document nodes are deleted. When you are certain that a NodeIterator isn't needed anymore, call detach( ) to tell the implementation that it no longer needs to keep track of it. Note, however, that once you call this method any subsequent call to nextNode( ) or previousNode( ) will throw an exception.
Calling detach( ) is not required, but doing so may improve performance when the document is being modified and the NodeIterator object is not immediately garbage collected.
NodeIterator.nextNode( ) | iterate to the next node |
Node nextNode( ) throws DOMException;
The next node in the sequence of nodes represented by this NodeIterator, or null if the last node has already been returned.
If this method is called after a call to detach( ), it throws a DOMException with a code of INVALID_STATE_ERR.
This method iterates forward through the sequence of nodes represented by this NodeIterator. If this is the first time it is called for a NodeIterator, it returns the first node in the sequence. Otherwise, it returns the node that follows the one that was previously returned.
// Create a NodeIterator to represent all elements in the document body var ni = document.createNodeIterator(document.body, NodeFilter.SHOW_ELEMENT, null, false); // Loop forward through all nodes in the iterator for(var e = ni.nextNode( ); e != null; e = ni.nextNode( )) { // Do something with element e }
NodeIterator.previousNode( ) | iterate to the previous node |
Node previousNode( ) throws DOMException;
The previous node in the sequence of nodes represented by this NodeIterator, or null if there is no previous node.
If this method is called after a call to detach( ), it throws a DOMException with a code of INVALID_STATE_ERR.
This method iterates backward through the sequence of nodes represented by this NodeIterator. It returns the node before the one that was most recently returned by previousNode( ) or nextNode( ). If there is no such node in the sequence, it returns null.
NodeList | a read-only array of nodes |
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!
Node.childNodes
Document.getElementsByTagName( ), Document.getElementsByTagNameNS( ), Element.getElementsByTagName( ), Element.getElementsByTagNameNS( ), HTMLDocument.getElementsByName( )
NodeList.item( ) | get an element of a NodeList |
Node item(unsigned long index);
The node at the specified position in the NodeList, or null if index is less than zero or greater than or equal to the length of the NodeList.
This method returns the specified element of a NodeList. In JavaScript, you can use the square-bracket array notation instead of calling item( ).
Notation | a notation in an XML DTD |
Node Notation
This infrequently used interface represents a notation declaration in the document type definition (DTD) of an XML document. In XML, notations are used to specify the format of an unparsed entity or to formally declare a processing instruction target.
The name of the notation is specified by the inherited nodeName property. Because notations appear in the DTD and not the document itself, Notation nodes are never part of the document tree, and the parentNode property is always null. The notations property of the DocumentType interface provides a way to look up Notation objects by notation name.
Notation objects are read-only and cannot be modified in any way.
ProcessingInstruction | a processing instruction in an XML document |
Node ProcessingInstruction
This infrequently used interface represents a processing instruction (or PI) in an XML document. Programmers working with HTML documents will never encounter a ProcessingInstruction node.
Document.createProcessingInstruction( )
Range | represents a contiguous range of a document |
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.
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.
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.
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.
Document.createRange( ), DocumentFragment; Chapter 17
Range.compareBoundaryPoints( )
Document.createRange( ), Range.cloneRange( )
Range.cloneContents( ) | copy range contents into a DocumentFragment |
DocumentFragment cloneContents( ) throws DOMException;
A DocumentFragment object that contains a copy of the document content within this range.
If this range includes a DocumentType node, this method throws a DOMException with a code of HIERARCHY_REQUEST_ERR.
This method duplicates the contents of this range and returns the results in a DocumentFragment object.
DocumentFragment, Range.deleteContents( ), Range.extractContents( )
Range.cloneRange( ) | make a copy of this range |
Range cloneRange( );
A new Range object that has the same boundary points as this range.
Range.collapse( ) | make one boundary point equal to the other |
void collapse(boolean toStart) throws DOMException;
This method sets one boundary point of the range to be the same as the other point. The point to be modified is specified by the toStart argument. After this method returns, the range is said to be "collapsed": it represents a single point within a document and has no content. When a range is collapsed like this, its collapsed property is true.
Range.compareBoundaryPoints( ) | compare positions of two ranges |
short compareBoundaryPoints(unsigned short how, Range sourceRange) throws DOMException;
-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.
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.
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:
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.deleteContents( ) | delete a region of the document |
void deleteContents( ) throws DOMException;
If any portion of the document that is represented by this range is read-only, this method throws a DOMException with a code of NO_MODIFICATION_ALLOWED_ERR.
This method deletes all document content represented by this range. When this method returns, the range is collapsed with both boundary points at the same position. Note that the deletion may result in adjacent Text nodes that can be merged with a call to Node.normalize( ).
See Range.cloneContents( ) for a way to copy document content and Range.extractContents( ) for a way to copy and delete document content in a single operation.
Node.normalize( ), Range.cloneContents( ), Range.extractContents( )
Range.detach( ) | free a Range object |
void detach( ) throws DOMException;
Like all Range methods, detach( ) throws a DOMException with a code of INVALID_STATE_ERR if it is called on a Range object that has already been detached.
DOM implementations keep track of all Range objects created for a document, because they may need to change the range boundary points when the document is modified. When you are certain that a Range object isn't needed any more, call the detach( ) method to tell the implementation that it no longer needs to keep track of that range. Note that once this method has been called for a Range object, any use of that Range will throw an exception. Calling detach( ) is not required but may improve performance in some circumstances when the document is being modified and a Range object is not subject to immediate garbage collection.
Range.extractContents( ) | delete document content and return it in a DocumentFragment |
DocumentFragment extractContents( ) throws DOMException;
A DocumentFragment node that contains the contents of this range.
This method throws a DOMException with a code of NO_MODIFICATION_ALLOWED_ERR if any part of the document content to be extracted is read-only, or a code of HIERARCHY_REQUEST_ERR if the range contains a DocumentType node.
This method deletes the specified range of a document and returns a DocumentFragment node that contains the deleted content (or a copy of the deleted content). When this method returns, the range is collapsed, and the document may contain adjacent Text nodes (which can be merged with Node.normalize( )).
DocumentFragment, Range.cloneContents( ), Range.deleteContents( )
Range.insertNode( ) | insert a node at the start of a range |
void insertNode(NodenewNode) throws RangeException, DOMException;
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:
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( ).
Range.selectNode( ) | set range boundaries to a node |
void selectNode(Node refNode) throws RangeException, DOMException;
A RangeException with a code of INVALID_NODE_TYPE_ERR if refNode is an Attr, Document, DocumentFragment, Entity, or Notation node, or if any ancestor of refNode is a DocumentType, Entity, or Notation node.
A DOMException with a code of WRONG_DOCUMENT_ERR if refNode is part of a different document than the one through which this range was created.
This method sets the contents of this range to the specified refNode. That is, it "selects" the node and its descendants.
Range.selectNodeContents( ) | set range boundaries to the children of a node |
void selectNodeContents(Node refNode) throws RangeException, DOMException;
A RangeException with a code of INVALID_NODE_TYPE_ERR if refNode or one of its ancestors is a DocumentType, Entity, or Notation node.
A DOMException with a code of WRONG_DOCUMENT_ERR if refNode is part of a different document than the one through which this range was created.
This method sets the boundary points of this range so that the range contains the children of refNode.
Range.setEnd( ) | set the end point of a range |
void setEnd(Node refNode, long offset) throws RangeException, DOMException;
A RangeException with a code of INVALID_NODE_TYPE_ERR if refNode or one of its ancestors is a DocumentType, Entity, or Notation node.
A DOMException with a code of WRONG_DOCUMENT_ERR if refNode is part of a different document than the one through which this range was created, or a code of INDEX_SIZE_ERR if offset is negative or is greater than the number of children or characters in refNode.
This method sets the end point of a range by specifying the values of the endContainer and endOffset properties.
Range.setEndAfter( ) | end a range after a specified node |
void setEndAfter(Node refNode) throws RangeException, DOMException;
A RangeException with a code of INVALID_NODE_TYPE_ERR if refNode is a Document, DocumentFragment, Attr, Entity, or Notation node, or if the root container of refNode is not a Document, DocumentFragment, or Attr node.
A DOMException with a code of WRONG_DOCUMENT_ERR if refNode is part of a different document than the one through which this range was created.
This method sets the end point of this range to fall immediately after the specified refNode.
Range.setEndBefore( ) | end a range before the specified node |
void setEndBefore(Node refNode) throws RangeException, DOMException;
This method throws the same exceptions in the same circumstances as Range.setEndAfter( ). See that method for details.
This method sets the end point of this range to fall immediately before the specified refNode.
Range.setStart( ) | set the start point of a range |
void setStart(Node refNode, long offset) throws RangeException, DOMException;
This method throws the same exceptions, for the same reasons, as Range.setEnd( ). See that method for details.
This method sets the start point of this range by specifying the values of the startContainer and startOffset properties.
Range.setStartAfter( ) | start a range after the specified node |
void setStartAfter(Node refNode) throws RangeException, DOMException;
This method throws the same exceptions in the same circumstances as Range.setEndAfter( ). See that method for details.
This method sets the starting point of this range to be immediately after the specified refNode.
Range.setStartBefore( ) | start a range before the specified node |
void setStartBefore(Node refNode) throws RangeException, DOMException;
This method throws the same exceptions in the same circumstances as Range.setEndAfter( ). See that method for details.
This method sets the starting point of this range to be immediately before the specified refNode.
Range.surroundContents( ) | surround range contents with the specified node |
void surroundContents(Node newParent) throws RangeException, DOMException;
This method throws a DOMException or RangeException with one of the following code values in the following circumstances:
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.
Range.toString( ) | get range contents as a plain-text string |
String toString( );
The contents of this range as a string of plain text without any markup.
RangeException | signals a range-specific exception |
The following constants define the legal values for the code property of a RangeException object. Note that these constants are static properties of RangeException, not properties of individual exception objects.
A RangeException is thrown by certain methods of the Range interface to signal a problem of some sort. Note that most exceptions thrown by Range methods are DOMException objects. A RangeException is generated only when none of the existing DOMException error constants is appropriate to describe the exception.
Rect | a CSS rect( ) value |
This interface represents a CSS rect(top right bottom left) value, as used with the CSS clip attribute, for example. Consult a CSS reference for details.
CSSPrimitiveValue.getRectValue( )
RGBColor | a CSS color value |
This interface represents a color specified in the RGB color space. The properties are CSSPrimitiveValue objects that specify the values of the red, green, and blue components of the color. Each CSSPrimitiveValue holds a number in the range 0-255 or a percentage in the range 0 -100%.
CSSPrimitiveValue.getRGBColorValue( )
StyleSheet | a style sheet of any type |
CSSStyleSheet
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.
CSSStyleSheet, Document.styleSheets, LinkStyle
LinkStyle.sheet, StyleSheet.parentStyleSheet
StyleSheetList.item( )
StyleSheetList | an array of style sheets |
This interface defines an array of StyleSheet objects. length specifies the number of style sheets in the array, and item( ) provides a way to retrieve the style sheet at a given position. In JavaScript, you can treat a StyleSheetList object as a read-only array, and you can index it using ordinary square-bracket array notation instead of calling the item( ) method.
DocumentStyle.styleSheets
StyleSheetList.item( ) | index an array of style sheets |
StyleSheet item(unsigned long index);
The StyleSheet object at the specified position within the array, or null if index is negative or is greater than or equal to length. Note that in JavaScript, it is usually simpler to treat a StyleSheetList object as an array and index it using square-bracket array notation instead of calling this method.
Text | a run of text in an HTML or XML document |
Node CharacterData Text
CDATASection
A Text node represents a run of plain text in an HTML or XML document. Plain text appears within HTML and XML elements and attributes, and Text nodes typically appear as children of Element and Attr nodes. Text nodes inherit from CharacterData, and the textual content of a Text node is available through the data property inherited from CharacterData or through the nodeValue property inherited from Node. Text nodes may be manipulated using any of the methods inherited from CharacterData or with the splitText( ) method defined by the Text interface itself. Text nodes never have children.
See Node.normalize( ) for a way to remove empty Text nodes and merge adjacent Text nodes from a subtree of a document.
CharacterData, Node.normalize( )
Document.createTextNode( ), Text.splitText( )
Text.splitText( ) | split a Text node in two |
Text splitText(unsigned long offset) throws DOMException;
The Text node that was split from this node.
This method may throw a DOMException with one of the following code values:
This method splits a Text node in two at the specified offset. The original Text node is modified so that it contains all text content up to, but not including, the character at position offset. A new Text node is created to contain all the characters from (and including) the position offset to the end of the string. This new Text node is the return value of the method. Additionally, if the original Text node has a parentNode, the new node is inserted into this parent node immediately after the original node.
The CDATASection interface inherits from Text, and this splitText( ) method can also be used with CDATASection nodes, in which case the newly created node is a CDATASection rather than a Text node.
TreeWalker | traverse a filtered document subtree |
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.
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.)
// 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; }
NodeFilter, NodeIterator; Chapter 17
Document.createTreeWalker( )
TreeWalker.firstChild( ) | return the first child that is not filtered out |
Node firstChild( );
The first child of the current node that is not filtered out, or null if there is no such child.
This method sets currentNode to the first child of the current node that is not filtered out and returns that child. If there is no such child, it leaves currentNode unchanged and returns null.
TreeWalker.lastChild( ) | return the last child that is not filtered out |
Node lastChild( );
The last child of the current node that is not filtered out, or null if there is no such child.
This method sets currentNode to the last child of the current node that is not filtered out and returns that child. If there is no such child, it leaves currentNode unchanged and returns null.
TreeWalker.nextNode( ) | return the next node that is not filtered out |
Node nextNode( );
The node that follows the current node in the document source and is not filtered out, or null if there is none.
This method sets currentNode to the next node (in document source order) that is not filtered out and returns that node. If there is no such node, or if the search for the next node takes the TreeWalker outside of the root subtree, currentNode remains unchanged and the method returns null.
Note that this method "flattens" the document tree structure and returns nodes in the order in which they appear in the document source. Calling nextNode( ) may cause the current node to move down, sideways, or up the document tree. This type of flattening traversal can also be performed with NodeIterator.nextNode( ).
TreeWalker.nextSibling( ) | return the next sibling that is not filtered out |
Node nextSibling( );
The next sibling of the current node that is not filtered out, or null if there is no such sibling.
This method sets currentNode to the next sibling of the current node that is not filtered out and returns that sibling. If there is no such sibling, it leaves currentNode unchanged and returns null.
TreeWalker.parentNode( ) | return the nearest ancestor that is not filtered out |
Node parentNode( );
The nearest ancestor of the current node that is not filtered out, or null if there is no such ancestor.
This method sets currentNode to the nearest ancestor of the current node that is not filtered out and returns that ancestor. If there is no such ancestor, it leaves currentNode unchanged and returns null.
TreeWalker.previousNode( ) | return the previous node that is not filtered out |
Node previousNode( );
The nearest node that precedes the current node in the document source and is not filtered out, or null if there is none.
This method sets currentNode to the previous node (in document source order) that is not filtered out and returns that node. If there is no such node, or if the search for the previous node takes the TreeWalker outside of the root subtree, currentNode remains unchanged and the method returns null.
Note that this method "flattens" the document tree structure and returns nodes in the order in which they appear in the document source. Calling previousNode( ) may cause the current node to move down, sideways, or up the document tree. This type of flattening traversal can also be performed with NodeIterator.previousNode( ).
TreeWalker.previousSibling( ) | return the previous sibling that is not filtered out |
Node previousSibling( );
The previous sibling of the current node that is not filtered out, or null if there is no such sibling.
This method sets currentNode to the closest previous sibling of the current node that is not filtered out and returns that sibling. If there is no such sibling, it leaves currentNode unchanged and returns null.
UIEvent | details about user interface events |
Event UIEvent
MouseEvent
The UIEvent interface is a subinterface of Event and defines the type of Event object passed to events of type DOMFocusIn, DOMFocusOut, and DOMActivate. These event types are not commonly used in web browsers, and what is more important about the UIEvent interface is that it is the parent interface of MouseEvent.
UIEvent.initUIEvent( ) | initialize the properties of a UIEvent object |
void initUIEvent(String typeArg, boolean canBubbleArg, boolean cancelableArg, AbstractView viewArg, long detailArg);
This method initializes the view and detail properties of this UIEvent and also the type, bubbles, and cancelable properties inherited from the Event interface. This method may be called only on newly created UIEvent objects, before they have been passed to EventTarget.dispatchEvent( ).
ViewCSS | see AbstractView |
Copyright © 2003 O'Reilly & Associates. All rights reserved.