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


Dynamic HTML: The Definitive Reference, 2rd Ed.Dynamic HTML: The Definitive ReferenceSearch this book

9.5. Shared Object Properties, Methods, and Events

Both the proprietary Internet Explorer DOM and W3C DOM expose a wide range of properties (including event handler properties) and methods almost universally across objects that reflect HTML elements. Rather than repeat the descriptions of these items ad nauseam in the reference listing, I am listing their details only once. Due to the large number of shared items (80 properties, 60 methods, and 72 event types), these shared items do not appear in the lists of properties, methods, and events for each object in the rest of this chapter, but they are available for practically every HTML element object (within the browser or standard version range indicated in each listing).

Obviously, the shared properties or methods that are meaningless except for rendered element objects may not be available to nonrendered elements. For example, invoking the IE scrollIntoView( ) method of a style element object is meaningless because the style element presents no content of its own on the page to which a window could scroll. Such items are typically part of the DOMs simply because the browsers' internal architectures utilize an inheritance mechanism that empowers all element objects with the same basic items, even if they have no particular application. You should get to know the shared items well, and refer to the object-specific items later in this chapter when you need their special powers.

In the following item descriptions, the example code uses the term elementID to refer to the identifier assigned to the id attribute of the element. In your scripts, substitute the object's true ID for the placeholder used here. Here is a list of the common items:

9.5.3. Event Handlers

Events

IE Windows

IE Mac

NN

W3C DOM

DOMActivate[13]

n/a

n/a

n/a

2

DOMAttrModified[13]

n/a

n/a

6

2

DOMCharacterDataModified[13]

n/a

n/a

6

2

DOMFocusIn[13]

n/a

n/a

n/a

2

DOMFocusOut[13]

n/a

n/a

n/a

2

DOMNodeInserted[13]

n/a

n/a

6

2

DOMNodeInsertedIntoDocument[13]

n/a

n/a

6

2

DOMNodeRemoved[13]

n/a

n/a

6

2

DOMNodeRemovedFromDocument[13]

n/a

n/a

6

2

DOMSubtreeModified[13]

n/a

n/a

6

2

onactivate

5.5

n/a

n/a

n/a

onafterupdate[14]

4

5

n/a

n/a

onbeforeactivate

6

n/a

n/a

n/a

onbeforecopy

5

n/a

n/a

n/a

onbeforecut

5

n/a

n/a

n/a

onbeforedeactivate

5.5

n/a

n/a

n/a

onbeforeeditfocus

5

n/a

n/a

n/a

onbeforepaste

5

n/a

n/a

n/a

onbeforeupdate[14]

4

5

n/a

n/a

onblur[15]

3

3.01

2

1

oncellchange[16]

5

n/a

n/a

n/a

onclick[15]

3

3.01

2

1

oncontextmenu

5

n/a

n/a

n/a

oncontrolselect

5.5

n/a

n/a

n/a

oncopy

5

n/a

n/a

n/a

oncut

5

n/a

n/a

n/a

ondataavailable[16]

4

n/a

n/a

n/a

ondatasetchanged[16]

4

n/a

n/a

n/a

ondatasetcomplete[16]

4

n/a

n/a

n/a

ondblclick[15]

4

4

3

n/a

ondeactivate

5.5

n/a

n/a

n/a

ondrag

5

n/a

n/a

n/a

ondragend

5

n/a

n/a

n/a

ondragenter

5

n/a

n/a

n/a

ondragleave

5

n/a

n/a

n/a

ondragover

5

n/a

n/a

n/a

ondragstart

5

n/a

n/a

n/a

ondrop

5

n/a

n/a

n/a

onerrorupdate[14]

4

5

n/a

n/a

onfilterchange

4

n/a

n/a

n/a

onfocus[15]

3

3.01

2

1

onfocusin

6

n/a

n/a

n/a

onfocusout

6

n/a

n/a

n/a

onhelp[15]

4

5

n/a

n/a

onkeydown[15]

4

4

4

3

onkeypress[15]

4

4

4

3

onkeyup[15]

4

4

4

3

onlayoutcomplete

5.5

n/a

n/a

n/a

onlosecapture

5

n/a

n/a

n/a

onmousedown[15]

4

4

4

1

onmouseenter

5.5

n/a

n/a

n/a

onmouseleave

5.5

n/a

n/a

n/a

onmousemove[15]

4

4

4

1

onmouseout[15]

3

3.01

2

1

onmouseover[15]

3

3.01

2

1

onmouseup[15]

4

4

4

1

onmousewheel

6

n/a

n/a

n/a

onmove

5.5

n/a

n/a

n/a

onmoveend

5.5

n/a

n/a

n/a

onmovestart

5.5

n/a

n/a

n/a

onpaste

5

n/a

n/a

n/a

onpropertychange

5

n/a

n/a

n/a

onreadystatechange[17]

4

n/a

n/a

n/a

onresize[15]

4

4

4

n/a

onresizeend

5.5

n/a

n/a

n/a

onresizestart

5.5

n/a

n/a

n/a

onrowenter[16]

4

n/a

n/a

n/a

onrowexit[16]

4

n/a

n/a

n/a

onrowsdelete[16]

5

n/a

n/a

n/a

onrowsinserted[16]

5

n/a

n/a

n/a

onscroll[18]

4

4

n/a

n/a

onselectstart

4

4

n/a

n/a

[13] Event type assignable only via the addEventListener( ) method for any node.

[14]Exposed as property for all elements in IE 6, but applies only to elements that support data binding: a, bdo, button, custom, div, frame, iframe, img, input (checkbox, hidden, password, radio, text), label, legend, marquee, rt, ruby, select, span, and textarea.

[15]Shared among all element objects only in recent browsers. Earlier implementations and compatibilities are listed with applicable objects throughout this chapter.

[16]Exposed as property for all elements in IE 6, but applies only to applet, object, and xml elements set for data binding.

[17]Exposed as property for all elements in IE 6, but applies only to applet, document, frame, frameSet, iframe, img, link, object, script, and xml elements unless an HTML behavior is attached to the element.

[18]Exposed as property for all elements in IE 6, but applies only applet, bdo, body, custom, div, embed, map, marquee, object, table, and textarea elements and the window object.

 
ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODENN 6 IE n/a DOM 1

Read-only
This set of constants belongs to the root Node object of the W3C DOM, and is therefore inherited by all document-level nodes and elements. Each property corresponds to an integer value associated with the nodeType property of every DOM node. You can use these properties as a more plain-language way to indicate the node type your script is looking for in comparisons or similar operations.

Example

if (myObject.nodeType == document.ELEMENT_NODE) {
    // process as an element here
}

Value

Integer corresponding to DOM node type as follows.

Property nodeTypeValue

ELEMENT_NODE

1

ATTRIBUTE_NODE

2

TEXT_NODE

3

CDATA_SECTION_NODE

4

ENTITY_REFERENCE_NODE

5

ENTITY_NODE

6

PROCESSING_INSTRUCTION_NODE

7

COMMENT_NODE

8

DOCUMENT_NODE

9

DOCUMENT_TYPE_NODE

10

DOCUMENT_FRAGMENT_NODE

11

NOTATION_NODE

12

Default

Constant values (above).

 
accessKeyNN n/a IE 4 DOM 1

Read/Write
This is single character key that either gives focus to an element (in some browsers) or activates a form control or link action. The browser and operating system determine if the user must press a modifier key (e.g., Ctrl, Alt, or Command) with the access key to activate the link. In Windows versions of IE 5 and later and Netscape 6, the Alt key is required and the key is not case-sensitive. For Macintosh versions of IE 5 and later and Netscape 6, the Ctrl modifier key is required to effect the action.

Although listed here as a widely shared property, that isn't strictly the case across all implementations. Netscape 6 (per the W3C DOM) recognizes this property only for the following elements: a, area, button, input, label, legend, and textarea. To this list, IE 4 adds applet, body, div, embed, isindex, marquee, object, select, span, table, and td (but removes label and legend). IE 5 adds every other renderable element, but with a caution. Except for input and other form-related elements, you must also assign a tabindex attribute or tabIndex property value to the IE 5 and later element (even if it's simply a value of zero for all) to let the accelerator key combination bring focus to the element. As of Version 7, Netscape does not alter UI behavior if a script changes the property's value.

Example

document.links[3].accessKey = "n";

Value

Single alphanumeric (and punctuation) keyboard character.

Default

Empty string.

 
all[ ]NN n/a IE 4 DOM n/a

Read-only
Returns an array of all HTML element objects contained by the current element. Items in this array are indexed (zero-based) in source code order. The collection transcends generations of nested elements such that document.all[ ] exposes every element in the entire document. See the all object for a list of this property value's own set of properties and methods.

As with all collections in Internet Explorer, you may use the traditional JavaScript array syntax (with square brackets around the index value) or IE's JScript alternative (with parentheses around the index value). If you are aiming for cross-browser deployment for collections that are available on both platforms, use the square brackets.

Unless you develop strictly for IE browsers, consider migrating to W3C DOM references via document.getElementById( ), implemented in IE 5 and later and Netscape 6.

Syntax

object.all(index).objectPropertyOrMethod
object.all[index].objectPropertyOrMethod
object.all("elementID").objectPropertyOrMethod
object.all["elementID"].objectPropertyOrMethod
object.all.elementID.objectPropertyOrMethod

Example

var inpVal = document.all.first_name.value;

Value

Array (collection) of element object references in HTML source code order.

Default

Current document's model.

 
attributes[ ]NN 6 IE 5 DOM 1

Read-only
Returns a named node map object, which resembles an array (collection) of attribute objects (W3C DOM type Attr), but also has some methods of its own to facilitate accessing a member of this array. IE's attributes array contains entries for all attributes of the element's internal DTD, plus any custom (expando) attributes explicitly set in the HTML source code in IE 6. Scripted changes to the element's attributes or their values are not reflected in this array.

For Netscape 6, the attributes array contains entries only for those attributes explicitly defined in the HTML source code for the element, including custom attributes. Scripted changes to attributes (additions or deletions) or their values are reflected in the attribute objects referenced by the attributes array.

In lieu of the named node map object methods, you may access individual attribute objects via standard JavaScript array syntax. By and large, however, it is far more convenient to access HTML element attribute values for scripting purposes either via their reflection as element object properties or via the element's getAttribute( ) and setAttribute( ) methods. For W3C DOM details (which are useful for XML document parsing), see the Attr and NamedNodeMap objects for properties and methods of these objects.

Example

var ldAttr = document.getElementById("myImg").attributes.getNamedItem("longdesc");

Value

Array (collection) of attribute object references in source code (Netscape 6), alphabetical-by-name (IE/Mac), or haphazard (IE/Windows) order.

Default

Current element's model.

 
baseURINN 6 IE n/a DOM 3

Read-only
This is a property of the Node object (proposed for DOM Level 3 Core) that reveals the base URI (full path to the source) from which the node was served. For example, each node copied from an XML document loaded into a document.implementation object reveals its baseURI, which is different from that of the HTML page performing the rendering.

Example

var nodeSrc = myXMLDoc.firstChild.childNodes[14].baseURI;

Value

Full URI string.

Default

Current node's internal value.

 
behaviorUrns[ ]NN n/a IE 5(Win) DOM n/a

Read-only
Provides an array of Uniform Resource Names for all external behaviors (.htc files) associated with the element through style sheet syntax. Perhaps for security reasons, the strings entries of this array are always empty.

Example

var htcCount = document.getElementById(elementID).behaviorUrns.length;

Value

Array of (empty) strings.

Default

Array of length 0.

 
canHaveChildrenNN n/a IE 5(Win) DOM n/a

Read-only
Specifies whether the current element may act as a container of other elements. The property value is based on IE for Windows built-in HTML DTDs, which define several elements (such as <br>) that may not have child nodes inserted into them.

Example

if (elementRef.canHaveChildren) {
    // statements to insert or append child elements
}

Value

Boolean value: true | false.

Default

Element-specific.

 
canHaveHTMLNN n/a IE 5.5(Win) DOM n/a

Read-only and Read/Write
Specifies whether the current element may act as a container of other content with HTML markup. The property reports identical information as canHaveChildren for regular HTML elements. For IE HTML Components (defined in an XML-based .htc file), the property is read/write, and directs the browser how to treat the custom element defined by the component.

Example

if (elementRef.canHaveHTML) {
    // statements to insert content with HTML markup
}

Value

Boolean value: true | false.

Default

Element-specific.

 
childNodes[ ]NN 6 IE 5 DOM 1

Read-only
This is a property of the W3C DOM Node object that consists of an array of references to all child nodes (a node list) in the next deeper level of the node hierarchy (whether part of the document node tree or free-standing document fragments not yet inserted into the document tree). To reach more deeply nested nodes, you must access the childNodes array of each child node of the current node. A vital property for walking through a node tree. See the NodeList object for the properties and methods of this kind of array.

Example

for (var i = 0; i < nodeRef.childNodes.length; i++) {
    if (nodeRef.childNodes[i].nodeType == document.ELEMENT_NODE) {
        // operate on an element
    }
}

Value

Array of node object references.

Default

Array of length zero.

 
children[ ]NN n/a IE 4 DOM n/a

Read-only
Returns an array of all first-level HTML element objects contained by the current element. This collection differs from the all[ ] collection in that it contains references only to the immediate children of the current element (whereas the all[ ] collection transcends generations). For example, document.body.children[ ] might contain a form, but no reference to form elements nested inside the form. Items in this array are indexed (zero-based) in source code order. In contrast to the childNodes[ ] array, the scope of this property is the element, not the node. See the children object.

Example

for (var i = 0; i < elementRef.children.length; i++) {
    if (elementRef.children[i].tagName == "FORM") {
        // operate on a form element
    }
}

Value

Array of element object references.

Default

Array of length zero.

 
citeNN 6 IE 6 DOM 1

Read/Write
This property (along with dateTime) is shared among all phrase element objects in IE 6, but in truth, it officially belongs only to the blockquote, quote, del, and ins element objects (see those element descriptions in
Chapter 8 for details on the corresponding attribute in the context of the element). Because the property is shared by four objects, Microsoft may have found it more convenient to implement the property internally for a larger related set of HTML element objects. Or it may be a mistake. Whatever the reason, do not expect this property in as many element objects as IE 6 exposes.

Value

Any valid URL to a document on the World Wide Web, including absolute or relative URLs.

Default

Empty string.

 
classNameNN 6 IE 4 DOM 1

Read/Write
This is an identifier generally used to associate an element with a style sheet rule defined for a class selector. You can alter the class association for an element by script. If the document includes an alternate class selector and style rule, adjusting the element's className property can provide a shortcut for adjusting many style properties at once.

Example

document.getElementById("elementID").className = "altHighlighted";

Value

Case-sensitive string. Multiple class names are space-delimited within the string.

Default

Empty string.

 
 
clientLeft, clientTopNN n/a IE 4 DOM n/a

Read-only
Broadly speaking, these provide the left and top coordinates of the element's content within the box that includes the element's padding, but with minor variations among various operating system versions of IE. Not available for all element types in IE for Macintosh. See the
Section 9.2 at the beginning of this chapter for details. More useful information for inline element positioning generally comes from the offsetLeft and offsetTop properties (including Netscape 6). For CSS-positioned elements (including changing an element's position), use style object properties, such as left and top, and (in IE only) pixelLeft and pixelTop.

Value

Integer pixel value.

Default

0

 
 
currentStyleNN n/a IE 5 DOM n/a

Read-only
Returns a style object with properties that reflect the effective values being applied to the element. This property takes into account style sheet rules defined in a style element, imported from external style sheet files, and inline style attributes. Because the style property reflects only inline style attributes, the currentStyle property is more valuable for reading initial values after a document loads. To modify style attributes, you can use the element's style object properties. For similar capabilities in Netscape 6, see the window.getComputedStyle( ) method.

Example

var currSize = document.getElementById("elementID").currentStyle.fontSize;

Value

style object reference.

Default

The effective style object.

 
dateTimeNN 6 IE 6 DOM 1

Read/Write
This property (along with cite) is shared among all phrase element objects in IE 6, but in truth, it officially belongs only to the blockquote, quote, del, and ins element objects (see those element descriptions in
Chapter 8 for details on the corresponding attribute in the context of the element). Because the property is shared by four objects, Microsoft may have found it more convenient to implement the property internally for a larger related set of HTML element objects. Or it may be a mistake. Whatever the reason, do not expect this property in as many element objects as IE 6 exposes.

Value

Date string.

Default

Empty string.

 
dirNN 6 IE 5 DOM 1

Read/Write
Indicates the direction of character rendering for the element's text whose characters are not governed by inherent directionality according to the Unicode standard and default browser language system. Character rendering is either left-to-right or right-to-left.

Value

ltr | rtl (case insensitive string).

Default

ltr

 
disabledNN 6 IE 4 DOM 1

Read/Write
Specifies whether the element is available for user interaction. When set to true, the element cannot receive focus or be modified by the user, and it typically appears grayed out on the page. This property is available for all HTML element objects in IE 5.5 for Windows and later. For IE 4 and IE 5, it applies only to form controls, while Netscape 6 and later recognize the property for form controls and the style element object. A disabled form control's name/value pair is not submitted with its form.

Example

document.getElementById("myButton").disabled = true;

Value

Boolean value: true | false.

Default

false

 
documentNN n/a IE 4 DOM n/a

Read-only
Returns a reference to the document object that contains the current element. Potentially helpful for functions that act on object references retrieved from event properties or passed as ID strings. The corresponding W3C DOM property is ownerDocument.

Example

var currDoc = document.getElementById("elementID").document;

Value

document object reference.

Default

The current document object.

 
filters[ ]NN n/a IE 4 DOM n/a

Returns an array of all filter objects contained by the current element. Applies only to the following element objects: bdo, body, button, div, fieldset, img, input, marquee, rt, ruby, span, table, td, textarea, and th. See the filter object for referencing syntax.

Value

Array of filter object references.

Default

Array of length zero.

 
firstChild, lastChildNN 6 IE 5 DOM 1

Read-only
Return a reference to the first or last child node (respectively) of the current element node. Most commonly, these child nodes are text nodes nested inside an element. For a simple element containing only one text node, both properties return a reference to the same text node. More complex constructions, such as tr elements, can have other element nodes (td elements) as their child nodes, but some browsers may turn source code carriage returns between elements into text nodes. Therefore, it's a good idea to validate the type of node returned by either property before acting on it.

Example

if (document.getElementById("elementID").firstChild.nodeType == 3) {
    // process as a text node
}

Value

Node object (including text node, HTML element node, etc.) reference.

Default

null

 
hideFocusNN n/a IE 5.5(Win) DOM n/a

Read/Write
Specifies whether the browser should display a dotted focus rectangle around the element if it has focus. The element continues to be able to receive focus if it is focusable by default or has the tabindex attribute set. When this property is set to true, there is no visual clue about the focus state.

Example

document.getElementById("elementID").hideFocus = true;

Value

Boolean value: true | false.

Default

false

 
idNN 6 IE 4 DOM 1

Read/Write
Specifies a unique identifier that distinguishes this element from all the rest in the document. The value of this property is most often used to assemble references to elements, but you can loop through all elements to see if there is a match of an id value. It is generally not a good idea to change this property's value for an element already in the document tree. But if a script creates a new element object (via the document.createElement( ) method, for instance), it can assign a unique identifier to this object's id property, and then add the element to the document tree.

Example

var headID = document.getElementsByTagName("head")[0].id;

Value

String.

Default

Empty string.

 
innerHTMLNN 6 IE 4 DOM n/a

Read/Write
Indicates the rendered text and HTML tags (i.e., all source code) between the start and end tags of the current element. A change to this property that includes HTML tags is rendered through the HTML parser, as if the new value were part of the original source code. You may change this property only after the document has fully loaded. Changes to the innerHTML property are not reflected in the source code when you view the source in the browser. This property is not supported in many objects in the Macintosh version of IE 4.

Netscape 6 supports this property as a convenience, even though the W3C DOM does not. Assigning a string lacking HTML tags to the innerHTML property has the same effect as assigning the string to the IE-only innerText property. In IE, you can read or write the source code that includes the element's tags via the outerHTML property.

Example

document.getElementById("elementID").innerHTML = "How <i>now</i> brown cow?";

Value

String that may or may not include HTML tags.

Default

Empty string.

 
innerTextNN n/a IE 4 DOM n/a

Read/Write
Indicates the rendered text (but not any tags) of the current element. If you want the rendered text as well as any nested HTML tags, see innerHTML. Any changes to this property are not rendered through the HTML parser, meaning that any HTML tags you include are treated as displayable text content only. You may change this property only after the document has fully loaded. Changes to the innerText property are not reflected in the source code when you view the source in the browser. This property is not supported in many objects in the Macintosh version of IE 4.

Example

document.getElementById("elementID").innerText = "How now brown cow?";

Value

String.

Default

Empty string.

 
isContentEditableNN n/a IE 5.5(Win) DOM n/a

Read-only
Specifies whether the current element has IE/Windows user editing engaged. Reveals the actual editing state as either explicitly set for the element or inherited from its ancestor tree.

Example

if (document.getElementById("elementID").isContentEditable) {
    // process the editable element
}

Value

Boolean value: true | false.

Default

false

 
isDisabledNN n/a IE 5.5(Win) DOM n/a

Read-only
Specifies whether the current element is disabled. Reveals the actual disabled state as either explicitly set for the element or inherited from its ancestor tree.

Example

if (document.getElementById("elementID").isDisabled) {
    // process the disabled element
}

Value

Boolean value: true | false.

Default

false

 
isMultiLineNN n/a IE 5.5(Win) DOM n/a

Read-only
Specifies whether the current element allows content to extend across multiple lines. Most text containers allow multiple lines, but other kinds of elements, such as a text input element are restricted to single line rendering.

Example

if (document.getElementById("elementID").isMultiLine) {
    // process the element as a potential multiple-line element
}

Value

Boolean value: true | false.

Default

Element default.

 
isTextEditNN n/a IE 4 DOM n/a

Read-only
Specifies whether the element can be used to create an IE/Windows TextRange object (via the createTextRange( ) method). Only body, button, text type input, and textarea elements are permitted to have text ranges created for their content.

Example

if (document.getElementById("elementID").isTextEdit) {
    var rng = document.getElementById("elementID").createTextRange( );
}

Value

Boolean value: true | false.

Default

Element default.

 
langNN 6 IE 4 DOM 1

Read/Write
Indicates the written language being used for the element's attribute and property values. Other applications and search engines might use this information to aid selection of spellchecking dictionaries and creating indices.

Example

document.getElementById("elementID").lang = "de";

Value

Case-insensitive language code.

Default

Browser default.

 
languageNN n/a IE 4 DOM n/a

Read/Write
Indicates the scripting language for script statements defined in the element.

Example

document.getElementById("elementID").language = "vbscript";

Value

Case-insensitive scripting language name as string: javascript | jscript | vbs | vbscript.

Default

jscript

 
lastChild

See firstChild.

 
localName, namespaceURI, prefixNN 6 IE n/a DOM 2

Read-only
These three properties apply primarily to XML document elements with tags that are defined with the help of XML namespaces. A simplified example of such a document follows:

<?xml version="1.0" encoding="ISO-8859-1"?>
<results xmlns:libBook="http://catalog.umv.edu/schema">
<libBook:title libBook:rareBooks="true">De Principia</libBook:title>
</results>

The properties reveal details about the element's naming characteristics. A localName is the equivalent of the nodeName property of the element, that is, the tag name within the scope of the entire document, even if the tag name is reused by another element originating from another namespace. The prefix, however, links the element with a prefix name that is normally defined with an xmlns attribute of a container in the XML document. This helps your script identify the namespace to which the element is associated. A further binding is revealed through the namespaceURI property, which returns the URI string assigned to the xmlns attribute of a container element. Although all three properties belong to the Node object, their values are null (or, rather, should be null, but in Netscape 6 are empty strings) for node types other than element and attribute nodes.

Example

var allTitles = document.getElementsByTagName("title");
for (var i = 0; i < allTitles.length; i++) {
    if (allTitles[i].prefix == "libBook" &&
        allTitles[i].namespaceURI.indexOf("catalog.umv.edu") != -1) {
        // process title elements from the desired namespace here
    }
}

Value

Strings.

Default

For localName, the element's tag name. For others, an empty string.

 
namespaceURI

See localName.

 
nextSibling, previousSiblingNN 6 IE 5 DOM 1

Read-only
Return a reference to the next or previous node (respectively) in the document tree at the same nested level as the current node. If there is no node in the position indicated by the property name, the property returns null. For a lone text node inside an element node, both properties return null. Node sequence is determined intially by source code order, but script changes to the document tree are reflected in the nodes returned by these properties.

Example

var nextNode = document.getElementById("elementID").nextSibling;

Value

Node object (including text node, HTML element node, etc.) reference.

Default

null

 
nodeNameNN 6 IE 5 DOM 1

Read-only
Returns a string that identifies the name of the node as influenced by the node type. For element and attribute node types, the property returns the tag name and attribute name, respectively. For many other kinds of nodes, which have no inherent label associated with them, the nodeName property returns a fixed string indicating the node type, such as #text for a text node and #document for the root document node. For elements, the property returns the same string value as the element object's tagName property. Note that browsers through IE 6 and Netscape 7 return element tag strings in all uppercase, regardless of source code style or DOCTYPE specification.

Example

if (document.getElementById("elementID").nextSibling.nodeName == "#text") {
    // process as a text node
}

Value

Fixed string for #cdata-section, #document, #document-fragment, and #text nodes; variable string for attribute, element, and other node types.

Default

Node-specific.

 
 
nodeValueNN 6 IE 5 DOM 1

Read/Write
Although the nodeValue property belongs to every node type, it is particularly helpful for text nodes because the property provides read/write access to the actual rendered text content of a text node. This property provides the W3C DOM canonical access to reading and modifying the text node nested inside an element, assuming your script addresses the nodeValue property of, say, an element's firstChild node. The property returns null for element nodes, so do not think of it as a pure replacement for the innerText or innerHTML convenience properties. The property returns the value assigned to an attribute when used with an attribute node.

Example

document.getElementById("elementID").firstChild.nodeValue = "New Text!";

Value

String, although IE for Windows may return an attribute node's value as a Number data type if the value consists of a numeric value. You should always assign a string to this property.

Default

Empty string.

 
 
offsetLeft, offsetTopNN 6 IE 4 DOM n/a

Read-only
Broadly speaking, provide the left and top coordinates of the element's box, but with minor variations with respect to the coordinate system context (vis-à-vis the offsetParent element) influenced by various operating system versions of IE and compatibility modes controlled by the DOCTYPE declaration. Implemented in Netscape 6 as a convenience, even though not part of the W3C DOM. See the
Section 9.2 at the beginning of this chapter for details. For positioned elements, you should rely more on the element's style properties that control location in the document or browser viewing space.

Example

if (document.getElementById("elementID").offsetLeft <= 20 &&
document.getElementById("elementID").offsetTop <=40) {
    ...
}

Value

Integer pixel count.

Default

Element-specific.

 
 
 
outerTextNN n/a IE 4 DOM n/a

Read/Write
Indicates the rendered text (but not any tags) of the current element. If you want the rendered text as well as the element's HTML tags, see outerHTML. Any changes to this property are not rendered through the HTML parser, meaning that any HTML tags you include are treated as displayable text content only. You may change this property only after the document has fully loaded. Changes to the outerText property are not reflected in the source code when you view the source in the browser. This property is not supported in many objects in the Macintosh version of IE 4.

Example

document.getElementById("elementID").outerText = "UNESCO";

Value

String.

Default

Empty string.

 
ownerDocumentNN 6 IE 5(Mac)/6(Win) DOM 1

Read-only
Returns a reference to the document object that contains the current node. Potentially helpful for functions that act on object references retrieved from event properties or passed as ID strings. The corresponding IE property is document.

Example

var currDoc = document.getElementById("elementID").ownerDocument;

Value

document object reference.

Default

The current document object.

 
parentElementNN n/a IE 4 DOM n/a

Read-only
Returns a reference to the next outermost element in the HTML containment hierarchy. An element's HTML parent is not necessarily the same as the object returned by the offsetParent property. The parentElement concerns itself strictly with source code containment, while the offsetParent property looks to the next outermost element that is used as the coordinate system for measuring the location of the current element. For example, if the main document contains a p element with an em element nested inside, the em element has two parents. The p element is the returned parentElement value (due to the HTML source code containment), while the body element is the returned offsetParent value (due to coordinate space containment).

You can jump multiple parent levels by cascading parentElement properties, as in:

document.getElementById("elementID").parentElement.parentElement;

You can then use references to access a parent element's properties or methods.

The corresponding property for the W3C DOM is parentNode.

Example

document.getElementById("elementID").parentElement.style.fontSize = "14pt";

Value

Element object reference.

Default

Element-specific.

 
parentNodeNN 6 IE 5 DOM 1

Read-only
Returns a reference to the next outermost node (usually an element) that acts as a container to the current node in the document tree. The relationship between the current node and its parent is purely structural, and is not concerned with positioning context. A parent node is one that completely encases the current node—not to be confused with sibling nodes, which, at best, reside on just one side of the current node. You can use the same cascading tricks as shown for the IE parentElement property, but it is hazardous to completely equate results from the element-centric IE-only properties with results from the W3C DOM node-centric properties (even though recent IE versions support both views of the world).

Example

if (document.getElementById("elementID").parentNode.nodeType == 1) {
    document.getElementById("elementID").parentNode.style.fontSize = "14pt";
}

Value

Element object reference.

Default

Node-specific.

 
parentTextEditNN n/a IE 4 DOM n/a

Read-only
Returns a reference to the next highest element up the HTML containment hierarchy that is of a type that allows a TextRange object to be created with it. This property may have to reach through many levels to find a suitable object. This property always returns null in IE for the Macintosh (through Version 5.1) because of lack of support for text ranges.

Example

var rangeElement = document.getElementById("elementID").parentTextEdit;
var rng = rangeElement.createTextRange( );

Value

Element object reference.

Default

body object.

 
prefix

See localName.

 
previousSibling

See nextSibling.

 
readyStateNN n/a IE 4 DOM n/a

Read-only
Returns the current download status of the object's content. If a script (especially one initiated by a user event) can perform some actions while the document is still loading, but must avoid other actions until the entire page has loaded, this property provides intermediate information about the loading process. You should use its value in condition tests. The value of this property changes during loading as the loading state changes. Each change of the property value fires an onReadyStateChange event (the event does not bubble).

When introduced with IE 4, the property was available for only the document, embed, img, link, object, script, and style objects. IE 5 expanded coverage to all HTML element objects.

Example

if (document.readyState == "loading") {
    //statements for alternate handling while loading
}

Value

For all but the object element, one of the following values (as strings): uninitialized | loading | loaded | interactive | complete. Some elements may allow the user to interact with partial content, in which case the property may return interactive until all loading has completed. Not all element types return all values in sequence during the loading process. The object element returns numeric values for these five states. They range from 0 (uninitialized) to 4 (complete).

Default

None.

 
recordNumberNN n/a IE 4 DOM n/a

Read-only
Used with IE data binding, returns an integer representing the record within the data set that generated the element (i.e., an element whose content is filled via data binding). Values of this property can be used to extract a specific record from an Active Data Objects (ADO) record set (see recordset property). Although this property is defined for all IE element objects, the other properties related to data binding belong to a subset of elements.

Example

<script for="tableTemplate" event="onclick">
    myDataCollection.recordset.absoluteposition = this.recordNumber;
    ...
</script>

Value

Integer.

Default

null

 
runtimeStyleNN n/a IE 5 DOM n/a

Read/Write
Returns a style object whose individual style properties convey values only if they are explicitly set via the regular style sheet processes. Unlike the currentStyle object, system default style sheet properties are not reflected. You can set individual style properties of this runtimeStyle object, but doing so transcends (some might say violates) normal cascading precedence. Any property you assign by script overrides all other settings for that style property governing that element, including values assigned to the element tag's style attribute and style property. For example, if you assign the value red to an element's style.color property, and assign the value green to the same element's runtimeStyle.color property, the element's text appears in green, even though the more specific style.color property still preserves the red value. At that point the element's currentStyle.color property also returns green, because that is the effective style governing the element at that instant.

You can use the runtimeStyle object to assign multiple style properties by reassigning a CSS syntax rule to the runtimeStyle.cssText property. Assign an empty string to the cssText property to remove all in-line attribute values, allowing the regular style sheet cascade to control the element's effective style.

Example

document.getElementById("elementID").runtimeStyle.cssText = 
  "border: 5px blue solid";

Value

style object reference.

Default

The effective style object and its explicitly defined style attribute values.

 
scopeName, tagUrnNN n/a IE 5(Win) DOM n/a

Read-only
For custom elements employing XML namespaces, the scopeName property returns the identifier that associates the tag name with a namespace that is defined elsewhere in the document via the xmlns attribute. All plain HTML elements return a value of HTML for this property. The tagUrn property returns the URI specified for the namespace. The corresponding properties in the W3C DOM are prefix and namespaceURI.

Example

var allTitles = document.getElementsByTagName("title");
for (var i = 0; i < allTitles.length; i++) {
    if (allTitles[i].scopeName == "libBook" &&
        allTitles[i].tagUrn.indexOf("catalog.umv.edu") != -1) {
        // process title elements from the desired namespace here
    }
}

Value

Strings.

Default

HTML for scopeName; empty string for tagUrn.

 
scrollHeight, scrollWidthNN 7 IE 4 DOM n/a

Read-only
Originally implemented in IE 4 for elements that either scrolled or influenced an element's scroll (body, button, caption, div, fieldset, legend, marquee, and textarea), these properties return the pixel dimensions of an element, including elements that are larger than the viewable area in the browser window. This is in contrast to the clientHeight and clientWidth properties for scrollable elements, which return dimensions of only visible portions of the element. IE for the Macintosh, however, interprets the intent of the scroll- properties differently, returning the dimensions of the visible portion.

Starting in IE 5 for Windows, all HTML elements have these properties, and the values for nonscrolling elements are the same as the offsetHeight and offsetWidth properties. Netscape 7 implements these properties for all elements, returning the height and width of the element, whether or not it's in view. The important point is that for key elements, such as the body, the properties mean different things and can disrupt cross-platform operation.

Example

var midPoint = document.body.scrollHeight/2;

Value

Positive integer or zero.

Default

None.

 
 
sourceIndexNN n/a IE 4 DOM n/a

Read-only
Returns the zero-based index of the element among all elements in the document. Elements are numbered according to their source code order, with the first element given a sourceIndex of zero.

Example

var whichElement = document.getElementById("elementID").sourceIndex;

Value

Positive integer or zero.

Default

Element-specific.

 
styleNN 6 IE 4 DOM 2

Read/Write
Indicates the style object associated with the element, as set by values explicitly assigned to the element's style attribute in the tag. In W3C DOM object terminology, this object more specifically is called a CSSStyleDeclaration object. For most style sheet scripting purposes, however, you can treat the IE and Navigator style object as similar objects. This property is the gateway to reading and writing individual style sheet property settings for an element. To read the effective style sheet properties governing an element (including imported style sheet attributes), see the currentStyle property earlier in this chapter (for IE) and the window.getComputedStyle( ) method (for Netscape 6).

Example

document.getElementById("elementID").style.fontSize = "14pt";

Value

style object.

Default

None.

 
tabIndexNN 6 IE 4 DOM 1

Read/Write
This is a number that indicates the sequence of this element within the tabbing order of all focusable elements in the document. Tabbing order follows a strict set of rules. Elements that have values other than zero assigned to their tabIndex properties are first in line when a user starts tabbing in a page. Focus starts with the element with the lowest tabIndex value and proceeds in order to the highest value, regardless of physical location on the page or in the document. If two elements have the same tabIndex values, the element that comes earlier in the document receives focus first. Next come all elements that either don't support the tabIndex property or have the value set to zero. These elements receive focus in the order in which they appear in the document.

The W3C DOM and Netscape 6 limit the tabIndex property to the following element objects: a, area, button, input, object, select, textarea. To this list, IE 4 adds applet, body, div, embed, isindex, marquee, span, table, and td. IE 5 adds every other renderable element. A negative value in IE (only) removes an element from tabbing order entirely.

Links and anchors cannot be tabbed to with the Mac version of IE 4, so the tabIndex property for a element objects is ignored in that version.

Example

document.getElementById("link3").tabIndex = 6;

Value

Integer.

Default

0

 
tagNameNN 6 IE 4 DOM 1

Read-only
Returns the name of the tag of the current element. Tag names are always returned in all uppercase letters for purposes of string comparisons, regardless of source code style or DOCTYPE declaration.

Example

var theTag = document.getElementById("elementID").tagName;

Value

String.

Default

Element-specific.

 
tagUrn

See scopeName.

 
titleNN 6 IE 4 DOM 1

Read/Write
Provides an advisory description of the element. When the element is one that has a physical presence on the page, the browser renders the value of this property as a floating text label when the cursor rests atop the element for a moment. The size, font characteristics, and color of this label are not within control of scripting.

Example

document.getElementById("elementID").title = "Hot stuff!";

Value

String.

Default

Empty string.

 
uniqueIDNN n/a IE 5(Win) DOM n/a

Read-only
Returns an identifier string that is unique among all object identifiers on the page. Used primarily to assign an ID to newly created elements when you don't mind the browser using its own naming scheme to invent the name. Most commonly used as a property of the document object, but it is accessible through any existing element object reference. The identifier is perfectly valid for use as string a parameter to methods that require an element ID.

Example

var newElem = document.createElement("p");
newElem.id = document.uniqueID;

Value

String.

Default

Browser-generated.

 
addBehavior( )NN n/a IE 5(Win) DOM n/a

addBehavior("URL")

Attaches an internal or external IE behavior to the current element. After a script attaches the behavior, the element responds to events defined for the behavior (if any), and provides access to properties and methods associated with the behavior. An external behavior file must be served from the same domain (and protocol) as the current page. For more information on applying IE/Windows behaviors, visit http://msdn.microsoft.com/workshop/author/behaviors/overview.asp.

Returned Value

Integer serial number usable as a parameter for the removeBehavior( ) method.

Parameters

URL
For external behaviors, a relative or absolute URL to the .htc file on the server. For internal behaviors, a special format as described in the next item.

#default#behaviorName

where behaviorName is one of the following built-in behaviors: anchorClick | anim | clientCaps | download | homePage | httpFolder | mediaBar | saveFavorite | saveHistory | saveSnapshot | userData.

 
addEventListener( )NN 6 IE n/a DOM 2

addEventListener("eventType",
listenerFunction,
useCapture)

Binds an event handler function to the current node so that the function executes when an event of a particular type arrives at the node either as event target or during event propagation. Note that W3C DOM events propagate through text nodes, as well as element nodes. The node listens for the event type either during event capture or event bubbling propagation, depending upon the setting of the Boolean third parameter. You may invoke this method multiple times for the same node but with different parameter values to assign as many event handling behaviors as you like, but only one listener function may be invoked for the same event and propagation type. If the event listener is added on a temporary basis, it may be removed via the removeEventListener( ) method.

Returned Value

None.

Parameters

eventType
A string of one event type (without the "on" prefix) known to the browser's object model. The W3C DOM knows the following event types (and Netscape 6 implements most of them):

abort blur change
click DOMActivate DOMAttrModified
DOMCharacterDataModified DOMFocusIn DOMFocusOut
DOMNodeInserted DOMNodeInsertedIntoDocument DOMNodeRemoved
DOMNodeRemovedFromDocument DOMSubtreeModified error
focus load mousedown
mousemove mouseout mouseover
mouseup reset resize
scroll select submit
unload    
listenerFunction
A reference to the function to execute when the node hears the event type in the specified propagation mode. As this is a reference to a function object, do not surround the name in quotes, nor include the parentheses of the function. At execution time, the browser automatically passes the current event object as a parameter to the listener function.

useCapture
A Boolean value. If true, the node listens for the event type only while the event propagates toward the target node (in event capture node). If false, the node listens only when the event bubbles outward from the event target. If the current node is the target of the event, either Boolean value may be used.

 
appendChild( )NN 6 IE 5 DOM 1

appendChild(nodeObject)

Inserts a new node after the end of the last child node of the current node object. The current node object must be capable of containing child nodes, otherwise the method throws an exception. This method is the most common way to append a dynamically created element, text node, or document fragment to an existing element, such as a script might do when assembling a chunk of new content for a document. But if the node reference passed as a parameter with the appendChild( ) method points to an existing node in the document tree, that node is first removed from the tree, and then appended to the end of the list of child nodes in the current object. This provides a shortcut way to move a node from one location to the end of a container.

Appending one text node as a sibling to an existing text node does not join the two text nodes together. To combine all sibling text nodes into one large text node, invoke the parent's normalize( ) method.

Returned Value

Reference to the appended node.

Parameters

nodeObject
Reference to any node object of a type that makes sense to become a child of the current object. It may be from dynamically-generated content (e.g., text node, element, or document fragment) or a node from the existing document tree.

 
applyElement( )NN n/a IE 5(Win) DOM n/a

applyElement(elementObject[,
type])

Inserts a new element as either a child element of the current object or as the new parent of the current object, depending on the value of the second parameter. The default behavior is to wrap the current object with the new element. But you may also choose to insert the new element as a child element. In this case, if the current object is in the document tree (as opposed to simply floating in memory after being created with document.createElement( )) and already has child elements nested inside it, the newly applied element is inserted in such a way that the previous children become children of the inserted element (i.e., grandchildren of the current object). This wrapping behavior is unique among IE element insertion methods and can have significant impact on the document tree. Use with caution.

Returned Value

Reference to the newly added element object.

Parameters

elementObject
Reference to any dynamically-generated or existing element object from the document tree.

type
Optional string value: inside (the new element becomes the sole, first child of the current object); outside (the new element becomes the parent of the current object). The default is outside.

 
attachEvent( )NN n/a IE 5(Win) DOM n/a

attachEvent("eventName",
functionReference)

Binds an event handler function to an element object for a particular event type. Similar in operation to the W3C DOM addEventListener( ) method, the IE attachEvent( ) method is used primarily for IE behaviors. Binding events through element object event handler properties is a better cross-browser approach for regular HTML pages. If you bind an event handler through the attachEvent( ) method, you can disengage the binding via the detachEvent( ) method.

Returned Value

Boolean value true if the binding is successful.

Parameters

eventName
String version of the event name, including the "on" prefix. Applicable event types include any event from IE/Windows extensive list of shared event types shown later in this section. Although not case-sensitive, all-lowercase values are recommended.

functionReference
A reference to the function to execute when the element receives the event either as the event target or through event propagation. As this is a reference to a function object, do not surround the name in quotes, nor include the parentheses of the function. No parameters may be passed to the function.

 
blur( )NN 2 IE 3 DOM 1

Removes focus from the current object, at which time the object's onblur event fires. Note that the range of elements capable of focus and blur (both the event and method) is limited in all browsers except for more recent versions of IE (see the shared tabindex attribute in
Chapter 8). Most reliably for backward compatibility, apply the blur( ) method to blatantly focusable elements, such as text input and textarea elements. Assigning the attribute onfocus="this.blur( );" to a text input element, for instance, is a crude but effective backward-compatible way to largely disable a field for browsers that do not provide genuine element disabling.

Use blur( ) and focus( ) methods in moderation on the same page. You can inadvertently trigger endless loops of blurring and focusing if alert dialog boxes are involved along the way. Moreover, be aware that when you invoke the blur( ) method on one object, some other object (perhaps the window object) receives an onfocus event.

Returned Value

None.

Parameters

None.

 
clearAttributes( )NN n/a IE 5(Win) DOM n/a

Removes all attributes from the current element except for the id and name attributes (if specified). Any rendering characteristics influenced by the element's attributes that are removed also no longer apply to the element.

Returned Value

None.

Parameters

None.

 
click( )NN 2 IE 4 DOM 1

Simulates the click action of a user on the element. Fires an onclick event in Internet Explorer 4 and later and Navigator 4 and later. Note in browsers prior to IE 4 and Netscape 6, not all elements are capable of the click( ) method (or onclick event). Also, don't expect all elements that normally change their graphical state when clicked by the user to simulate the same state change during the scripted click. For example, some Macintosh browser versions fail to change the checked state of a checkbox when a script invokes a click( ) method on the checkbox. In this case, invoke the click( ) method only if an onclick event handler executes some code; but also set the checked property of the checkbox as desired.

Returned Value

None.

Parameters

None.

 
cloneNode( )NN 6 IE 5 DOM 1

cloneNode(deepBoolean)

Copies the current node to memory, and returns a reference to the node copy (which is not part of the document tree). Because the clone is a full-fledged node, you can perform additional node-related operations on the clone before inserting the node elsewhere in the document tree. Beware, however, that id attributes of cloned elements are the same as the original. Change the id properties of those elements in the fragment before reintroducing the clone into the document tree.

The Boolean parameter determines whether the clone is of only the current node or the current node and all nested nodes. Note that if you clone a simple element container and set the parameter to false, the text node inside the element does not become part of the cloned copy.

Returned Value

Reference to document fragment in memory.

Parameters

deepBoolean
Boolean value that controls whether the copy includes all nested nodes (true) or only the current node (false). Parameter is optional in IE, with a default value of false.

 
componentFromPoint( )NN n/a IE 5(Win) DOM n/a

componentFromPoint(x,
y)

Returns a string that denotes where the coordinate points are in the element. For elements that display scroll bars, the returned value reveals precisely which piece of the scroll bar is at the coordinate location. If you engage Microsoft's document editing mode, additional pieces, such as draggable size handlers, are also indicated in the returned value. For areas of elements not displaying scroll bars or edit handles, you can also determine whether the coordinate is inside or outside the element, which is handy for collision detection between event coordinates and the element.

The most common source for coordinate parameter values is the event object, especially the event.clientX and event.clientY properties. You can apply these values directly, as in:

var where = event.srcElement.componentFromPoint(event.clientX, event.clientY);

Returned Value

One of the string values in the following table.

Returned string values

Description

empty string

Inside the element content area

outside

Outside the element content area

handleBottom

Edit mode resize handle at bottom

handleBottomLeft

Edit mode resize handle at bottom left

handleBottomRight

Edit mode resize handle at bottom right

handleLeft

Edit mode resize handle at left

handleRight

Edit mode resize handle at right

handleTop

Edit mode resize handle at top

handleTopLeft

Edit mode resize handle at top left

handleTopRight

Edit mode resize handle at top right

scrollbarDown

Scroll bar down arrow

scrollbarHThumb

Scroll bar horizontal thumb control

scrollbarLeft

Scroll bar left arrow

scrollbarPageDown

Scroll bar page-down region

scrollbarPageLeft

Scroll bar page-left region

scrollbarPageRight

Scroll bar page-right region

scrollbarPageUp

Scroll bar page-up region

scrollbarRight

Scroll bar right arrow

scrollbarUp

Scroll bar up arrow

scrollbarVThumb

Scroll bar vertical thumb control

Parameters

x
Positive or negative pixel count relative to the top of the screen.

y
Positive or negative pixel count relative to the left edge of the screen

 
contains( )NN n/a IE 4 DOM n/a

contains(elementReference)

Returns whether the current element contains the specified element.

Returned Value

Boolean value: true | false.

Parameters

elementReference
A fully formed element object reference (e.g., document.getElementById("myDIV")).

 
createControlRange( )NN n/a IE 5(Win) DOM n/a

Though implemented for many HTML element objects, this method should be used only with the document.body object. See the createControlRange( ) method of the body object for details.

 
detachEvent( )NN n/a IE 5(Win) DOM n/a

detachEvent("eventName",
functionReference)

Removes a previously attached event handler function binding from an element object for a particular event type. Similar in operation to the W3C DOM removeEventListener( ) method, the IE detachEvent( ) method is used primarily for IE behaviors. Binding events through element object event handler properties is a better cross-browser approach for regular HTML pages. The event property equivalent of the detachEvent( ) method is to assign null to the event property.

Returned Value

None.

Parameters

eventName
String version of the event name, including the "on" prefix. Applicable event types include any event from IE/Windows extensive list of shared event types shown later in this section. Although not case-sensitive, all-lowercase values are recommended.

functionReference
A reference to the function to execute when the element receives the event either as the event target or through event propagation. As this is a reference to a function object, do not surround the name in quotes, nor include the parentheses of the function.

 
dispatchEvent( )NN 6 IE n/a DOM 2

dispatchEvent(eventObjectReference)

Directs an event to fire on the current node. Used primarily when artificially creating an event by script, and then sending that event to a node for its event listener function to execute. The event object passed as a parameter must have an event type specified, but other properties of the event object (such as mouse event location or character key) may also be set when initializing the newly created event object. The following script fragment creates a generic mouse event, initializes the event as a mousedown type that bubbles and is cancelable, and sends the event to an element with the ID myNode:

var newEvt = document.createEvent("MouseEvents");
newEvt.initEvent("mousedown", true, true);
document.getElementById("myNode").dispatchEvent(newEvt);

See the W3C DOM Event, MouseEvent, and UIEvent objects for more details. The corresponding method for IE/Windows-only is fireEvent( ).

Returned Value

The W3C DOM specification indicates a Boolean value of true is returned if any event listener function that executes in response to the dispatchEvent( ) method also invokes the event.preventDefault( ) method. The method returns a value starting with Netscape 7.

Parameters

eventObjectReference
A reference to an event object. Most commonly this object is created and initialized by associated script statements.

 
doScroll( )NN n/a IE 5(Win) DOM n/a

doScroll(["scrollAction"])

Controls the scrolling of any element that displays scroll bars. Because most HTML elements can use style sheets to hardwire a height and width, while having the overflow style attribute to scroll, the doScroll( ) method is applicable to any element.

Rather than scrolling to a coordinate position, the doScroll( ) method simulates the click on a scroll bar control or region as directed by the parameter. Each invocation of the method triggers the onscroll event for the element. Invoke this method through a separate function that gets called from setTimeout( ) if the script sequence leading up to the scroll involves reflowing of the page (to let IE catch up with rendering).

Returned Value

None.

Parameters

scrollAction
The string name of one scroll bar region. If omitted, the default value applied is scrollbarDown. Most regions have interchangable long and short names, as shown in the following list:

scrollbarDown (or down)
scrollbarHThumb
scrollbarLeft (or left)
scrollbarPageDown (or pageDown)
scrollbarPageLeft (or pageLeft)
scrollbarPageRight (or pageRight)
scrollbarPageUp (or up)
scrollbarVThumb
 
dragDrop( )NN n/a IE 5.5(Win) DOM n/a

Triggers an ondragstart event for the current element, allowing a mouse event handler function to initiate script execution related to the start of dragging even before the user has actually begun to drag the element. Returns a Boolean true when the user releases the mouse button after the physical drag operation.

Returned Value

Boolean value: true | false.

Parameters

None.

 
fireEvent( )NN n/a IE 5.5(Win) DOM n/a

fireEvent("eventType"[,
eventObjectReference])

Directs an event to fire on the current element. Used primarily when artificially creating an event by script, and then sending that event to an element for its event handler function to execute. You can send a simple event of any type you wish. Such a generic event object has four properties automatically assigned to it:

cancelBubble = false; 
returnValue = true; 
srcElement = reference-to-current-element; 
type = event-type-specified-as-the-parameter; 

Or you may pass along an event object that has more details associated with it, such as the event location or character key. The following script fragment creates a generic event object, assigns some properties to it, and then sends the event (as an onclick event) to an element with the ID myElem:

var newEvt = document.createEventObject( );
newEvt.clientX = 50;
newEvt.clientY = 300;
newEvt.cancelBubble = true;
document.getElementById("myElem").fireEvent("onclick", newEvt);

See the IE event object for more details. The corresponding W3C DOM method is dispatchEvent( ).

Returned Value

Boolean value (true | false) signifying whether the event fired successfully.

Parameters

eventType
String value of the "on" version of the event name (e.g., "onmousedown").

eventObjectReference
An optional reference to an event object, usually one that is created anew.

 
focus( )NN 2 IE 3 DOM 1

Gives focus from the current object, at which time the object's onfocus event fires. Note that the range of elements capable of focus and blur (both the event and method) is limited in all browsers except for more recent versions of IE (see the shared tabindex attribute in
Chapter 8). Most reliably for backward compatibility, apply the focus( ) method to blatantly focusable elements, such as text input and textarea elements.

To give a text box focus and pre-select all the text in the box, use the sequence of focus( ) and select( ) methods on the element. If this sequence is to occur after windows change (such as after an alert dialog box closes), place the methods in a separate function, and invoke this function through the setTimeout( ) method following the alert( ) method for the dialog. This allows IE/Windows to sequence statement execution correctly.

Returned Value

None.

Parameters

None.

 
getAdjacentText( )NN n/a IE 5(Win) DOM n/a

getAdjacentText("where")

Returns the text (excluding HTML tags and attributes) in and around the current element in the direction indicated by one of four parameter values. The text segment extends only until the next element start or end tag. For example, consider the following HTML:

<p>This is a very <span id="mySpan">short</span> paragraph.</p>

Invoking the getAdjacentText( ) method on the span element with each of the four parameter values yields the values as shown here:

document.getElementById("mySpan").getAdjacentText("beforeBegin")
    // returns: "This is a very "
document.getElementById("mySpan").getAdjacentText("afterBegin")
    // returns: "short"
document.getElementById("mySpan").getAdjacentText("beforeEnd")
    // returns: "short"
document.getElementById("mySpan").getAdjacentText("afterEnd")
    // returns: " paragraph."

In this case the afterBegin and beforeEnd parameters return the same value because no elements are inside the span element. Invoking the method on the outer p element and the afterBegin parameter yields the text up to the start of the span element. In some document tree structures, this method returns the equivalent of W3C DOM's child node nodeValue properties.

Returned Value

String, which may contain leading or trailing spaces, depending on the structure of the text fragment inside the element.

Parameters

where
One of four constant string values (case-insensitive).

Constant

Description

beforeBegin

Text in front of current element's start tag back to preceding tag

afterBegin

Text after current element's start tag until next (start or end) tag

beforeEnd

Text in front of current element's end tag back to the preceding (start or end) tag

afterEnd

Text after current element's end tag until next (start or end) tag

 
getAttribute( )NN 6 IE 4 DOM 1

getAttribute(attributeName)

getAttribute(attributeName[,caseSensitivity])

Returns the value of the named attribute within the current element. If the attribute is reflected in the object model as a property, this method returns the same value as when reading the object's property. This is the preferred method for reading an element object attribute (i.e., property) value under the W3C DOM.

The attribute name you pass as a parameter is not case-sensitive in current browsers. IE, however, provides an optional second parameter that lets you force case-sensitivity in the attribute naming. This might encourage the reuse of the same attribute name but with different case letters—an ill-advised practice.

See the setAttribute( ) method for assigning values to attributes and creating new attribute/value pairs.

Returned Value

The W3C DOM and Netscape 6 maintain attribute values exclusively as string data types. IE, however may return an attribute value as a string, number, or Boolean.

Parameters

attributeName
The (case-insensitive by default) attribute name used in the HTML tag (not including the = symbol). While IE lets you switch between case-sensitivity settings, Netscape 6 does not demand case-sensitivity. But given the trend toward case-sensitive XHTML, it is best to get into the case-sensitive habit.

caseSensitivity
An optional integer value for IE only. Default value is 0 (not case-sensitive). If 1, the attribute in the HTML tag must match the case of the attributeName parameter exactly for its value to be returned.

 
getAttributeNode( )NN 6 IE 6 DOM 1

getAttributeNode(attributeName)

Returns a reference to the attribute node (Attr object) associated with the name. This type of node is the same kind that populates the array returned by an element's attributes property, but the getAttributeNode( ) method gives you direct access to the Attr node object by name. More helpful in XML documents, where an attribute can convey important data associated with the element. See the Attr object for details about that node type.

Returned Value

Reference to an Attr object.

Parameters

attributeName
The attribute name used in the tag (not including the = symbol). Neither IE nor Navigator demands case-sensitivity. But given the trend toward case-sensitive XHTML, it is best to get into the case-sensitive habit.

 
getAttributeNodeNS( )NN 6 IE n/a DOM 2

getAttributeNodeNS("namespaceURI",
"localName")

Returns a reference to the local-named Attr object with a matching namespace URI within the current element. This method works like getAttributeNS( ) but accommodates attributes for XML documents that are labeled according to a namespace specification.

Returned Value

Reference to an Attr object.

Parameters

namespaceURI
URI string matching a URI assigned to a label earlier in the document.

localName
The local name portion of the attribute.

 
getAttributeNS( )NN 6 IE n/a DOM 2

getAttributeNS("namespaceURI",
"localName")

Returns the value of the local-named attribute with a matching namespace URI within the current element. This method works like getAttribute( ) but accommodates attributes for XML documents that are labeled according to a namespace specification. The following simple XML document uses a namespace for an attribute of the libBook:title element:

<?xml version="1.0" encoding="ISO-8859-1"?>
<results xmlns:libBook="http://catalog.umv.edu/schema">
<libBook:title libBook:rareBooks="true">De Principia</libBook:title>
</results>

To retrieve the value of the libBook:rareBooks attribute, the method for the element would include the getAttributeNS( ) method call with the following parameters:

getAttributeNS("http://catalog.umv.edu/schema", "rareBooks")

Returned Value

The W3C DOM and Netscape 6 maintain attribute values exclusively as string data types.

Parameters

namespaceURI
URI string matching a URI assigned to a label earlier in the document.

localName
The local name portion of the attribute.

 
getBoundingClientRect( )NN n/a IE 5(Win) DOM n/a

Returns an IE TextRectangle object that describes the rectangular space occupied by the current element (including non-text elements, such as images). The rectangle (which has properties for top, right, bottom, and left coordinates) is as wide as the widest point of the content (e.g, the longest line of a word-wrapped paragraph) and as tall as the sum of all content. To obtain measures of rectangles for individual lines of a text element, see the getClientRects( ) method.

Returned Value

TextRectangle object.

Parameters

None.

 
getClientRects( )NN n/a IE 5(Win) DOM n/a

Returns an array of IE TextRectangle objects. Each entry of the array is a TextRectangle object for a single line of a multiline text element. Lines that have different font sizes or line heights will be encased by rectangles that are of different heights. See the TextRectangle object for its properties. To obtain one TextRectangle object for an entire element, use the getBoundingClientRect( ) method.

Returned Value

Array of TextRectangle objects.

Parameters

None.

 
getElementsByTagName( )NN 6 IE 5 DOM 1

getElementsByTagName("tagName")

Returns an array of all descendant elements of the current element whose tag name matches the parameter of the method. Elements in the array include children, grandchildren, and so on, and are in the source code order. The current element is not included in the array. If there are no matches, the array has a length of zero.

Netscape 6, IE 5/Macintosh, and IE 6/Windows let you specify the quoted asterisk wildcard character as a parameter to return an array of all descendant elements, regardless of tag name. Be aware, however, that different browsers may have slight differences in their document tree structures that result in wildcard parameter array lengths that don't match each other.

Returned Value

Array of zero or more element references.

Parameters

tagName
The (case-insensitive by default) tag name for desired elements. Or an asterisk that acts as a wildcard character to signify all tag names.

 
getElementsByTagNameNS( )NN 6 IE n/a DOM 2

getElementsByTagNameNS("namespaceURI",
"localName")

Returns an array of all descendant elements of the current element which have a local name that matches the second parameter of the method, and a namespace URI (assigned elsewhere in the document as a namespace declaration) that matches the first method parameter. Elements in the array include children, grandchildren, and so on, and are in the source code order. The current element is not included in the array. If there are no matches, the array has a length of zero. Applies primarily to XML documents.

Returned Value

Array of zero or more element references.

Parameters

namespaceURI
URI string matching a URI assigned to a label earlier in the document.

localName
The local name portion of the tag name.

 
getExpression( )NN n/a IE 5(Win) DOM n/a

getExpression("attributeName")

Returns a string version of the script expression used in a corresponding setExpression( ) method call on an attribute of the current element. The setExpression( ) method assigns a script expression used to calculate the value assigned to the attribute. The expression is calculated automatically in response to some event types and to the document.recalc( ) method. To read the current value of the attribute, you must use the eval( ) function on the string returned by the getExpression( ) method. See the setExpression( ) method later in this section.

Returned Value

String.

Parameters

attributeName
Name of the current element's attribute to which an expression is assigned by the setExpression( ) method.

 
hasAttribute( )NN 6 IE n/a DOM 1

hasAttribute("attributeName")

Returns a Boolean value true if the current element has an attribute whose name matches the method parameter.

Returned Value

Boolean value: true | false.

Parameters

attributeName
The case-sensitive attribute name to search for.

 
hasAttributeNS( )NN 6 IE n/a DOM 2

hasAttributeNS("namespaceURI",
"localName")

Returns a Boolean value true if the current element has an attribute with a local name that matches the method's second parameter, and a namespace URI (assigned elsewhere in the document as a namespace declaration) that matches the first method parameter.

Returned Value

Boolean value: true | false.

Parameters

namespaceURI
URI string matching a URI assigned to a label earlier in the document.

localName
The local name portion of the attribute name.

 
hasAttributes( )NN 6 IE n/a DOM 1

Returns a Boolean value true if the current element has any attributes explicitly assigned within the tag.

Returned Value

Boolean value: true | false.

Parameters

None.

 
hasChildNodes( )NN 6 IE 5 DOM 1

Returns a Boolean value true if the current node contains one or more child nodes.

Returned Value

Boolean value: true | false.

Parameters

None.

 
insertAdjacentElement( )NN n/a IE 5(Win) DOM n/a

insertAdjacentElement("where",
elementObjectReference)

Inserts an element object into the designated position relative to the current element. Typically, the element object about to be inserted is created separately (for example, via document.createElement( )) or it may be a reference to an object already in the document tree, and the method essentially moves the object to its new location with the help of the insertAdjacentElement( ) method.

The destination is governed by the first attribute, which consists of one of four values that determine where the insertion occurs, as follows.

Position

Insert new element

BeforeBegin

Before start tag of current element, as a previous sibling

AfterBegin

Immediately after current element's start tag, as a first child element

BeforeEnd

Immediately before current element's end tag, as a last child element

AfterEnd

After end tag of current element, as a next sibling

Although the effects on the document element tree are well-defined, the rendered result varies with the combination of inline and block elements you use as the current and inserted element objects. Inserting a block-level element (such as a div or p element) causes that element to render on the next line and at the left edge of the block-level positioning context (such as the body or td element). Applying the W3C DOM appendChild( ) method on elements is the equivalent of the insertAdjacentElement( ) method with the beforeEnd position parameter.

Returned Value

Reference to the inserted element object.

Parameters

where
String value of one of the following case-insensitive constants: BeforeBegin | AfterBegin | BeforeEnd | AfterEnd. The first and last locations are outside the HTML tags of the current element; the middle two locations are between the tags and element content.

elementObjectReference
Reference to any valid element object either existing in the document tree or created dynamically.

 
insertAdjacentHTML( )NN n/a IE 4 DOM n/a

insertAdjacentHTML("where",
HTMLText)

Inserts a text string into the designated position relative to the element's existing HTML. If HTML tags are part of the text to be inserted, the browser interprets the tags and performs the desired rendering. This method is not supported in many objects in the Macintosh version of IE 4.

Returned Value

None.

Parameters

where
String value of one of the following constants: BeforeBegin | AfterBegin | BeforeEnd | AfterEnd. The first and last locations are outside the HTML tags of the current element; the middle two locations are between the tags and element content.

HTMLText
String value of the text and/or HTML to be inserted in the desired location.

 
insertAdjacentText( )NN n/a IE 4 DOM n/a

insertAdjacentText("where",
text)

Inserts text into the designated position relative to the element's existing HTML. If HTML tags are part of the text to be inserted, the tags are shown literally on the page. This method is not supported in many objects in the Macintosh version of IE 4.

Returned Value

None.

Parameters

where
String value of one of the following constants: BeforeBegin | AfterBegin | BeforeEnd | AfterEnd. The first and last locations are outside the HTML tags of the current element; the middle two locations are between the tags and element content.

HTMLText
String value of the text to be inserted in the desired location.

 
insertBefore( )NN 6 IE 5 DOM 1

insertBefore(newChildNode,
referenceChildNodeOrNull)

Inserts a node as a child of the current node (usually the current node is an element) before one of the other child nodes of the current node. The new child can be a reference to an existing node in the document tree (in which case it is removed from its original position when this method is invoked). The child node may also be created anew as any valid DOM node type, including a document fragment (which may hold HTML tags) or Attr (the latter implemented for Netscape 6 and IE 6).

The second parameter allows you to specify a reference point among existing child nodes, in front of which the new child node is inserted. Alternatively, if you specify null as the second parameter (or omit the parameter in IE), the new node is inserted as the last child of the current node—the same result as the appendChild( ) method.

Returned Value

Reference to the inserted node object.

Parameters

newChildNode
Any valid node object that can be a child of a parent node.

referenceChildNodeOrNull
Any child node of the current node, or null.

 
isSupported( )NN 6 IE n/a DOM 2

isSupported("feature",
"version")

Returns a Boolean true if the current node supports (i.e., conforms to the required specifications of) a stated W3C DOM module and version. While the document.implementation object's hasFeature( ) method performs the same test, it does so on the entire browser application. The isSupported( ) method performs the test on an individual node, allowing you to verify feature support for the current node type. Parameter values for isSupported( ) are the same as for document.implementation.hasFeature( ).

It is up to the browser maker to validate that the DOM implemented in the browser conforms with each module before allowing the browser to return true for the module. That doesn't necessarily mean that the implementation is bug-free or consistent with other implementations. Caveat scriptor.

In theory, you could use this method to verify module support prior to accessing a property or invoking a method, as in the following fragment that assumes myElem is a reference to an element node:

if (myElem.isSupported("CSS", "2.0")) {
    myElem.style.color = "green";
}

In practice, object detection is a better solution because W3C DOM support reporting facilities are not widely implemented yet and are certainly not backward compatible.

Returned Value

Boolean value: true | false.

Parameters

feature
As of W3C DOM Level 2, permissible case-sensitive module name strings are: Core, XML, HTML, Views, StyleSheets, CSS, CSS2, Events, UIEvents, MouseEvents, MutationEvents, HTMLEvents, Range, Traversal.

version
String representation of the major and minor version of the DOM module cited in the first parameter. For the W3C DOM Level 2, the version is 2.0, even when the DOM module supports another W3C standard that has its own numbering system. Thus, the test for HTML DOM module support is for Version 2.0, even though HTML is at 4.x.

 
mergeAttributes( )NN n/a IE 5(Win) DOM n/a

mergeAttributes(modelElementReference[,
preserveIDs])

Copies attribute name/value pairs from the element specified as a parameter to the current element. This is helpful for copying a large set of attributes from an existing element to a newly created element. By default, the copy does not include the id or name attributes so that the two elements maintain separate identifiers for scripting and form purposes. Starting with IE 5.5/Windows, an optional Boolean second parameter, when set to false, duplicates id and name attributes as well.

Returned Value

None.

Parameters

modelElementReference
Reference to an existing element that serves as a model for attribute name/value pairs to be copied to the current element.

preserveIDs
An optional Boolean value. If false, the id and name attributes from the model element are not copied to the current element. The default for this parameter is true.

 
normalize( )NN 6 IE n/a DOM 2

Collapses all sibling text nodes of the current (element) node into a single text node. Invoking this method may be needed after inserting or removing child nodes of an element, if your node walking (traversal) scripts expect contiguous text to be contained by a single text node. The W3C DOM considers a document tree to be normal only if a text node has no other text nodes as siblings.

Returned Value

None.

Parameters

None.

 
releaseCapture( )NN n/a IE 5(Win) DOM n/a

Turns off mouse event capture mode that had been engaged earlier by the setCapture( ) method. In the IE event model, mouse event capture is designed for temporary use, such as processing mouse events while a custom context menu (implemented as a positioned div element) is activated. IE event capture is also released automatically by several user actions: giving focus to another window, frame, or the browser's Address box; scrolling a window; displaying a system dialog box; or displaying the true context menu.

Returned Value

None.

Parameters

None.

 
removeAttribute( )NN 6 IE 4 DOM 1

removeAttribute("attributeName")

removeAttribute("attributeName"[, caseSensitivity])

Removes the named attribute from the current element. An IE 4 requirement that limited attribute removal to attributes that had been added with the setAttribute( ) method is not applicable in IE 5 and later or Netscape 6. Removing an attribute does not change the source code when viewed through the browser, but does affect how the browser renders the element. The attribute value or node is also no longer available after removal.

Returned Value

In IE, Boolean true if successful; false if the attribute doesn't exist. No returned value in Netscape 6 (or W3C DOM specification).

Parameters

attributeName
The (case-insensitive by default) attribute name used in the HTML tag (not including the = symbol). While IE lets you switch between case-sensitivity settings, Netscape 6 does not demand case-sensitivity. But given the trend toward case-sensitive XHTML, it is best to get into the case-sensitive habit.

caseSensitivity
An optional integer value for IE only. Default value is 0 (not case-sensitive). If 1, the attribute in the HTML tag must match the case of the attributeName parameter exactly for its value to be returned.

 
removeAttributeNode( )NN 6 IE 6 DOM 1

removeAttributeNode(attrObjectReference)

Removes the attribute from the current element indicated by the parameter reference to an existing Attr node object. This provides an alternate way to remove an attribute from an element if the script has only a reference to the Attr node object, rather than its name. Removing an attribute node does not change the source code when viewed through the browser, but does affect how the browser renders the element. The attribute value or node is no longer available after removal.

Returned Value

Reference to the removed Attr object, which is no longer part of the document tree, but may now be inserted elsewhere in the document tree.

Parameters

attrObjectReference
A reference to an Attr node object associated with the current element.

 
removeAttributeNS( )NN 6 IE n/a DOM 2

removeAttributeNS("namespaceURI",
"localName")

Removes the local-named attribute with a matching namespace URI from the current element. This method works like removeAttribute( ) but accommodates attributes for XML documents that are labeled according to a namespace specification. The following simple XML document uses a namespace for an attribute of the libBook:title element:

<?xml version="1.0" encoding="ISO-8859-1"?>
<results xmlns:libBook="http://catalog.umv.edu/schema">
<libBook:title libBook:rareBooks="true">De Principia</libBook:title>
</results>

To remove the value of the libBook:rareBooks attribute, the method for the element would include the removeAttributeNS( ) method call with the following parameters:

removeAttributeNS("http://catalog.umv.edu/schema", "rareBooks")

Returned Value

None.

Parameters

namespaceURI
URI string matching a URI assigned to a label earlier in the document.

localName
The local name portion of the attribute.

 
removeBehavior( )NN n/a IE 5(Win) DOM n/a

removeBehavior(behaviorID)

Disconnects the association between the current element and a behavior that had been made earlier via the addBehavior( ) method. The parameter is the value that had been returned by the addBehavior( ) method, which you must preserve as a variable between invocation of the two methods.

Returned Value

Boolean value true if the removal is successful; otherwise false.

Parameters

behaviorID
Integer serial number initially generated by the addBehavior( ) method for the current element and behavior type.

 
removeChild( )NN 6 IE 5 DOM 1

removeChild(childNodeReference)

Removes a child node from the current element. The parameter must be a reference to an existing child node nested inside the current element. Once removed, the child node is no longer part of the document tree, but is still preserved in memory. The method returns a reference to the removed node so that you may modify it and place it elsewhere in the document tree. Note that you can command one node to remove one of its children, but you cannot command a node to remove itself (but see removeNode( ) for IE).

Returned Value

A reference to the removed node.

Parameters

childNodeReference
Reference to an existing child node.

 
removeEventListener( )NN 6 IE n/a DOM 2

removeEventListener("eventType",
listenerFunction,
useCapture)

Cuts a previously established event binding between an event handler function and the current node. This method assumes that an event listener was added to the node at some prior time. To assure removal of the desired event listener, use the identical three parameters for removeEventListener( ) that you used for addEventListener( ). You may invoke this method multiple times for the same node but with different parameter values so as not to disturb other event listeners assigned to the same node. Invoke this method only if user interaction with the node improves with the particular event handling turned off.

Returned Value

None.

Parameters

eventType
A string of one event type (without the "on" prefix) known to the browser's object model. The W3C DOM knows the following event types (and Netscape 6 implements most of them):

abort blur change
click DOMActivate DOMAttrModified
DOMCharacterDataModified DOMFocusIn DOMFocusOut
DOMNodeInserted DOMNodeInsertedIntoDocument DOMNodeRemoved
DOMNodeRemovedFromDocument DOMSubtreeModified error
focus load mousedown
mousemove mouseout mouseover
mouseup reset resize
scroll select submit
unload    
listenerFunction
A reference to the function to execute when the node hears the event type in the specified propagation mode. As this is a reference to a function object, do not surround the name in quotes, nor include the parentheses of the function. At execution time, the browser automatically passes the current event object as a parameter to the listener function.

useCapture
A Boolean value. If true, the node listens for the event type only while the event propagates toward the target node (in event capture node). If false, the node listens only when the event bubbles outward from the event target. If the current node is the target of the event, either Boolean value may be used.

 
removeExpression( )NN n/a IE 5(Win) DOM n/a

removeExpression("attributeName")

Disengages an expression that had been assigned previously to an element's attribute (assigned via the setExpression( ) method). Invoking the removeExpression( ) method turns off the automatic expression re-evaluation that might alter the attribute value in response to user activity (or explicit recalculation via the document.recalc( ) method). But the value assigned to the attribute as a result of the most recent calculation remains in effect, even after the expression is removed.

Returned Value

Boolean true if the removal is successful; otherwise false.

Parameters

attributeName
Name of the current element's attribute to which an expression had been assigned by the setExpression( ) method.

 
removeNode( )NN n/a IE 5(Win) DOM n/a

removeNode([childrenFlag])

Removes the current node from the document tree. The method returns a reference to the removed node so that you may modify it and place it elsewhere in the document tree. By default, the method removes only the current node and none of its child nodes. Removing a container node without its children can wreak havoc with the document tree, especially for complex elements, such as tables.

Returned Value

A reference to the removed node.

Parameters

childrenFlag
Optional Boolean value: false (default) removes only the current node; true removes current node and all nested child nodes.

 
 
replaceChild( )NN 6 IE 5 DOM 1

replaceChild(newChildNodeReference,
oldChildNodeReference)

Replaces one child node of the current node with a new child node. Typically, this is used with element nodes, but Netscape 6 and IE 6 also allow usage with Attr node objects. Parameters point to the incoming and outgoing child nodes, respectively. The new child node may be created anew or may be a reference to a node that exists elsewhere in the document tree. In the latter case, invoking the replaceChild( ) method removes the node from its original location in the document tree, and puts it into the child node position of the node referenced by the second parameter. The method returns a reference to the removed node so that you may modify it and place it elsewhere in the document tree. Note that you can command one node to replace one of its children, but you cannot command a node to replace itself (but see replaceNode( ) and swapNode( ) for IE).

Returned Value

A reference to the removed node.

Parameters

newChildNodeReference
Reference to a node that will replace an existing node.

oldChildNodeReference
Reference to an existing child node that is to be replace.

 
replaceNode( )NN n/a IE 5(Win) DOM n/a

replaceNode(newNodeObjectReference)

Replaces the current node with a new node. The new node may be created anew (e.g., a text node or element) or may be a reference to a node that exists elsewhere in the document tree. In the latter case, invoking the replaceNode( ) method removes the node from its original location in the document tree, and puts it into the current node's.

Returned Value

Reference to the removed node.

Parameters

newNodeObjectReference
Reference to the node object that will replace the current node.

 
scrollIntoView( )NN 7 IE 4 DOM n/a

scrollIntoView([showAtTop])

Scrolls the content holding the current element so that the element is brought into view. The default behavior is to display the element so that its top is at the top of the scroll space. But you may also align the element at the bottom of the scroll space, if you prefer.

Returned Value

None.

Parameters

showAtTop
An optional Boolean value. If true (the default), the top of the content is positioned at the top of the scroll space; if false, the bottom of the content is positioned at the bottom of the scroll space.

 
setActive( )NN n/a IE 5.5(Win) DOM n/a

Makes the current element the active element without scrolling the page to bring the active element into view. Nor does the method change focus between windows or frames if the method is invoked across window object boundaries. The element, however, receives an onfocus event when the method is invoked.

Returned Value

None.

Parameters

None.

 
setAttribute( )NN 6 IE 4 DOM 1

setAttribute("attributeName", value)
setAttribute("attributeName", value[, caseSensitivity])

Sets the value of the named attribute within the current element. If the attribute is reflected in the object model as a property, this method acts the same as assigning a value to the object's property. Even so, the W3C DOM declares the setAttribute( ) method as the preferred way to adjust an attribute value (and the getAttribute( ) method for reading the value).

If the attribute does not yet exist in the element, the setAttribute( ) method adds the attribute as a name/value pair to the element (except in IE 4 through 5.5, the newly added attribute is not reported as part of the element's attributes collection).

IE treats the attribute names more as object property names. Therefore, when a discrepancy exists between the attribute and corresponding property names (e.g., class versus className), IE requires the property name version. To assign a new value to the class attribute of an element for both IE and Navigator, you should branch the code to invoke the method only once per browser to avoid adding an unused className attribute to the Navigator element. For purposes of object detection, a browser that supports the W3C DOM approach returns a string value type for the element's getAttribute("class") method.

Values you assign to an attribute must be all strings for Netscape 6 (the W3C DOM specification). IE allows other data types (such as Number and Boolean), but if you assign, say, a numeric value in string form, the data type gets converted so that getAttribute( ) returns the value in IE's preferred data type. In Netscape 6, all attribute values are strings.

Attribute names in Netscape 6 are not case-sensitive, but you should get in the habit of using all lowercase attribute names (in the direction of XHTML). IE is case-sensitive about attribute names for this method by default. An optional third parameter lets you control whether the attribute name should be treated in a case-sensitive manner. Avoid playing case-sensitivity tricks with attribute names (two different attributes with the same spelling but different case characteristics). If you use all lowercase attribute names for all your code, you can omit the third IE parameter while staying W3C DOM compliant.

Returned Value

None.

Parameters

attributeName
The attribute name used in the HTML tag (except as noted above for IE).

value
For Netscape 6, the attribute value as a string data type. For IE, the attribute value as a string, number, or Boolean, as dictated by the attribute's data type. Strings are safe for all values, although IE internally converts the data types as necessary.

caseSensitivity
An optional integer value for IE only. If 1 (the default), the attribute in the HTML tag must match the case of the attributeName parameter exactly for its value to be set (allowing for multiple attribute names with the same spelling but different cases to coexist). If 0, the attributeName parameter aligns itself with the first attribute with the same name, regardless of case.

 
setAttributeNode( )NN 6 IE 6 DOM 1

setAttributeNode(attrObjectReference)

Inserts or replaces an attribute in the current element. The parameter is a reference to an Attr node object that is either created anew or references from another element in the document tree. When the setAttributeNode( ) method is invoked, the browser first looks for a match between the new attribute's name and existing attribute names. If there is a match, the new attribute replaces the original one; otherwise, the new attribute is added to the attributes of the element. Adding an attribute node does not change the source code when viewed through the browser, but may affect how the browser renders the element if the attribute affects the visual representation of the element. The value of the new attribute may be retrieved via the getAttribute( ) method.

Returned Value

Reference to a replaced Attr object (which is no longer part of the document tree) or null for an insertion.

Parameters

attrObjectReference
A reference to an Attr node object created through document.createAttribute( ) or an Attr node from another element in the document tree.

 
setAttributeNodeNS( )NN 6 IE n/a DOM 2

setAttributeNodeNS(attrObjectReference)

Inserts or replaces an attribute in the current element. The parameter is a reference to an Attr node object that is either created anew or references from another element in the document tree. When the setAttributeNodeNS( ) method is invoked, the browser first looks for a match between the new attribute's pairing of local name and namespace URI and existing attribute local names and namespace URIs. If there is a match, the new attribute replaces the original one; otherwise, the new attribute is added to the attributes of the element. Adding an attribute node does not change the source code when viewed through the browser, but may affect how the browser renders the element if the attribute affects the visual representation of the element. The value of the new attribute may be retrieved via the getAttributeNS( ) method.

Returned Value

Reference to a replaced Attr object (which is no longer part of the document tree) or null for an insertion.

Parameters

attrObjectReference
A reference to an Attr node object created through document.createAttributeNS( ) or an Attr node from another element in the document tree.

 
setAttributeNS( )NN 6 IE n/a DOM 2

setAttributeNS("namespaceURI",
"qualifiedName",
"value")

Inserts or replaces an attribute in the current element. If a match exists among the element's attributes for both the namespace URI and the qualified name passed as parameters, the new value is assigned to the existing attribute. If there is no match, the attribute is added to the element.

Returned Value

None.

Parameters

namespaceURI
URI string matching a URI assigned to a label earlier in the document.

qualifiedName
The full name for the attribute, consisting of the local name prefix (if any), a colon, and the local name.

value
The string value for the attribute.

 
setCapture( )NN n/a IE 5(Win) DOM n/a

setCapture([containerFlag])

Initiates IE capture mode for all click-related mouse events (onclick, ondblclick, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup), sending all event processing for those events to the current element, regardless of the actual event target. Useful for mouse modality required while handling custom context menus or dragging. While capture is engaged, the event.srcElement property for each event holds a reference to the element that would normally receive the event, but only the capture-mode element's event handlers actually process the events. When your modal effect is no longer neeeded, disengage capture mode with the releaseCapture( ) method. IE event capture is also released automatically by several user actions: giving focus to another window, frame, or the browser's Address box; scrolling a window; displaying a system dialog box; or displaying the true context menu.

Starting with IE 5.5, an optional parameter provides more control over event propagation when a user triggers a mouse event atop an element whose parent has the capture mode set. The default behavior (parameter omitted or set to true) causes the parent container to intercept events, as you would expect. But if you set the parameter to false, you direct events to proceed intially to their event targets (descendant elements of the capture-mode element). Such events can then bubble upward as normal; all other mouse events proceed directly to the capture-mode element. For example, if you invoke the setCapture( ) method on an element that contains a form with clickable form controls, you will probably want to use the false parameter so that mouse actions (such as clicking in text boxes) reach their intended targets even while capture mode is on. Otherwise, descendant elements won't respond to mouse activity, and the form controls will act as if they were disabled.

Returned Value

None.

Parameters

containerFlag
Boolean true (default) to let current element (if a container) capture all mouse events, or false to let mouse events reach their intended targets before bubbling.

 
setExpression( )NN n/a IE 5(Win) DOM n/a

setExpression("propertyName",
"expression",
["scriptLanguage"])

Assigns a script expression to an element object's property as a way to calculate dynamically a value for the property. This method works with properties of element objects and their style objects if you like. The expression is re-evaluated automatically for most user-oriented events, or you may explicitly force re-evaluation at any time via the recalc( ) method.

Assigning an expression to an element attribute can take the place of some event handling, such as maintaining position relationships among elements when a user resizes the browser window. For example, to keep an element horizontally centered in the browser window, you could use one of the following techniques to apply an expression to the element's style.left property. The first example demonstrates the syntax (also for IE 5 for Windows or later) for assigning an expression as an inline attribute for the the element:

<div id="heading" style="position:absolute; left:expression(
  document.body.clientWidth/2-document.getElementById("heading").offsetWidth/2);

Alternatively, a function invoked at load time could include the following statement:

document.getElementById("heading").style.setExpression("left", 
 "document.body.clientWidth/2-document.getElementById('heading').offsetWidth/2;", 
 "JScript");

In both cases, the same expression calculates the coordinate position for the element's left edge relative to the current viewable width of the body element. Because this expression depends on a body element dimension property, the browser knows that it should re-evaluate any expression that might be impacted by a change in the body size caused by window resizing.

Be sure the resulting value of the expression you assign is the desired data type for the attribute you are setting. Isolate and run some initial tests on the expression before assigning it to the setExpression( ) method. Otherwise debugging will be more difficult.

If you want an expression to assign a value to an attribute and force that value to stick, use the removeExpression( ) method to prevent any further re-evaluation of the attribute value.

Returned Value

None.

Parameters

propertyName
The name of the attribute being controlled by the expression, but in case-sensitive property name form (e.g., use the className property name instead of the corresponding class attribute name).

expression
A string that contains the script expression to be evaluated. The expression must evaluate to a value suitable for the property named in the first parameter, so multiple, semicolon-delimited statements are not allowed. References to other elements should be complete references. Early implementations may balk at references that include arrays.

scriptLanguage
One of three constant strings: JScript | JavaScript | VBScript. The default is JScript.

 
swapNode( )NN n/a IE 5(Win) DOM n/a

swapNode(otherNodeObject)

Exchanges the current node (in the document tree) with a different node passed as a parameter. The other node object can be created anew, or it can be a reference to a node elsewhere in the document tree. In the latter case, the result is the same as a bi-directional exchange, where the two nodes essentially change places. If the two nodes are of different node types or element display types (e.g., an inline versus a block-level element), the rendering of the document may be affected significantly.

Returned Value

Reference to the node from which the method is invoked (i.e., the current node).

Parameters

otherNodeObject
Reference to any node object, usually another node in the document tree.



Library Navigation Links

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