Chapter 25. W3C DOM ReferenceThis 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.
AvailabilityAvailability Inherits from/OverridesInherits from Title and Short DescriptionEvery 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. AvailabilityThe information in the "Availability" section tells you what level and what module of the DOM standard defines the interface or method. Since properties do not have their own reference pages, they do not have availability information. If the availability of a property is different from the availability of the interface that defines it, this fact is noted in the description of the property. Inherits fromDOM 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. SubinterfacesThis section contains the opposite of the "Inherits from" information: it lists any interfaces that inherit from this one. For example, the "Subinterfaces" section of the reference page for the Element interface specifies that HTMLElement is a subinterface of Element and inherits Element's methods and properties. Also ImplementsThe 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. ConstantsSome 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. PropertiesIf 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:
MethodsIf 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. SynopsisIf 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):
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. ArgumentsIf 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:
ReturnsThe "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. ThrowsThis section explains the kinds of exceptions the method can throw and under what circumstances it throws them. DOM TypesDOM 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:
DescriptionMost 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. ExampleReference pages for some commonly used interfaces and methods include an example in this section to illustrate typical usage of the interface or method. Most pages do not contain examples, however -- you'll find those in first half of this book. See AlsoMost 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.
AvailabilityAlso Implements
Properties
Methods
DescriptionIn the DOM, a view is an object that displays a document in some way. The Window object of client-side JavaScript is such a view. This AbstractView interface is a very preliminary step toward standardizing some of the properties and methods of the Window object. It simply specifies that all View objects have a property named document that refers to the document they display. In addition, if an implementation supports CSS style sheets, all View objects also implement the ViewCSS interface and define a getComputedStyle( ) method for determining how an element is actually rendered in the view. The document property gives every view a reference to the document it displays. The reverse is true also: every document has a reference to the view that displays it. If a DOM implementation supports the View module, the object that implements the Document interface also implements the DocumentView interface. This DocumentView interface defines a defaultView property that refers to the window in which the document is displayed. This interface has the word "Abstract" in its name to emphasize the fact that it is merely the beginning of a standardized window interface. In order to be useful, future levels of the DOM standard will have to introduce a new interface that extends AbstractView and adds other properties or methods. See AlsoType ofDocument.defaultView
AvailabilitySynopsisCSSStyleDeclaration getComputedStyle(Element elt, String pseudoElt); Arguments
ReturnsA 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. DescriptionAn element in a document may obtain style information from an inline style attribute and from any number of style sheets in the style-sheet "cascade." Before the element can actually be displayed in a view, its style must be "computed" by extracting style information from the appropriate parts of the cascade. This method allows access to those computed styles. By contrast, the style property of an element gives you access only to the inline styles of an element and tells you nothing about style-sheet attributes that apply to the element. Note that this method also provides a way to determine the actual pixel coordinates at which an element is rendered in this view. getComputedStyle( ) is actually defined by the ViewCSS interface. In any DOM implementation that supports the View and CSS modules, any object that implements AbstractView always implements ViewCSS also. So, for simplicity, this method has been listed with AbstractView. In Internet Explorer, similar functionality is available through the nonstandard currentStyle property of each HTMLElement object. See Also
AvailabilityInherits from/OverridesNode Attr Properties
DescriptionAn Attr object represents an attribute of an Element node. Attr objects are associated with Element nodes but are not directly part of the document tree (and have a null parentNode property). You can obtain an Attr object through the attributes property of the Node interface or by calling the getAttributeNode( ) method of the Element interface. Attr objects are nodes, and the value of an Attr is represented by the child nodes of the Attr node. In HTML documents, this is simply a single Text node. In XML documents, however, Attr nodes may have both Text and EntityReference children. The value property provides a shortcut for reading and writing the value of an attribute as a String. In most cases, the easiest way to work with element attributes is with the getAttribute( ) and setAttribute( ) methods of the Element interface. These methods use strings for attribute names and values and avoid the use of Attr nodes altogether. See AlsoPassed toElement.removeAttributeNode( ), Element.setAttributeNode( ), Element.setAttributeNodeNS( ) Returned byDocument.createAttribute( ), Document.createAttributeNS( ), Element.getAttributeNode( ), Element.getAttributeNodeNS( ), Element.removeAttributeNode( ), Element.setAttributeNode( ), Element.setAttributeNodeNS( )
AvailabilityInherits from/OverridesNode CharacterData Text CDATASection DescriptionThis 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. See AlsoReturned byDocument.createCDATASection( )
AvailabilityInherits from/OverridesNode CharacterData SubinterfacesComment, Text Properties
Methods
DescriptionCharacterData 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. See Also
AvailabilitySynopsisvoid appendData(String arg) throws DOMException; Arguments
ThrowsThis method throws a DOMException with a code of NO_MODIFICATION_ALLOWED_ERR if called on a node that is read-only. DescriptionThis method appends the string arg to the end of the data property for this node.
AvailabilitySynopsisvoid deleteData(unsigned long offset, unsigned long count) throws DOMException; Arguments
ThrowsThis method may throw a DOMException with one of the following code values:
DescriptionThis 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.
AvailabilitySynopsisvoid insertData(unsigned long offset, String arg) throws DOMException; Arguments
ThrowsThis method may throw a DOMException with one of the following code values in the following circumstances:
DescriptionThis method inserts the specified string arg into the text of a Text or Comment node at the specified position offset.
AvailabilitySynopsisvoid replaceData(unsigned long offset, unsigned long count, String arg) throws DOMException; Arguments
ThrowsThis method may throw a DOMException with one of the following code values in the following circumstances:
DescriptionThis 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.
AvailabilitySynopsisString substringData(unsigned long offset, unsigned long count) throws DOMException; Arguments
ReturnsA string that consists of count characters of the Text or Comment node starting with the character at position offset. ThrowsThis method may throw a DOMException with one of the following code values:
DescriptionThis 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.
AvailabilityInherits from/OverridesNode CharacterData Comment DescriptionA 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. See AlsoReturned byDocument.createComment( )
AvailabilityProperties
DescriptionThis interface represents a CSS counter( ) or counters( ) value. Consult a CSS reference for more information. See AlsoReturned byCSSPrimitiveValue.getCounterValue( )
AvailabilityPropertiesThis 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( ).
DescriptionThis interface defines one property for each CSS attribute defined by the CSS2 specification. If the DOM implementation supports this interface (which is part of the "CSS2" feature), all CSSStyleDeclaration objects also implement CSS2Properties. Reading one of the properties defined by this interface is equivalent to calling getPropertyValue( ) for the corresponding CSS attribute, and setting the value of one of these properties is equivalent to calling setProperty( ) for the corresponding attribute. The properties defined by CSS2Properties include properties that correspond to CSS shortcut attributes, and CSS2Properties handles these shortcut properties correctly. See Also
AvailabilityInherits from/OverridesCSSRule CSSCharsetRule Properties
DescriptionThis interface represents an @charset rule in a CSS style sheet. Consult a CSS reference for details.
AvailabilityInherits from/OverridesCSSRule CSSFontFaceRule PropertiesDescriptionThis interface represents an @font-face rule in a CSS style sheet. Consult a CSS reference for details.
AvailabilityInherits from/OverridesCSSRule CSSImportRule Properties
DescriptionThis interface represents an @import rule in a CSS style sheet. The styleSheet property represents the imported style sheet.
AvailabilityInherits from/OverridesCSSRule CSSMediaRule Properties
Methods
DescriptionThis 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.
AvailabilitySynopsisvoid deleteRule(unsigned long index) throws DOMException; Arguments
ThrowsThis method throws a DOMException with one of the following code values in the following circumstances:
DescriptionThis method deletes the rule at the specified position in the cssRules array.
AvailabilitySynopsisunsigned long insertRule(String rule, unsigned long index) throws DOMException; Arguments
ReturnsThe value of the index argument. ThrowsThis method throws a DOMException with one of the following code values in the following circumstances:
DescriptionThis method inserts the specified rule into the cssRules array at the specified index.
AvailabilityInherits from/OverridesCSSRule CSSPageRule Properties
DescriptionThis 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.
AvailabilityInherits from/OverridesCSSValue CSSPrimitiveValue ConstantsThe 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.
Properties
Methods
DescriptionThis subinterface of CSSValue represents a single CSS value. Contrast it with the CSSValueList interface, which represents a list of CSS values. The word "primitive" in the name of this interface is misleading; this interface can represent some complex types of CSS values, such as counters, rectangles, and colors. The primitiveType property holds one of the previously defined constants and specifies the type of the value. The various methods defined by this interface allow you to query values of various types and also to set numeric and string values. See AlsoCounter, CSSValue, CSSValueList, Rect, RGBColor Type ofRGBColor.blue, RGBColor.green, RGBColor.red, Rect.bottom, Rect.left, Rect.right, Rect.top
AvailabilitySynopsisCounter getCounterValue( ) throws DOMException; ReturnsThe Counter object that represents the value of this CSSPrimitiveValue. ThrowsThis method throws a DOMException with a code of INVALID_ACCESS_ERR if the primitiveType property is not CSS_COUNTER. DescriptionThis 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.
AvailabilitySynopsisfloat getFloatValue(unsigned short unitType) throws DOMException; Arguments
ReturnsThe floating-point numeric value of this CSSPrimitiveValue, expressed in the specified units. ThrowsThis 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.) DescriptionFor 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.
AvailabilitySynopsisRect getRectValue( ) throws DOMException; ReturnsThe Rect object that represents the value of this CSSPrimitiveValue. ThrowsThis method throws a DOMException with a code of INVALID_ACCESS_ERR if the primitiveType property is not CSS_RECT. DescriptionThis 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.
AvailabilitySynopsisRGBColor getRGBColorValue( ) throws DOMException; ReturnsThe RGBColor object that represents the value of this CSSPrimitiveValue. ThrowsThis method throws a DOMException with a code of INVALID_ACCESS_ERR if the primitiveType property is not CSS_RGBCOLOR. DescriptionThis 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.
AvailabilitySynopsisString getStringValue( ) throws DOMException; ReturnsThe string value of this CSSPrimitiveValue. ThrowsThis 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.
AvailabilitySynopsisvoid setFloatValue(unsigned short unitType, float floatValue) throws DOMException; Arguments
ThrowsThis 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. DescriptionThis method specifies the unit type and numeric value for this CSSPrimitiveValue.
AvailabilitySynopsisvoid setStringValue(unsigned short stringType, String stringValue) throws DOMException; Arguments
ThrowsThis 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. DescriptionThis method sets the string value and string type for this CSSPrimitiveValue.
AvailabilitySubinterfacesCSSCharsetRule, CSSFontFaceRule, CSSImportRule, CSSMediaRule, CSSPageRule, CSSStyleRule, CSSUnknownRule ConstantsThese constants represent the various types of rules that may appear in a CSS style sheet. They are the legal values of the type property, and they specify which of the above subinterfaces this object implements. unsigned short UNKNOWN_RULE = 0; // CSSUnknownRule unsigned short STYLE_RULE = 1; // CSSStyleRule unsigned short CHARSET_RULE = 2; // CSSCharsetRule unsigned short IMPORT_RULE = 3; // CSSImportRule unsigned short MEDIA_RULE = 4; // CSSMediaRule unsigned short FONT_FACE_RULE = 5; // CSSFontFaceRule unsigned short PAGE_RULE = 6; // CSSPageRule Properties
DescriptionThis interface defines properties that are common to all types of rules in CSS style sheets. No object directly implements this interface; instead, they implement one of the more specific subinterfaces listed earlier. The most important subinterface is probably CSSStyleRule, which describes a CSS rule that defines a document style. See AlsoType ofCSSRule.parentRule, CSSStyleDeclaration.parentRule, CSSStyleSheet.ownerRule Returned byCSSRuleList.item( )
AvailabilityPropertiesMethods
DescriptionThis 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.) See AlsoType ofCSSMediaRule.cssRules, CSSStyleSheet.cssRules
AvailabilitySynopsisCSSRule item(unsigned long index); Arguments
ReturnsThe CSSRule object at the specified position, or null if index is not a valid position.
AvailabilityAlso ImplementsIf the implementation supports the "CSS2" feature in addition to the "CSS" feature (as most web browsers do), all objects that implement this interface also implement the CSS2Properties interface. CSS2Properties provides commonly used shortcut properties for setting and querying the values of CSS attributes. See CSS2Properties for details. Properties
Methods
DescriptionThis attribute represents a CSS style declaration block: a set of CSS attributes and their values, separated from each other by semicolons. The style declaration block is the portion of a style rule within curly braces in a CSS style sheet. The value of the HTML style attribute also constitutes a style declaration block. The item( ) method and the length property allow you to loop through the names of all CSS attributes specified in this declaration block. In JavaScript, you can also simply treat the CSSStyleDeclaration object as an array and index it using square-bracket notation instead of calling the item( ) method explicitly. Once you have the names of the CSS attributes specified in this declaration, you can use other methods of this interface to query the values of those attributes. getPropertyValue( ) returns the value as a string, and getPropertyCSSValue( ) returns the attribute value as a CSSValue object. (Note that the DOM API refers to CSS style attributes as "properties." I use the term "attributes" here to avoid confusing them with JavaScript object properties.) In most web browsers, every object that implements CSSStyleDeclaration also implements the CSS2Properties interface, which defines an object property for each CSS attribute defined by the CSS2 specification. You can read and write the values of these convenience properties instead of calling getPropertyValue( ) and setProperty( ). See AlsoType ofCSSFontFaceRule.style, CSSPageRule.style, CSSStyleRule.style, HTMLElement.style Returned byDocument.getOverrideStyle( ), AbstractView.getComputedStyle( )
AvailabilitySynopsisCSSValue getPropertyCSSValue(String propertyName); Arguments
ReturnsA 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.
AvailabilitySynopsisString getPropertyPriority(String propertyName); Arguments
ReturnsThe 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.
AvailabilitySynopsisString getPropertyValue(String propertyName); Arguments
ReturnsThe string value of the named CSS attribute, or the empty string if that attribute is not explicitly set in this declaration block. DescriptionThis 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.
AvailabilitySynopsisString item(unsigned long index); Arguments
ReturnsThe name of the CSS attribute at index, or the empty string if index is negative or greater than or equal to the length property. DescriptionThe 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.
AvailabilitySynopsisString removeProperty(String propertyName) throws DOMException; Arguments
ReturnsThe 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. ThrowsIf this style declaration is read-only, this method throws a DOMException with a code of NO_MODIFICATION_ALLOWED_ERR. DescriptionThis method deletes a named attribute from this style declaration block and returns the value of the attribute.
AvailabilitySynopsisvoid setProperty(String propertyName, String value, String priority) throws DOMException; Arguments
ThrowsThis 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. DescriptionThis 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.
AvailabilityInherits from/OverridesCSSRule CSSStyleRule Properties
DescriptionThis 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. See Also
AvailabilityInherits from/OverridesCSS StyleSheet CSSStyleSheet Properties
Methods
DescriptionThis 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. See AlsoType ofCSSImportRule.styleSheet, CSSRule.parentStyleSheet Returned byDOMImplementation.createCSSStyleSheet( )
AvailabilitySynopsisvoid deleteRule(unsigned long index) throws DOMException; Arguments
ThrowsThis 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. DescriptionThis method deletes the rule at the specified index from the cssRules array.
AvailabilitySynopsisunsigned long insertRule(String rule, unsigned long index) throws DOMException; Arguments
ReturnsThe value of the index argument. ThrowsThis method throws a DOMException with one of the following code values in the following circumstances:
DescriptionThis method inserts (or appends) a new CSS rule at the specified index of the cssRules array of this style sheet.
AvailabilityInherits from/OverridesCSS CSSRule CSSUnknownRule DescriptionThis 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.
AvailabilitySubinterfacesCSSPrimitiveValue, CSSValueList ConstantsThe following constants specify the valid values for the cssValueType property:
Properties
DescriptionThis interface represents the value of a CSS attribute. The cssText property gives the value in textual form. If the cssValueType property is CSSValue.CSS_PRIMITIVE_VALUE, this CSSValue object also implements the more specific CSSPrimitiveValue interface. If cssValueType is CSSValue.CSS_VALUE_LIST, this CSSValue represents a list of values and also implements the CSSValueList interface. See AlsoCSSPrimitiveValue, CSSValueList Returned byCSSStyleDeclaration.getPropertyCSSValue( ), CSSValueList.item( )
AvailabilityInherits from/OverridesCSSValue CSSValueList PropertiesMethods
DescriptionThis 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.
AvailabilitySynopsisCSSValue item(unsigned long index); Arguments
ReturnsThe CSSValue object at the specified position in this CSSValueList, or null if index is negative or is greater than or equal to length.
AvailabilityInherits from/OverridesNode Document SubinterfacesHTMLDocument Also Implements
Because these interfaces define commonly implemented additions to the Document interface, their properties and methods are listed and documented here, as if they were directly part of the Document interface. Properties
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. Methods
DescriptionThe Document interface is the root node of a document tree. A Document node may have multiple children, but only one of those children may be an Element node: it is the root element of the document. The root element is most easily accessed through the documentElement property. The doctype and implementation properties provide access to the DocumentType object (if any) and the DOMImplementation object for this document. Most of the methods defined by the Document interface are "factory methods" that are used to create various types of nodes that can be inserted into this document. The notable exceptions are getElementById( ) and getElementsByTagName( ), which are quite useful for finding a specific Element or a set of related Element nodes within the document tree. Contrast this Document object to the Document object documented in the client-side reference section of this book. The Level 0 properties and methods of that client-side Document object are formally defined by the DOM standard in the HTMLDocument interface. See HTMLDocument in this reference section for the DOM equivalent of the traditional client-side JavaScript Document object. The Document interface is defined by the Core module of the DOM Level 2 specification. A number of the other modules define "add-on" interfaces that are intended to be implemented by the same object that implements the Document interface. For example, if an implementation supports the CSS module, the object that implements this interface also implements the DocumentCSS interface. In JavaScript, the properties and methods of these add-on interfaces can be used as if they were defined by Document, and for that reason, those methods and properties are listed here. See the earlier Section section for a full list of the add-on interfaces for Document. See AlsoType ofAbstractView.document, HTMLFrameElement.contentDocument, HTMLIFrameElement.contentDocument, HTMLObjectElement.contentDocument, Node.ownerDocument Returned byDOMImplementation.createDocument( )
AvailabilitySynopsisAttr createAttribute(String name) throws DOMException; Arguments
ReturnsA newly created Attr node with its nodeName property set to name. ThrowsThis method throws a DOMException with a code of INVALID_CHARACTER_ERR if name contains an illegal character. See Also
AvailabilitySynopsisAttr createAttributeNS(String namespaceURI, String qualifiedName) throws DOMException; Arguments
ReturnsA newly created Attr node with the specified name and namespace. ThrowsThis method may throw a DOMException with one of the following code values in the following circumstances:
DescriptioncreateAttributeNS( ) 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.
AvailabilitySynopsisCDATASection createCDATASection(Stringdata) throws DOMException; Arguments
ReturnsA newly created CDATASection node, with the specified data as its contents. ThrowsIf 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.
AvailabilitySynopsisComment createComment(String data); Arguments
ReturnsA newly created Comment node, with the specified data as its text.
AvailabilitySynopsisDocumentFragment createDocumentFragment( ); ReturnsA newly created DocumentFragment node with no children.
AvailabilitySynopsisElement createElement(String tagName) throws DOMException; Arguments
ReturnsA newly created Element node with the specified tag name. ThrowsThis method throws a DOMException with a code of INVALID_CHARACTER_ERR if tagName contains an illegal character.
AvailabilitySynopsisElement createElementNS(String namespaceURI, String qualifiedName) throws DOMException; Arguments
ReturnsA newly created Element node, with the specified tag name and namespace. ThrowsThis method may throw a DOMException with one of the following code values in the following circumstances:
DescriptioncreateElementNS( ) 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.
AvailabilitySynopsisEntityReference createEntityReference(String name) throws DOMException; Arguments
ReturnsA new EntityReference node that references an entity with the specified name. ThrowsThis method may throw a DOMException with one of the following code values:
DescriptionThis 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.
AvailabilitySynopsisEvent createEvent(String eventType) throws DOMException; Arguments
ReturnsA newly created Event object of the specified type. ThrowsThis method throws a DOMException with a code of NOT_SUPPORTED_ERR if the implementation does not support events of the requested type. DescriptionThis 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.
After creating an Event object with this method, you must initialize the object with the initialization method shown in the table. See the appropriate Event interface reference page for details about the initialization method. This method is actually defined not by the Document interface but by the DocumentEvent interface. If an implementation supports the Events module, the Document object always implements the DocumentEvent interface and supports this method. See Also
AvailabilitySynopsisNodeIterator createNodeIterator(Node root, unsigned long whatToShow, NodeFilter filter, boolean entityReferenceExpansion) throws DOMException; Arguments
ReturnsA newly created NodeIterator object. ThrowsThis method throws a DOMException with a code of NOT_SUPPORTED_ERR if the root argument is null. DescriptionThis 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. See Also
AvailabilitySynopsisProcessingInstruction createProcessingInstruction(String target, String data) throws DOMException; Arguments
ReturnsA newly created ProcessingInstruction node. ThrowsThis method may throw a DOMException with one of the following code values in the following circumstances:
AvailabilitySynopsisRange createRange( ); ReturnsA newly created Range object with both boundary points set to the beginning of the document. DescriptionThis 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.
AvailabilitySynopsisText createTextNode(String data); Arguments
ReturnsA newly created Text node that represents the specified data string.
AvailabilitySynopsisTreeWalker createTreeWalker(Node root, unsigned long whatToShow, NodeFilter filter, boolean entityReferenceExpansion) throws DOMException; Arguments
ReturnsA newly created TreeWalker object. ThrowsThis method throws a DOMException with a code of NOT_SUPPORTED_ERR if the root argument is null. DescriptionThis 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. See Also
AvailabilityDOM Level 2 Core; in DOM Level 1, defined by HTMLDocument SynopsisElement getElementById(String elementId); Arguments
ReturnsThe Element node that represents the document element with the specified id attribute, or null if no such element is found. DescriptionThis method searches the document for an Element node with an id attribute whose value is elementId, and returns that Element. If no such Element is found, it returns null. The value of the id attribute is intended to be unique within a document, and if this method finds more than one Element with the specified elementId, it may return one at random or it may return null. In HTML documents, this method always searches for attributes named id. In XML documents, however, it searches for any attribute whose type is id, regardless of what the attribute name is. If XML attribute types are not known (because, for example, the XML parser could not locate the document's DTD), this method always returns null. This is an important and commonly used method since it provides a simple way to obtain the Element object that represents a specific document element. Note that it provides functionality similar to the nonstandard document.all[] array defined by Internet Explorer 4 and later. Finally, note that the name of this method ends with "Id", not with "ID"; be careful not to misspell it. See AlsoDocument.getElementsByTagName( ), Element.getElementsByTagName( ), HTMLDocument.getElementsByName( )
AvailabilitySynopsisNode[] getElementsByTagName(String tagname); Arguments
ReturnsA 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. DescriptionThis 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. ExampleYou can find and iterate through all <h1> tags in a document with code like the following: var headings = document.getElementsByTagName("h1"); for(var i = 0; i < headings.length; i++) { // Loop through the returned tags var h = headings[i]; // Now do something with the <h1> element in the h variable } See AlsoDocument.getElementById( ), Element.getElementsByTagName( ), HTMLDocument.getElementsByName( )
AvailabilitySynopsisNode[] getElementsByTagNameNS(String namespaceURI, String localName); Arguments
ReturnsA read-only array (technically, a NodeList) of all Element nodes in the document tree that have the specified namespace and local name. DescriptionThis 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.
AvailabilitySynopsisCSSStyleDeclaration getOverrideStyle(Element elt, String pseudoElt); Arguments
ReturnsA 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. DescriptionThis 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. See AlsoCSSStyleDeclaration, CSS2Properties, AbstractView.getComputedStyle( ), Reference
AvailabilitySynopsisNode importNode(Node importedNode, boolean deep) throws DOMException; Arguments
ReturnsA copy of importedNode (and possibly all of its descendants) with its ownerDocument set to this document. ThrowsThis 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. DescriptionThis 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. See Also
AvailabilityInherits from/OverridesNode DocumentFragment DescriptionThe 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. See AlsoReturned byDocument.createDocumentFragment( ), Range.cloneContents( ), Range.extractContents( )
AvailabilityInherits from/OverridesNode DocumentType Properties
DescriptionThis infrequently used interface represents the DTD of an XML document. Programmers working exclusively with HTML documents never need to use this interface. Because a DTD is not part of a document's content, DocumentType nodes never appear in the document tree. If an XML document has a DTD, the DocumentType node for that DTD is available through the doctype property of the Document node. DocumentType nodes are immutable and may not be modified in any way. See AlsoType ofDocument.doctype Passed toDOMImplementation.createDocument( ) Returned byDOMImplementation.createDocumentType( )
AvailabilityConstantsThe 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.
Properties
DescriptionA DOMException object is thrown when a DOM method or property is used incorrectly or in an inappropriate context. The value of the code property indicates the general type of exception that occurred. Note that a DOMException may be thrown when reading or writing a property of an object as well as when calling a method of an object. The descriptions of object properties and methods in this reference include a list of exception types they may throw. Note, however, that certain commonly thrown exceptions are omitted from these lists. A DOMException with a code of NO_MODIFICATION_ALLOWED_ERR is thrown any time an attempt is made to modify a read-only node, such as an Entity node or one of its descendants. Thus, most methods and read/write properties of the Node interface (and of its subinterfaces) may throw this exception. Because read-only nodes appear only in XML documents and not in HTML documents, and because it applies so universally to the methods and writable properties of Node objects, the NO_MODIFICATION_ALLOWED_ERR exception is omitted from the descriptions of those methods and properties. Similarly, many DOM methods and properties that return strings may throw a DOMException with a code of DOMSTRING_SIZE_ERR, which indicates that the text to be returned is too long to be represented as a string value in the underlying JavaScript implementation. Although this type of exception may theoretically be thrown by many properties and methods, it is very rare in practice and is omitted from the descriptions of those methods and properties. Note that not all exceptions in the DOM are signaled with a DOMException. Exceptions having to do with events and event handling cause an EventException object to be thrown, and exceptions involving the DOM Range module cause a RangeException to be thrown. See Also
AvailabilityAlso Implements
Methods
DescriptionThe 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. See AlsoType ofDocument.implementation
AvailabilitySynopsisCSSStyleSheet createCSSStyleSheet(String title, String media) throws DOMException; Arguments
ReturnsA CSSStyleSheet object. ThrowsA DOMException with a code of SYNTAX_ERR if the media argument is malformed. DescriptionThis 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.
AvailabilitySynopsisDocument createDocument(String namespaceURI, String qualifiedName, DocumentType doctype) throws DOMException; Arguments
ReturnsA Document object with its documentElement property set to a root Element node of the specified type. ThrowsThis method may throw a DOMException with the following code values in the following circumstances:
DescriptionThis method creates a new Document object and the specified root documentElement object for that document. If the doctype argument is non-null, the ownerDocument property of this DocumentType object is set to the newly created document. This method is used to create XML documents and may not be supported by HTML-only implementations. Use createHTMLDocument( ) to create a new HTML document. See AlsoDOMImplementation.createDocumentType( ), DOMImplementation.createHTMLDocument( )
AvailabilitySynopsisDocumentType createDocumentType(String qualifiedName, String publicId, String systemId) throws DOMException; Arguments
ReturnsA new DocumentType object with an ownerDocument property of null. ThrowsThis method may throw a DOMException with one of the following code values:
DescriptionThis 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.
AvailabilitySynopsisHTMLDocument createHTMLDocument(String title); Arguments
ReturnsThe new HTMLDocument object. DescriptionThis 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. See Also
AvailabilitySynopsisboolean hasFeature(String feature, String version); Arguments
Returnstrue 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. DescriptionThe 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.
ExampleYou might use this method in code like the following: // Check whether the browser supports the DOM Level 2 Traversal API if (document.implementation && document.implementation.hasFeature && document.implementation.hasFeature("Traversal", "2.0")) { // If so, use it here... } else { // If not, traverse the document some other way } See Also
AvailabilityInherits from/OverridesNode Element SubinterfacesHTMLElement Properties
Methods
DescriptionThe Element interface represents HTML or XML elements or tags. The tagName property specifies the name of the element. The getElementsByTagName( ) method provides a powerful way to locate element descendants of a given element that have a specified tag name. The various other methods of this interface provide access to the attributes of the element. If you give an element a unique identifier using the id attribute in your document source, you can then easily locate the Element node that represents that document element with the useful Document.getElementById( ) method. To create a new Element node for insertion into a document, use Document.createElement( ). In HTML documents (and many XML documents) all attributes have simple string values, and you can use the simple methods getAttribute( ) and setAttribute( ) for any attribute manipulation you need to do. If you are working with XML documents that may contain entity references as part of attribute values, you will have to work with Attr objects and their subtree of nodes. You can get and set the Attr object for an attribute with getAttributeNode( ) and setAttributeNode( ), or you can iterate through the Attr nodes in the attributes[] array of the Node interface. If you are working with an XML document that uses XML namespaces, you'll need to use the various methods whose names end with "NS". In the DOM Level 1 specification, the normalize( ) method was part of the Element interface. In the Level 2 specification, normalize( ) is instead part of the Node interface. All Element nodes inherit this method and can still use it. See AlsoType ofAttr.ownerElement, Document.documentElement Passed toDocument.getOverrideStyle( ), AbstractView.getComputedStyle( ) Returned byDocument.createElement( ), Document.createElementNS( ), Document.getElementById( )
AvailabilitySynopsisString getAttribute(String name); Arguments
ReturnsThe 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 (""). DescriptiongetAttribute( ) 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( ). ExampleThe following code illustrates two different ways of obtaining an attribute value for an HTML <img> element: // Get all images in the document var images = document.body.getElementsByTagName("IMG"); // Get the SRC attribute of the first one var src0 = images[0].getAttribute("SRC"); // Get the SRC attribute of the second simply by reading the property var src1 = images[1].src; See Also
AvailabilitySynopsisAttr getAttributeNode(String name); Arguments
ReturnsAn Attr node whose descendants represent the value of the named attribute, or null if this element has no such attribute. DescriptiongetAttributeNode( ) 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. See AlsoElement.getAttribute( ), Element.getAttributeNodeNS( ), Reference
AvailabilitySynopsisAttr getAttributeNodeNS(String namespaceURI, String localName); Arguments
ReturnsThe Attr node whose descendants represent the value of the specified attribute, or null if this element has no such attribute. DescriptionThis method works like getAttributeNode( ), except that the attribute is specified by the combination of a namespace URI and a local name defined within that namespace. This method is useful only with XML documents that use namespaces. See Also
AvailabilitySynopsisString getAttributeNS(String namespaceURI, String localName); Arguments
ReturnsThe 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. DescriptionThis method works just like the getAttribute( ) method, except that the attribute is specified by a combination of namespace URI and local name within that namespace. This method is useful only with XML documents that use namespaces. See Also
AvailabilitySynopsisNode[] getElementsByTagName(String name); Arguments
ReturnsAn array (technically, a NodeList) of Element objects that are descendants of this element and have the specified tag name. DescriptionThis 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. ExampleYou 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"); See AlsoDocument.getElementById( ), Document.getElementsByTagName( ), HTMLDocument.getElementsByName( )
AvailabilitySynopsisNode[] getElementsByTagNameNS(String namespaceURI, String localName); Arguments
ReturnsAn array (technically, a NodeList) of Element objects that are descendants of this element and have the specified name and namespace. DescriptionThis method works like getElementsByTagName( ), except that the tag name of the desired elements is specified as a combination of a namespace URI and a local name defined within that namespace. This method is useful only with XML documents that use namespaces. See AlsoDocument.getElementsByTagNameNS( ), Element.getElementsByTagName( )
AvailabilitySynopsisboolean hasAttribute(String name); Arguments
Returnstrue if this element has a specified or default value for the named attribute, and false otherwise. DescriptionThis 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. See AlsoReference , Element.getAttribute( ), Element.setAttribute( )
AvailabilitySynopsisboolean hasAttributeNS(String namespaceURI, String localName); Arguments
Returnstrue if this element has an explicitly specified value or a default value for the specified attribute; false otherwise. DescriptionThis method works like hasAttribute( ), except that the attribute to be checked for is specified by namespace and name. This method is useful only with XML documents that use namespaces. See Also
AvailabilitySynopsisvoid removeAttribute(String name); Arguments
ThrowsThis 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. DescriptionremoveAttribute( ) 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. See Also
AvailabilitySynopsisAttr removeAttributeNode(Attr oldAttr) throws DOMException; Arguments
ReturnsThe Attr node that was removed. ThrowsThis method may throw a DOMException with the following code values:
DescriptionThis method removes (and returns) an Attr node from the set of attributes of an element. If the removed attribute has a default value specified by the DTD, a new Attr is added representing this default value. If is often simpler to use removeAttribute( ) instead of this method. See Also
AvailabilitySynopsisvoid removeAttributeNS(String namespaceURI, String localName); Arguments
ThrowsThis 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. DescriptionremoveAttributeNS( ) works just like removeAttribute( ), except that the attribute to be removed is specified by name and namespace instead of simply by name. This method is useful only with XML documents that use namespaces. See AlsoElement.getAttributeNS( ), Element.removeAttribute( ), Element.setAttributeNS( )
AvailabilitySynopsisvoid setAttribute(String name, String value) throws DOMException; Arguments
ThrowsThis method may throw a DOMException with the following code values:
DescriptionThis method sets the specified attribute to the specified value. If no attribute by that name already exists, a new one is created. Note that Element objects that represent the tags of an HTML document also implement the HTMLElement interface and (usually) one of its tag-specific subinterfaces. As a shortcut, these interfaces define properties that correspond to the standard HTML attributes for each tag, and it is usually easier to set an HTML attribute simply by setting the appropriate property. The value argument is a plain string. If you are working with an XML document and need to include an entity reference in an attribute value, use setAttributeNode( ). Example// Set the TARGET attribute of all links in a document var links = document.body.getElementsByTagName("A"); for(var i = 0; i < links.length; i++) { links[i].setAttribute("TARGET", "newwindow"); } See AlsoElement.getAttribute( ), Element.removeAttribute( ), Element.setAttributeNode( )
AvailabilitySynopsisAttr setAttributeNode(Attr newAttr) throws DOMException; Arguments
ReturnsThe Attr node that was replaced by newAttr, or null if no attribute was replaced. ThrowsThis method may throw a DOMException with a code of the following values:
DescriptionThis 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. See Also
AvailabilitySynopsisAttr setAttributeNodeNS(Attr newAttr) throws DOMException; Arguments
ReturnsThe Attr node that was replaced by newAttr, or null if no attribute was replaced. ThrowsThis 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. DescriptionThis method works just like setAttributeNode( ), except that it is designed for use with Attr nodes that represent attributes specified by namespace and name. This method is useful only with XML documents that use namespaces. It may be unimplemented (i.e., throw a NOT_SUPPORTED_ERR) on browsers that do not support XML documents. See AlsoAttr, Element.setAttributeNS( ), Element.setAttributeNode( )
AvailabilitySynopsisvoid setAttributeNS(String namespaceURI, String qualifiedName, String value) throws DOMException; Arguments
ThrowsThis method may throw a DOMException with the following code values:
DescriptionThis method is like setAttribute( ), except that the attribute to be created or set is specified by a namespace URI and a qualified name that consists of a namespace prefix, a colon, and a local name within the namespace. In addition to letting you change the value of an attribute, this method allows you to change the namespace prefix of an attribute. This method is useful only with XML documents that use namespaces. It may be unimplemented (i.e., throw a NOT_SUPPORTED_ERR) on browsers that do not support XML documents. See Also
AvailabilityInherits from/OverridesNode Entity Properties
DescriptionThis infrequently used interface represents an entity in an XML document type definition (DTD). It is never used with HTML documents. The name of the entity is specified by the nodeName property inherited from the Node interface. The entity content is represented by the child nodes of the Entity node. Note that Entity nodes and their children are not part of the document tree (and the parentNode property of an Entity is always null). Instead, a document may contain one or more references to an entity; see EntityReference for more information. Entities are defined in the DTD of a document, either as part of an external DTD file or as part of an "internal subset" that defines local entities specific to the current document. The DocumentType interface has an entities property that allows Entity nodes to be looked up by name. This is the only way to obtain a reference to an Entity node; because they are part of the document type, Entity nodes never appear as part of the document itself. Entity nodes and all of their descendants are read-only and cannot be edited or modified in any way. See Also
AvailabilityInherits from/OverridesNode EntityReference DescriptionThis 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. See AlsoReturned byDocument.createEntityReference( )
AvailabilitySubinterfacesMutationEvent, UIEvent ConstantsThese constants are the legal values of the eventPhase property; they represent the current phase of event propagation for this event:
Properties
Methods
DescriptionThis interface represents an event that occurred on some node of the document and contains details about the event. Various subinterfaces of Event define additional properties that provide details pertinent to specific types of events. Many event types use a more specific subinterface of Event to describe the event that has occurred. However, the event types defined by the HTMLEvents module use the Event interface directly. These event types are: "abort", "blur", "change", "error", "focus", "load", "reset", "resize", "scroll", "select", "submit", and "unload". See AlsoEventListener, EventTarget, MouseEvent, UIEvent; Chapter 19 Passed toEventTarget.dispatchEvent( ) Returned byDocument.createEvent( )
AvailabilitySynopsisvoid initEvent(String eventTypeArg, boolean canBubbleArg, boolean cancelableArg); Arguments
DescriptionThis 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.
AvailabilitySynopsisvoid preventDefault( ); DescriptionThis 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.
AvailabilitySynopsisvoid stopPropagation( ); DescriptionThis 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.
AvailabilityConstantsThe 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.
Properties
DescriptionAn 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( )).
AvailabilityMethods
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. DescriptionThis interface defines the structure of an event listener or event handler. In languages such as Java, an event listener is an object that defines a method named handleEvent( ) that takes an Event object as its sole argument. In JavaScript, however, any function that expects a single Event argument, or a function that expects no argument, can serve as an event listener. Example// This function is an event listener for a "submit" event function submitHandler(e) { // Call a form-validation function defined elsewhere if (!validate(e.target)) e.preventDefault( ); // If validation fails, don't submit form } // We might register the event listener above like this document.forms[0].addEventListener("submit", submitHandler, false); See AlsoEvent, EventTarget; Chapter 19 Passed toEventTarget.addEventListener( ), EventTarget.removeEventListener( )
AvailabilityMethods
DescriptionIn 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. See AlsoEvent, EventListener; Chapter 19 Type ofEvent.currentTarget, Event.target, MouseEvent.relatedTarget Passed toMouseEvent.initMouseEvent( )
AvailabilitySynopsisvoid addEventListener(String type, EventListener listener, boolean useCapture); Arguments
DescriptionThis method adds the specified event listener function to the set of listeners registered on this node to handle events of the specified type. If useCapture is true, the listener is registered as a capturing event listener. If useCapture is false, it is registered as a normal event listener. addEventListener( ) may be called multiple times to register multiple event handlers for the same type of event on the same node. Note, however, that the DOM makes no guarantees about the order in which multiple event handlers will be invoked. If the same event listener function is registered twice on the same node with the same type and useCapture arguments, the second registration is simply ignored. If a new event listener is registered on this node while an event is being handled at this node, the new event listener is not invoked for that event. When a Document node is duplicated with Node.cloneNode( ) or Document.importNode( ), the event listeners registered for the original node are not copied. See Also
AvailabilitySynopsisboolean dispatchEvent(Event evt) throws EventException; Arguments
Returnsfalse if the preventDefault( ) method of evt was called at any time during the propagation of the event, or true otherwise. ThrowsThis 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. DescriptionThis method dispatches a synthetic event created with Document.createEvent( ) and initialized with the initialization method defined by the Event interface or one of its subinterfaces. The node on which this method is called becomes the target of the event, but the event first propagates down the document tree during the capturing phase, and then, if the bubbles property of the event is true, it bubbles up the document tree after being handled at the event target itself. See AlsoDocument.createEvent( ), Event.initEvent( ), MouseEvent.initMouseEvent( )
AvailabilitySynopsisv oid removeEventListener(String type, EventListener listener, boolean useCapture); Arguments
DescriptionThis 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.
AvailabilityInherits from/OverridesNode Element HTMLElement HTMLAnchorElement PropertiesThis interface defines the properties in the following table, which correspond to the HTML attributes of the <a> tag.
Methods
DescriptionThis interface represents an <a> tag in an HTML document. href, name, and target are the key properties, representing the most commonly used attributes of the tag. HTMLAnchorElement objects can be obtained from the links and anchors HTMLCollection properties of the HTMLDocument interface. Example// Get the destination URL of first the hyperlink in the document var url = document.links[0].href; // Scroll the document so the anchor named "_bottom_" is visible document.anchors['_bottom_'].focus( ); See AlsoLink and Anchor objects in the client-side reference section
AvailabilitySynopsisvoid blur( ); DescriptionFor web browsers that allow hyperlinks to have the keyboard focus, this method takes keyboard focus away from a hyperlink.
AvailabilitySynopsisvoid focus( ); DescriptionThis 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.
AvailabilityInherits from/OverridesNode Element HTMLElement HTMLBodyElement Properties
DescriptionThe 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. Exampledocument.body.text = "#ff0000"; // Display text in bright red document.fgColor = "#ff0000"; // Same thing using old DOM Level 0 API document.body.style.color = "#ff0000"; // Same thing using CSS styles See AlsoDocument object in the client-side reference section
AvailabilityPropertiesMethods
DescriptionAn 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. Examplevar c = document.forms; // This is an HTMLCollection of form elements var firstform = c[0]; // It can be used like a numeric array var lastform = c[c.length-1]; // The length property gives the number of elements var address = c["address"]; // It can be used like an associative array var address = c.address; // JavaScript allows this notation, too See AlsoType ofHTMLDocument.anchors, HTMLDocument.applets, HTMLDocument.forms, HTMLDocument.images, HTMLDocument.links, HTMLFormElement.elements, HTMLMapElement.areas, HTMLSelectElement.options, HTMLTableElement.rows, HTMLTableElement.tBodies, HTMLTableRowElement.cells, HTMLTableSectionElement.rows
AvailabilitySynopsisNode item(unsigned long index); Arguments
ReturnsThe element at the specified index, or null if index is less than zero or greater than or equal to the length property. DescriptionThe 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. Examplevar c = document.images; // This is an HTMLCollection var img0 = c.item(0); // You can use the item( ) method this way var img1 = c[1]; // But this notation is easier and more common See Also
AvailabilitySynopsisNode namedItem(String name); Arguments
ReturnsAn element with the specified name, or null if no elements in the HTMLCollection have that name. DescriptionThis 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. Examplevar 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">
AvailabilityInherits from/OverridesNode Document HTMLDocument Properties
Methods
DescriptionThis interface extends Document and defines HTML-specific properties and methods that provide compatibility with the DOM Level 0 Document object (see the Document object in the client-side reference section). Note that HTMLDocument does not have all the properties of the Level 0 Document object. The properties that specify document colors and background images have been renamed and moved to the HTMLBodyElement. Finally, note that in the Level 1 DOM, HTMLDocument defines a method named getElementById( ). In the Level 2 DOM, this method has been moved to the Document interface, and it is now inherited by HTMLDocument rather than defined by it. See the Document.getElementById( ) entry in this reference section for details. See AlsoDocument.getElementById( ), HTMLBodyElement; Document object in the client-side reference section Returned byHTMLDOMImplementation.createHTMLDocument( )
AvailabilitySynopsisvoid close( ); DescriptionThis 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. See AlsoHTMLDocument.open( ); Document.close( ) in the client-side reference section
AvailabilitySynopsisNode[] getElementsByName(String elementName); Arguments
ReturnsAn 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. DescriptionThis 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. See AlsoDocument.getElementById( ), Document.getElementsByTagName( )
AvailabilitySynopsisvoid open( ); DescriptionThis 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. Examplevar w = window.open(""); // Open a new window var d = w.document; // Get its HTMLDocument object d.open(); // Open the document for writing d.write("<h1>Hello world</h1>"); // Output some HTML to the document d.close(); // End the document and display it See AlsoHTMLDocument.close( ), HTMLDocument.write( ); Document.open( ) in the client-side reference section
AvailabilitySynopsisvoid write(String text); Arguments
DescriptionThis 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. See AlsoHTMLDocument.open( ); Document.write( ) in the client-side reference section
AvailabilitySynopsisvoid writeln(String text); Arguments
DescriptionThis 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. See AlsoDocument.writeln( ) in the client-side reference section
AvailabilityInherits from/OverridesNode Element HTMLElement Also Implements
Subinterfaces
Properties
DescriptionThis 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:
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.
* Indicates interfaces documented in this book. ** Indicates deprecated elements and attributes. *** Indicates attributes added in HTML DOM Level 2 working draft. See AlsoHTMLElement in the client-side reference section Type ofHTMLDocument.body Passed toHTMLSelectElement.add( ) Returned byHTMLTableElement.createCaption( ), HTMLTableElement.createTFoot( ), HTMLTableElement.createTHead( ), HTMLTableElement.insertRow( ), HTMLTableRowElement.insertCell( ), HTMLTableSectionElement.insertRow( )
AvailabilityInherits from/OverridesNode Element HTMLElement HTMLFormElement Properties
In addition to the properties above, HTMLFormElement also defines the properties in the following table, which correspond directly to HTML attributes.
Methods
DescriptionThis interface represents a <form> element in an HTML document. The elements property is an HTMLCollection that provides convenient access to all elements of the form. The submit( ) and reset( ) methods allow a form to be submitted or reset under program control. See the Form object in the client-side reference section for more details. See AlsoForm object in the client-side reference section Type ofHTMLButtonElement.form, HTMLFieldSetElement.form, HTMLInputElement.form, HTMLIsIndexElement.form, HTMLLabelElement.form, HTMLLegendElement.form, HTMLObjectElement.form, HTMLOptionElement.form, HTMLSelectElement.form, HTMLTextAreaElement.form
AvailabilitySynopsisvoid reset( ); DescriptionThis 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. See AlsoForm.reset( ) in the client-side reference section
AvailabilitySynopsisvoid submit( ); DescriptionThis 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. See AlsoForm.submit( ) in the client-side reference section
AvailabilityInherits from/OverridesNode Element HTMLElement HTMLInputElement Properties
Methods
DescriptionThis 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.
See Chapter 15 for more information about HTML forms and form elements. Note also that each distinct type of form input element has its own reference page in the client-side reference section of this book. See AlsoHTMLFormElement, 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)
AvailabilitySynopsisvoid blur( ); DescriptionThis method takes keyboard focus away from this form element.
AvailabilitySynopsisvoid click( ); DescriptionThis 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.
AvailabilitySynopsisvoid focus( ); DescriptionThis method transfers keyboard focus to this element so the user can interact with it without first clicking on it.
AvailabilitySynopsisvoid select( ); DescriptionThis 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.
AvailabilityInherits from/OverridesNode Element HTMLElement HTMLOptionElement Properties
DescriptionThis interface describes an <option> element within a <select> element. See AlsoHTMLFormElement, HTMLInputElement, HTMLSelectElement; Option and Select objects in the client-side reference section; Chapter 15
AvailabilityInherits from/OverridesNode Element HTMLElement HTMLSelectElement Properties
Methods
DescriptionThis interface represents a <select> element in an HTML form. The options property provides convenient access to the set of <option> elements it contains, and the add( ) and remove( ) methods provide an easy way to modify the set of options. See AlsoHTMLFormElement, HTMLOptionElement; Option and Select objects in the client-side reference section; Chapter 15
AvailabilitySynopsisvoid add(HTMLElement element, HTMLElement before) throws DOMException; Arguments
ThrowsThis 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. DescriptionThis 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. See AlsoSelect object in the client-side reference section
AvailabilitySynopsisvoid blur( ); DescriptionThis method takes keyboard focus away from this element.
AvailabilitySynopsisvoid focus( ); DescriptionThis method transfers keyboard focus to this <select> element so the user can interact with it using the keyboard instead of the mouse.
AvailabilitySynopsisvoid remove(long index); Arguments
DescriptionThis method removes the <option> element at the specified position in the options array. If the specified index is less than zero or greater than or equal to the number of options, the remove( ) method ignores it and does nothing. See AlsoSelect object in the client-side reference section
AvailabilityInherits from/OverridesNode Element HTMLElement HTMLTableCaptionElement Properties
DescriptionA <caption> element in an HTML table. See AlsoType ofHTMLTableElement.caption
AvailabilityInherits from/OverridesNode Element HTMLElement HTMLTableCellElement PropertiesIn 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.
DescriptionThis interface represents <td> and <th> elements in HTML tables.
AvailabilityInherits from/OverridesNode Element HTMLElement HTMLTableColElement PropertiesThis interface defines the properties in the following table, each of which corresponds to an HTML attribute of a <col> or <colgroup> element.
DescriptionThis interface represents a <col> or <colgroup> element in an HTML table.
AvailabilityInherits from/OverridesNode Element HTMLElement HTMLTableElement Properties
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.
Methods
DescriptionThis interface represents an HTML <table> element and defines a number of convenience properties and methods for querying and modifying various sections of the table. These methods and properties make it easier to work with tables, but they could also be duplicated with core DOM methods. See AlsoHTMLTableCaptionElement, HTMLTableCellElement, HTMLTableColElement, HTMLTableRowElement, HTMLTableSectionElement
AvailabilitySynopsisHTMLElement createCaption( ); ReturnsAn 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.
AvailabilitySynopsisHTMLElement createTFoot( ); ReturnsAn 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.
AvailabilitySynopsisHTMLElement createTHead( ); ReturnsAn 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.
AvailabilitySynopsisvoid deleteCaption( ); DescriptionIf this table has a <caption> element, this method removes it from the document tree. Otherwise, it does nothing.
AvailabilitySynopsisvoid deleteRow(long index) throws DOMException; Arguments
ThrowsThis 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. DescriptionThis method deletes the row at the specified position from the table. Rows are numbered in the order in which they appear in the document source. Rows in <thead> and <tfoot> sections are numbered along with all other rows in the table. See Also
AvailabilitySynopsisvoid deleteTFoot( ); DescriptionIf this table has a <tfoot> element, this method removes it from the document tree. If the table has no footer, this method does nothing.
AvailabilitySynopsisvoid deleteTHead( ); DescriptionIf this table has a <thead> element, this method deletes it; otherwise, it does nothing.
AvailabilitySynopsisHTMLElement insertRow(long index) throws DOMException; Arguments
ReturnsAn HTMLTableRowElement that represents the newly inserted row. ThrowsThis 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. DescriptionThis 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. See Also
AvailabilityInherits from/OverridesNode Element HTMLElement HTMLTableRowElement Properties
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.
Methods
DescriptionThis interface represents a row in an HTML table.
AvailabilitySynopsisvoid deleteCell(long index) throws DOMException; Arguments
ThrowsThis 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. DescriptionThis method deletes the cell at the specified position in the table row.
AvailabilitySynopsisHTMLElement insertCell(long index) throws DOMException; Arguments
ReturnsAn HTMLTableCellElement object that represents the newly created and inserted <td> element. ThrowsThis 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. DescriptionThis 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.
AvailabilityInherits from/OverridesNode Element HTMLElement HTMLTableSectionElement Properties
In addition to the rows property, this interface defines the properties in the following table, which represent the attributes of the underlying HTML element.
Methods
DescriptionThis interface represents a <tbody>, <thead>, or <tfoot> section of an HTML table. See AlsoType ofHTMLTableElement.tFoot, HTMLTableElement.tHead
AvailabilitySynopsisvoid deleteRow(long index) throws DOMException; Arguments
ThrowsThis 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. DescriptionThis method deletes the row at the specified position within this section. Note that for this method index specifies a row's position within its section, not within the entire table. See Also
AvailabilitySynopsisHTMLElement insertRow(long index) throws DOMException; Arguments
ReturnsAn HTMLTableRowElement that represents the newly created and inserted <tr> element. ThrowsThis 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. DescriptionThis 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. See Also
AvailabilityInherits from/OverridesNode Element HTMLElement HTMLTextAreaElement Properties
Methods
DescriptionThis interface represents a <textarea> element that creates a multiline text-input field in an HTML form. The initial contents of the text area are specified between the <textarea> and </textarea> tags. The user may edit this value and query and set the text with the value property (or by modifying the Text node child of this element). See AlsoHTMLFormElement, HTMLInputElement; Textarea in the client-side reference section; Chapter 15
AvailabilitySynopsisvoid blur( ); DescriptionThis method takes keyboard focus away from this element.
AvailabilitySynopsisvoid focus( ); DescriptionThis method transfers keyboard focus to this element so the user can edit the displayed text without having to first click on the text area.
AvailabilitySynopsisvoid select( ); DescriptionThis 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.
AvailabilityPropertiesDescriptionIn 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. See Also
AvailabilityProperties
Methods
DescriptionThis interface represents a list or array of media types for a style sheet. length specifies the number of elements in the list, and item( ) allows a specific media type to be retrieved by position. appendMedium( ) and deleteMedium( ) allow entries to be appended to and deleted from the list. JavaScript allows a MediaList object to be treated as an array, and you can use square-bracket notation instead of calling item( ). The HTML 4 standard defines the following media types (they are case-sensitive, and must be written in lowercase letters): screen, tty, tv, projection, handheld, print, braile, aural, and all. The screen type is most relevant to documents being displayed in web browsers on desktop or laptop computers. The print type is used for styles intended for printed documents. See AlsoType ofStyleSheet.media
AvailabilitySynopsisvoid appendMedium(String newMedium) throws DOMException; Arguments
ThrowsThis 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. DescriptionThis 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.
AvailabilityDOM Level 2 StyleSheets AvailabilitySynopsisvoid deleteMedium(String oldMedium) throws DOMException; Arguments
ThrowsThis 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. DescriptionThis method deletes the specified media type from this MediaList, or throws an exception if the list does not contain the specified type.
AvailabilitySynopsisString item(unsigned long index); Arguments
ReturnsThe 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.
AvailabilityInherits from/OverridesEvent UIEvent MouseEvent Properties
Methods
DescriptionThis interface defines the type of Event object that is passed to events of types click, mousedown, mousemove, mouseout, mouseover, and mouseup. Note that in addition to the properties listed here, this interface also inherits the properties of the UIEvent and Event interfaces. See Also
AvailabilitySynopsisvoid 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); ArgumentsThe 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. DescriptionThis 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( ).
AvailabilityInherits from/OverridesEvent MutationEvent ConstantsThe following constants represent the set of possible values for the attrChange property:
Properties
Methods
DescriptionThis 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( )):
AvailabilitySynopsisvoid initMutationEvent(String typeArg, boolean canBubbleArg, boolean cancelableArg, Node relatedNodeArg, String prevValueArg, String newValueArg, String attrNameArg, unsigned short attrChangeArg); ArgumentsThe 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. DescriptionThis 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( ).
AvailabilityPropertiesMethods
DescriptionThe NamedNodeMap interface defines a collection of nodes that may be looked up by their nodeName property or, for nodes that use namespaces, by their namespaceURI or localName properties. The most notable use of the NamedNodeMap interface is the attributes property of the Node interface: a collection of Attr nodes that may be looked up by attribute name. Many of the methods of NamedNodeMap are similar to the methods of Element for manipulating attributes. Element attributes are usually most easily manipulated through the methods of the Element interface, and the NamedNodeMap interface is not commonly used. NamedNodeMap objects are "live," which means that they immediately reflect any changes to the document tree. For example, if you obtain a NamedNodeMap that represents the attributes of an element and then add a new attribute to that element, the new attribute is available through the NamedNodeMap. See AlsoType ofDocumentType.entities, DocumentType.notations, Node.attributes
AvailabilitySynopsisNode getNamedItem(String name); Arguments
ReturnsThe named node, or null if no node with that name was found.
AvailabilitySynopsisNode getNamedItemNS(String namespaceURI, String localName); Arguments
ReturnsThe element of the NamedNodeMap that has the specified namespaceURI and localName properties, or null if there is no such node. DescriptiongetNamedItemNS( ) looks up an element of a NamedNodeMap by namespace and local name. It is useful only with XML documents that use namespaces.
AvailabilitySynopsisNode item(unsigned long index); Arguments
ReturnsThe node at the specified position, or null if index is less than zero or greater than or equal to the length of the NamedNodeMap. DescriptionThis 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. See Also
AvailabilitySynopsisNode removeNamedItem(String name) throws DOMException; Arguments
ReturnsThe node that was removed. ThrowsThis 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. DescriptionDeletes 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. See Also
AvailabilitySynopsisNode removeNamedItemNS(String namespaceURI, String localName) throws DOMException; Arguments
ReturnsThe node that was removed. ThrowsThis method throws exceptions for the same reason as removeNamedItem( ). DescriptionThis 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.
AvailabilitySynopsisNode setNamedItem(Node arg) throws DOMException; Arguments
ReturnsThe node that was replaced, or null if no node was replaced. ThrowsThis method may throw a DOMException with one of the following code values:
DescriptionsetNamedItem( ) 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. See Also
AvailabilitySynopsisNode setNamedItemNS(Node arg) throws DOMException; Arguments
ReturnsThe node that was replaced, or null if no node was replaced. ThrowsThis 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. DescriptionThis 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.
AvailabilitySubinterfacesAttr, CharacterData, Document, DocumentFragment, DocumentType, Element, Entity, EntityReference, Notation, ProcessingInstruction Also Implements
ConstantsAll Node objects implement one of the subinterfaces listed above. Every Node object has a nodeType property that specifies which of the subinterfaces it implements. These constants are the legal values for that property; their names are self-explanatory. Note that these are static properties of the Node( ) constructor function; they are not properties of individual Node objects. Also note that they are not supported by Internet Explorer 4, 5, or 6. Node.ELEMENT_NODE = 1; // Element Node.ATTRIBUTE_NODE = 2; // Attr Node.TEXT_NODE = 3; // Text Node.CDATA_SECTION_NODE = 4; // CDATASection Node.ENTITY_REFERENCE_NODE = 5; // EntityReference Node.ENTITY_NODE = 6; // Entity Node.PROCESSING_INSTRUCTION_NODE = 7; // ProcessingInstruction Node.COMMENT_NODE = 8; // Comment Node.DOCUMENT_NODE = 9; // Document Node.DOCUMENT_TYPE_NODE = 10; // DocumentType Node.DOCUMENT_FRAGMENT_NODE = 11; // DocumentFragment Node.NOTATION_NODE = 12; // Notation Properties
Methods
DescriptionAll 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.
See Also
AvailabilitySynopsisNode appendChild(Node newChild) throws DOMException; Arguments
ReturnsThe node that was added. ThrowsThis method may throw a DOMException with one of the following code values in the following circumstances:
DescriptionThis 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. ExampleThe following function inserts a new paragraph at the end of the document: function appendMessage(message) { var pElement = document.createElement("P"); var messageNode = document.createTextNode(message); pElement.appendChild(messageNode); // Add text to paragraph document.body.appendChild(pElement); // Add paragraph to document body } See AlsoNode.insertBefore( ), Node.removeChild( ), Node.replaceChild( )
AvailabilitySynopsisNode cloneNode(boolean deep); Arguments
ReturnsA copy of this node. DescriptionThe 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.
AvailabilitySynopsisboolean hasAttributes( ); Returnstrue if this node has one or more attributes; false if it has none. Note that only Element nodes can have attributes. See Also
AvailabilitySynopsisboolean hasChildNodes( ); Returnstrue if this node has one or more children; false if it has none. See AlsoNode.childNodes
AvailabilitySynopsisNode insertBefore(Node newChild, Node refChild) throws DOMException; Arguments
ReturnsThe node that was inserted. ThrowsThis method may throw a DOMException with the following code values:
DescriptionThis 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. ExampleThe following function inserts a new paragraph at the beginning of a document: function insertMessage(message) { var paragraph = document.createElement("p"); // Create a <p> Element var text = document.createTextNode(message); // Create a Text node paragraph.appendChild(text); // Add text to the paragraph // Now insert the paragraph before the first child of the body document.body.insertBefore(paragraph, document.body.firstChild) } See AlsoNode.appendChild( ), Node.removeChild( ), Node.replaceChild( )
AvailabilitySynopsisboolean isSupported(String feature, String version); Arguments
Returnstrue if the node supports the specified version of the specified feature, and false if it does not. DescriptionThe 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. See Also
AvailabilitySynopsisvoid normalize( ); DescriptionThis 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. See Also
AvailabilitySynopsisNode removeChild(Node oldChild) throws DOMException; Arguments
ReturnsThe node that was removed. ThrowsThis method may throw a DOMException with the following code values in the following circumstances:
DescriptionThis 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. ExampleYou can delete the last child of the document body with this code: document.body.removeChild(document.body.lastChild); See AlsoNode.appendChild( ), Node.insertBefore( ), Node.replaceChild( )
AvailabilitySynopsisNode replaceChild(Node newChild, Node oldChild) throws DOMException; Arguments
ReturnsThe node that was removed from the document and replaced. ThrowsThis method may throw a DOMException with the following code values:
DescriptionThis 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. ExampleThe following code replaces a node n with a <b> element and then inserts the replaced node into the <b> element, which reparents the node and makes it appear in bold: // Get the first child node of the first paragraph in the document var n = document.getElementsByTagName("p")[0].firstChild; var b = document.createElement("b"); // Create a <b> element n.parentNode.replaceChild(b, n); // Replace the node with <b> b.appendChild(n); // Reinsert the node as a child of <b> See AlsoNode.appendChild( ), Node.insertBefore( ), Node.removeChild( )
AvailabilityConstantsThe 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; Methods
DescriptionA 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. ExampleYou might define and use a node filter function as follows: // Define a node filter that filters out everything but <h1> and <h2> elements var myfilter = function(n) { // Filter node n if ((n.nodeName == "H1") || (n.nodeName == "H2")) return NodeFilter.FILTER_ACCEPT; else return NodeFilter.FILTER_SKIP; } // Now create a NodeIterator that uses the filter var ni = document.createNodeIterator(document.body, // Traverse the document body NodeFilter.SHOW_ELEMENT, // Elements only myfilter, // Filter by tag name false); // No entity expansion See AlsoType ofNodeIterator.filter, TreeWalker.filter Passed toDocument.createNodeIterator( ), Document.createTreeWalker( )
AvailabilityProperties
Methods
DescriptionA NodeIterator represents the sequence of Document nodes that results from traversing a document subtree in document source order and filtering the nodes using a two-stage process. Create a NodeIterator object with Document.createNodeIterator( ). Use the nextNode( ) and previousNode( ) methods to iterate forward and backward through the sequence of nodes. Call detach( ) when you are done with a NodeIterator, unless you are sure that the NodeIterator will be garbage collected before the document is modified. Note that the properties of this interface are all read-only copies of the arguments passed to Document.createNodeIterator( ). To be returned by the nextNode( ) or previousNode( ) methods, a node must pass two filtration steps. First, the node type must be one of the types specified by the whatToShow property. See NodeFilter for a list of constants that can be combined to specify the whatToShow argument to Document.createNodeIterator( ). Next, if the filter property is not null, each node that passes the whatToShow test is passed to the filter function specified by the filter property. If this function returns NodeFilter.FILTER_ACCEPT, the node is returned. If it returns NodeFilter.FILTER_REJECT or NodeFilter.FILTER_SKIP, the NodeIterator skips the node. Note that when a node is rejected by either of these filtration steps, it is only the node itself that is rejected; the children of the node are not automatically rejected and are subject to the same filtration steps. NodeIterator objects remain valid even if the document tree they are traversing is modified. The nextNode( ) and previousNode( ) methods return nodes based on the current state of the document, not the state of the document that existed when the NodeIterator was created. See AlsoNodeFilter, TreeWalker; Chapter 17 Returned byDocument.createNodeIterator( )
AvailabilitySynopsisvoid detach( ); DescriptionDOM 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.
AvailabilitySynopsisNode nextNode( ) throws DOMException; ReturnsThe next node in the sequence of nodes represented by this NodeIterator, or null if the last node has already been returned. ThrowsIf this method is called after a call to detach( ), it throws a DOMException with a code of INVALID_STATE_ERR. DescriptionThis 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. Example// 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 }
AvailabilitySynopsisNode previousNode( ) throws DOMException; ReturnsThe previous node in the sequence of nodes represented by this NodeIterator, or null if there is no previous node. ThrowsIf this method is called after a call to detach( ), it throws a DOMException with a code of INVALID_STATE_ERR. DescriptionThis 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.
AvailabilityPropertiesMethods
DescriptionThe NodeList interface defines a read-only ordered list (i.e., an array) of Node objects. The length property specifies how many nodes are in the list, and the item( ) method allows you to obtain the node at a specified position in the list. The elements of a NodeList are always valid Node objects: NodeLists never contain null elements. In JavaScript, NodeList objects behave like JavaScript arrays, and you can query an element from the list using square-bracket array notation instead of calling the item( ) method. However, you cannot assign new nodes to a NodeList using square brackets. Since it is always easier to think of a NodeList object as a read-only JavaScript array, this book uses the notation Node[] (i.e., a Node array) instead of NodeList. See Element.getElementsByTagName( ), for example, which is listed as returning a Node[] instead of a NodeList object. Similarly, the childNodes property of the Node object is technically a NodeList object, but the "Node" reference page defines it as a Node[], and the property itself is usually referred to as "the childNodes[] array." Note that NodeList objects are "live": they are not static, but immediately reflect changes to the document tree. For example, if you have a NodeList that represents the children of a specific node and you then delete one of those children, the child will be removed from your NodeList. Be careful when you are looping through the elements of a NodeList if the body of your loop makes changes to the document tree (such as deleting nodes) that may affect the contents of the NodeList! See AlsoType ofNode.childNodes Returned byDocument.getElementsByTagName( ), Document.getElementsByTagNameNS( ), Element.getElementsByTagName( ), Element.getElementsByTagNameNS( ), HTMLDocument.getElementsByName( )
AvailabilitySynopsisNode item(unsigned long index); Arguments
ReturnsThe 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. DescriptionThis method returns the specified element of a NodeList. In JavaScript, you can use the square-bracket array notation instead of calling item( ).
AvailabilityInherits from/OverridesNode Notation Properties
DescriptionThis 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. See Also
AvailabilityInherits from/OverridesNode ProcessingInstruction Properties
DescriptionThis infrequently used interface represents a processing instruction (or PI) in an XML document. Programmers working with HTML documents will never encounter a ProcessingInstruction node. See AlsoReturned byDocument.createProcessingInstruction( )
AvailabilityConstantsThese 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.
PropertiesThe 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.
MethodsThe 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.
DescriptionA Range object represents a contiguous range or region of a document, such as the region that the user might select with a mouse drag in a web browser window. If an implementation supports the Range module, the Document object defines a createRange( ) method that you can call to create a new Range object. (Be careful, however: Internet Explorer defines an incompatible Document.createRange( ) method that returns an object similar to, but not compatible with, the Range interface.) The Range interface defines a number of methods for specifying a "selected" region of a document and several more methods for implementing cut and paste-type operations on the selected region. A range has two boundary points: a start point and an end point. Each boundary point is specified by a combination of a node and an offset within that node. The node is typically an Element, Document, or Text node. For Element and Document nodes, the offset refers to the children of that node. An offset of 0 specifies a boundary point before the first child of the node. An offset of 1 specifies a boundary point after the first child and before the second child. If the boundary node is a Text node, however, the offset specifies a position between two characters of that text. The properties of the Range interface provide a way to obtain boundary nodes and offsets of a range. The methods of the interface provide a number of ways to set the boundaries of a range. Note that the boundaries of a range may be set to nodes within a Document or a DocumentFragment. Once the boundary points of a range are defined, you can use deleteContents( ), extractContents( ), cloneContents( ), and insertNode( ) to implement cut-, copy-, and paste-style operations. When a document is altered by insertion or deletion, all Range objects that represent portions of that document are altered, if necessary, so that their boundary points remain valid and they represent (as closely as possible) the same document content. For further details, read the reference pages for each of the Range methods and see the discussion of the Range API in Chapter 17. See AlsoDocument.createRange( ), DocumentFragment; Chapter 17 Passed toRange.compareBoundaryPoints( ) Returned byDocument.createRange( ), Range.cloneRange( )
AvailabilitySynopsisDocumentFragment cloneContents( ) throws DOMException; ReturnsA DocumentFragment object that contains a copy of the document content within this range. ThrowsIf this range includes a DocumentType node, this method throws a DOMException with a code of HIERARCHY_REQUEST_ERR. DescriptionThis method duplicates the contents of this range and returns the results in a DocumentFragment object. See AlsoDocumentFragment, Range.deleteContents( ), Range.extractContents( )
AvailabilitySynopsisRange cloneRange( ); ReturnsA new Range object that has the same boundary points as this range. See Also
AvailabilitySynopsisvoid collapse(boolean toStart) throws DOMException; Arguments
DescriptionThis 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.
AvailabilitySynopsisshort compareBoundaryPoints(unsigned short how, Range sourceRange) throws DOMException; Arguments
Returns-1 if the specified boundary point of this range is before the specified boundary point of sourceRange, 0 if the two specified boundary points are the same, or 1 if the specified boundary point of this range is after the specified boundary point of sourceRange. ThrowsIf sourceRange represents a range of a different document than this range does, this method throws a DOMException with a code of WRONG_DOCUMENT_ERR. DescriptionThis 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.
AvailabilitySynopsisvoid deleteContents( ) throws DOMException; ThrowsIf 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. DescriptionThis 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. See AlsoNode.normalize( ), Range.cloneContents( ), Range.extractContents( )
AvailabilitySynopsisvoid detach( ) throws DOMException; ThrowsLike 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. DescriptionDOM 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.
AvailabilitySynopsisDocumentFragment extractContents( ) throws DOMException; ReturnsA DocumentFragment node that contains the contents of this range. ThrowsThis 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. DescriptionThis 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( )). See AlsoDocumentFragment, Range.cloneContents( ), Range.deleteContents( )
AvailabilitySynopsisvoid insertNode(NodenewNode) throws RangeException, DOMException; Arguments
ThrowsThis 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:
DescriptionThis method inserts the specified node (and all its descendants) into the document at the start position of this range. When this method returns, this range includes the newly inserted node. If newNode is already part of the document, it is removed from its current position and then reinserted at the start of the range. If newNode is a DocumentFragment node, it is not inserted itself, but all of its children are inserted, in order, at the start of the range. If the node that contains the start of the range is a Text node, it is split into two adjacent nodes before the insertion takes place. If newNode is a Text node, it is not merged with any adjacent Text nodes after it is inserted. To merge adjacent nodes, call Node.normalize( ). See Also
AvailabilitySynopsisvoid selectNode(Node refNode) throws RangeException, DOMException; Arguments
ThrowsA 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. DescriptionThis method sets the contents of this range to the specified refNode. That is, it "selects" the node and its descendants. See Also
AvailabilitySynopsisvoid selectNodeContents(Node refNode) throws RangeException, DOMException; Arguments
ThrowsA 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. DescriptionThis method sets the boundary points of this range so that the range contains the children of refNode. See Also
AvailabilitySynopsisvoid setEnd(Node refNode, long offset) throws RangeException, DOMException; Arguments
ThrowsA 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. DescriptionThis method sets the end point of a range by specifying the values of the endContainer and endOffset properties.
AvailabilitySynopsisvoid setEndAfter(Node refNode) throws RangeException, DOMException; Arguments
ThrowsA 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. DescriptionThis method sets the end point of this range to fall immediately after the specified refNode.
AvailabilitySynopsisvoid setEndBefore(Node refNode) throws RangeException, DOMException; Arguments
ThrowsThis method throws the same exceptions in the same circumstances as Range.setEndAfter( ). See that method for details. DescriptionThis method sets the end point of this range to fall immediately before the specified refNode.
AvailabilitySynopsisvoid setStart(Node refNode, long offset) throws RangeException, DOMException; Arguments
ThrowsThis method throws the same exceptions, for the same reasons, as Range.setEnd( ). See that method for details. DescriptionThis method sets the start point of this range by specifying the values of the startContainer and startOffset properties.
AvailabilitySynopsisvoid setStartAfter(Node refNode) throws RangeException, DOMException; Arguments
ThrowsThis method throws the same exceptions in the same circumstances as Range.setEndAfter( ). See that method for details. DescriptionThis method sets the starting point of this range to be immediately after the specified refNode.
AvailabilitySynopsisvoid setStartBefore(Node refNode) throws RangeException, DOMException; Arguments
ThrowsThis method throws the same exceptions in the same circumstances as Range.setEndAfter( ). See that method for details. DescriptionThis method sets the starting point of this range to be immediately before the specified refNode.
AvailabilitySynopsisvoid surroundContents(Node newParent) throws RangeException, DOMException; Arguments
ThrowsThis method throws a DOMException or RangeException with one of the following code values in the following circumstances:
DescriptionThis 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.
AvailabilitySynopsisString toString( ); ReturnsThe contents of this range as a string of plain text without any markup.
AvailabilityConstantsThe 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.
Properties
DescriptionA 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.
AvailabilityProperties
DescriptionThis 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. See AlsoReturned byCSSPrimitiveValue.getRectValue( )
AvailabilityProperties
DescriptionThis 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%. See AlsoReturned byCSSPrimitiveValue.getRGBColorValue( )
AvailabilitySubinterfacesCSSStyleSheet Properties
DescriptionThis interface represents a style sheet that is associated with this document. If this is a CSS style sheet, the object that implements this StyleSheet interface also implements the CSSStyleSheet subinterface and defines properties and methods that allow you to examine and set the CSS rules that comprise the style sheet. See CSSStyleSheet for details. If a DOM implementation supports style sheets, you can obtain a complete list of the style sheets associated with a document through the Document.styleSheets property. Furthermore, the HTML <style> and <link> elements and XML style-sheet ProcessingInstruction nodes implement the LinkStyle interface and provide a reference to the StyleSheet through a property named sheet. See AlsoCSSStyleSheet, Document.styleSheets, LinkStyle Type ofLinkStyle.sheet, StyleSheet.parentStyleSheet Returned byStyleSheetList.item( )
AvailabilityPropertiesMethods
DescriptionThis 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. See AlsoType ofDocumentStyle.styleSheets
AvailabilitySynopsisStyleSheet item(unsigned long index); Arguments
ReturnsThe 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.
AvailabilityInherits from/OverridesNode CharacterData Text SubinterfacesCDATASection Methods
DescriptionA 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. See AlsoCharacterData, Node.normalize( ) Returned byDocument.createTextNode( ), Text.splitText( )
AvailabilitySynopsisText splitText(unsigned long offset) throws DOMException; Arguments
ReturnsThe Text node that was split from this node. ThrowsThis method may throw a DOMException with one of the following code values:
DescriptionThis method splits a Text node in two at the specified offset. The original Text node is modified so that it contains all text content up to, but not including, the character at position offset. A new Text node is created to contain all the characters from (and including) the position offset to the end of the string. This new Text node is the return value of the method. Additionally, if the original Text node has a parentNode, the new node is inserted into this parent node immediately after the original node. The CDATASection interface inherits from Text, and this splitText( ) method can also be used with CDATASection nodes, in which case the newly created node is a CDATASection rather than a Text node. See Also
AvailabilityProperties
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.
Methods
DescriptionA TreeWalker filters a specified document subtree and defines methods that allow programs to traverse the filtered tree (which may have a significantly different structure than the original document tree). Create a TreeWalker object with the createTreeWalker( ) method of the Document object. Once a TreeWalker is created, you can use its firstChild( ) and nextSibling( ) methods to traverse the filtered subtree it represents in the same way that you might use the firstChild and nextSibling properties of the Node interface to traverse an unfiltered document tree. A TreeWalker applies the same two filtration steps that a NodeIterator does. The various traversal methods defined by TreeWalker will return only nodes that pass both filters. First, the node type must be one of the types specified by the whatToShow property. See NodeFilter for a list of constants that can be combined to specify the whatToShow argument to Document.createTreeWalker( ). Second, if the filter property is not null, each node that passes the whatToShow test is passed to the filter function specified by the filter property. If this function returns NodeFilter.FILTER_ACCEPT, the node is returned. If it returns NodeFilter.FILTER_REJECT, the node and all of its descendants are skipped by the TreeWalker (this differs from NodeIterator filtration, in which descendants are never automatically rejected). If the node filter function returns NodeFilter.FILTER_SKIP, the TreeWalker ignores the node but does consider its descendants. Unlike NodeIterators, TreeWalkers are not modified when the underlying document is modified. The current node of a TreeWalker remains unchanged, even if that node is removed from the document. (And, in this case, the TreeWalker can be used to traverse the tree of deleted nodes, if any, that surround that current node.) Example// A NodeFilter that rejects <font> tags and any element with a // class="sidebar" attribute and any descendants of such an element var filter = function(n) { if (n.nodeName == "FONT") return NodeFilter.FILTER_SKIP; if (n.nodeType == Node.ELEMENT_NODE && n.className == "sidebar") return NodeFilter.FILTER_REJECT; return NodeFilter.FILTER_ACCEPT; } // Create a TreeWalker using the filter above var tw = document.createTreeWalker(document.body, // Walk HTML document body // Consider all nodes except comments ~NodeFilter.SHOW_COMMENT, filter, // Use filter above false); // Don't expand entity references // Here's a recursive function that traverses a document using a TreeWalker function traverse(tw) { // Remember the current node var currentNode = tw.currentNode; // Loop through the children of the current node of the TreeWalker for(var c = tw.firstChild( ); c != null; c = tw.nextSibling( )) { process(c); // Do something to process the child traverse(tw); // And recursively process its children } // Put the TreeWalker back in the state we found it in tw.currentNode = currentNode; } See AlsoNodeFilter, NodeIterator; Chapter 17 Returned byDocument.createTreeWalker( )
AvailabilitySynopsisNode firstChild( ); ReturnsThe first child of the current node that is not filtered out, or null if there is no such child. DescriptionThis 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.
AvailabilitySynopsisNode lastChild( ); ReturnsThe last child of the current node that is not filtered out, or null if there is no such child. DescriptionThis 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.
AvailabilitySynopsisNode nextNode( ); ReturnsThe node that follows the current node in the document source and is not filtered out, or null if there is none. DescriptionThis 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( ).
AvailabilitySynopsisNode nextSibling( ); ReturnsThe next sibling of the current node that is not filtered out, or null if there is no such sibling. DescriptionThis 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.
AvailabilitySynopsisNode parentNode( ); ReturnsThe nearest ancestor of the current node that is not filtered out, or null if there is no such ancestor. DescriptionThis 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.
AvailabilitySynopsisNode previousNode( ); ReturnsThe nearest node that precedes the current node in the document source and is not filtered out, or null if there is none. DescriptionThis 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( ).
AvailabilitySynopsisNode previousSibling( ); ReturnsThe previous sibling of the current node that is not filtered out, or null if there is no such sibling. DescriptionThis 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.
AvailabilityInherits from/OverridesEvent UIEvent SubinterfacesMouseEvent Properties
Methods
DescriptionThe UIEvent interface is a subinterface of Event and defines the type of Event object passed to events of type DOMFocusIn, DOMFocusOut, and DOMActivate. These event types are not commonly used in web browsers, and what is more important about the UIEvent interface is that it is the parent interface of MouseEvent. See Also
AvailabilitySynopsisvoid initUIEvent(String typeArg, boolean canBubbleArg, boolean cancelableArg, AbstractView viewArg, long detailArg); Arguments
DescriptionThis 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( ).
Copyright © 2003 O'Reilly & Associates. All rights reserved. |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|