9.5. Shared Object Properties, Methods, and EventsBoth 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.1. Properties
9.5.2. Methods
9.5.3. Event Handlers
Exampleif (myObject.nodeType == document.ELEMENT_NODE) { // process as an element here } ValueInteger corresponding to DOM node type as follows.
DefaultConstant values (above).
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. Exampledocument.links[3].accessKey = "n"; ValueSingle alphanumeric (and punctuation) keyboard character. DefaultEmpty string.
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. Syntaxobject.all(index).objectPropertyOrMethod object.all[index].objectPropertyOrMethod object.all("elementID").objectPropertyOrMethod object.all["elementID"].objectPropertyOrMethod object.all.elementID.objectPropertyOrMethod Examplevar inpVal = document.all.first_name.value; ValueArray (collection) of element object references in HTML source code order. DefaultCurrent document's model.
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. Examplevar ldAttr = document.getElementById("myImg").attributes.getNamedItem("longdesc"); ValueArray (collection) of attribute object references in source code (Netscape 6), alphabetical-by-name (IE/Mac), or haphazard (IE/Windows) order. DefaultCurrent element's model.
Examplevar nodeSrc = myXMLDoc.firstChild.childNodes[14].baseURI; ValueFull URI string. DefaultCurrent node's internal value.
Examplevar htcCount = document.getElementById(elementID).behaviorUrns.length; ValueArray of (empty) strings. DefaultArray of length 0.
Exampleif (elementRef.canHaveChildren) { // statements to insert or append child elements } ValueBoolean value: true | false. DefaultElement-specific.
Exampleif (elementRef.canHaveHTML) { // statements to insert content with HTML markup } ValueBoolean value: true | false. DefaultElement-specific.
Examplefor (var i = 0; i < nodeRef.childNodes.length; i++) { if (nodeRef.childNodes[i].nodeType == document.ELEMENT_NODE) { // operate on an element } } ValueArray of node object references. DefaultArray of length zero.
Examplefor (var i = 0; i < elementRef.children.length; i++) { if (elementRef.children[i].tagName == "FORM") { // operate on a form element } } ValueArray of element object references. DefaultArray of length zero.
ValueAny valid URL to a document on the World Wide Web, including absolute or relative URLs. DefaultEmpty string.
Exampledocument.getElementById("elementID").className = "altHighlighted"; ValueCase-sensitive string. Multiple class names are space-delimited within the string. DefaultEmpty string.
Examplevar midHeight = document.body.clientHeight/2; ValueInteger pixel value. Default0
ValueInteger pixel value. Default0
Exampledocument.getElementById("elementID").contentEditable = "true"; ValueString constant: false | inherit | true. Defaultinherit
Examplevar currSize = document.getElementById("elementID").currentStyle.fontSize; Valuestyle object reference. DefaultThe effective style object.
ValueDate string. DefaultEmpty string.
Valueltr | rtl (case insensitive string). Defaultltr
Exampledocument.getElementById("myButton").disabled = true; ValueBoolean value: true | false. Defaultfalse
Examplevar currDoc = document.getElementById("elementID").document; Valuedocument object reference. DefaultThe current document object.
ValueArray of filter object references. DefaultArray of length zero.
Exampleif (document.getElementById("elementID").firstChild.nodeType == 3) { // process as a text node } ValueNode object (including text node, HTML element node, etc.) reference. Defaultnull
Exampledocument.getElementById("elementID").hideFocus = true; ValueBoolean value: true | false. Defaultfalse
Examplevar headID = document.getElementsByTagName("head")[0].id; ValueString. DefaultEmpty string.
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. Exampledocument.getElementById("elementID").innerHTML = "How <i>now</i> brown cow?"; ValueString that may or may not include HTML tags. DefaultEmpty string.
Exampledocument.getElementById("elementID").innerText = "How now brown cow?"; ValueString. DefaultEmpty string.
Exampleif (document.getElementById("elementID").isContentEditable) { // process the editable element } ValueBoolean value: true | false. Defaultfalse
Exampleif (document.getElementById("elementID").isDisabled) { // process the disabled element } ValueBoolean value: true | false. Defaultfalse
Exampleif (document.getElementById("elementID").isMultiLine) { // process the element as a potential multiple-line element } ValueBoolean value: true | false. DefaultElement default.
Exampleif (document.getElementById("elementID").isTextEdit) { var rng = document.getElementById("elementID").createTextRange( ); } ValueBoolean value: true | false. DefaultElement default.
Exampledocument.getElementById("elementID").lang = "de"; ValueCase-insensitive language code. DefaultBrowser default.
Exampledocument.getElementById("elementID").language = "vbscript"; ValueCase-insensitive scripting language name as string: javascript | jscript | vbs | vbscript. Defaultjscript
<?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. Examplevar 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 } } ValueStrings. DefaultFor localName, the element's tag name. For others, an empty string.
Examplevar nextNode = document.getElementById("elementID").nextSibling; ValueNode object (including text node, HTML element node, etc.) reference. Defaultnull
Exampleif (document.getElementById("elementID").nextSibling.nodeName == "#text") { // process as a text node } ValueFixed string for #cdata-section, #document, #document-fragment, and #text nodes; variable string for attribute, element, and other node types. DefaultNode-specific.
Exampleif (document.getElementById("elementID").firstChild.nodeType == 1) { // process as an element } ValueInteger values according to the following table.
DefaultNode-specific.
Exampledocument.getElementById("elementID").firstChild.nodeValue = "New Text!"; ValueString, 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. DefaultEmpty string.
Examplevar midpoint = document.getElementById("elementID").offsetWidth/2; ValueInteger pixel count. DefaultElement-specific.
Exampleif (document.getElementById("elementID").offsetLeft <= 20 && document.getElementById("elementID").offsetTop <=40) { ... } ValueInteger pixel count. DefaultElement-specific.
Examplevar containerLeft = document.getElementById("elementID")offsetParent.offsetLeft; ValueObject reference. Defaultbody object.
Exampledocument.getElementById("elementID").outerHTML = "<acronym id="quotes">NI<i>M</i>BY</acronym>"; ValueString that may or may not include HTML tags. DefaultEmpty string.
Exampledocument.getElementById("elementID").outerText = "UNESCO"; ValueString. DefaultEmpty string.
Examplevar currDoc = document.getElementById("elementID").ownerDocument; Valuedocument object reference. DefaultThe current document object.
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. Exampledocument.getElementById("elementID").parentElement.style.fontSize = "14pt"; ValueElement object reference. DefaultElement-specific.
Exampleif (document.getElementById("elementID").parentNode.nodeType == 1) { document.getElementById("elementID").parentNode.style.fontSize = "14pt"; } ValueElement object reference. DefaultNode-specific.
Examplevar rangeElement = document.getElementById("elementID").parentTextEdit; var rng = rangeElement.createTextRange( ); ValueElement object reference. Defaultbody object.
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. Exampleif (document.readyState == "loading") { //statements for alternate handling while loading } ValueFor 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). DefaultNone.
Example<script for="tableTemplate" event="onclick"> myDataCollection.recordset.absoluteposition = this.recordNumber; ... </script> ValueInteger. Defaultnull
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. Exampledocument.getElementById("elementID").runtimeStyle.cssText = "border: 5px blue solid"; Valuestyle object reference. DefaultThe effective style object and its explicitly defined style attribute values.
Examplevar 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 } } ValueStrings. DefaultHTML for scopeName; empty string for tagUrn.
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. Examplevar midPoint = document.body.scrollHeight/2; ValuePositive integer or zero. DefaultNone.
Exampledocument.body.scrollTop = 40; ValuePositive integer or zero. Default0
Examplevar whichElement = document.getElementById("elementID").sourceIndex; ValuePositive integer or zero. DefaultElement-specific.
Exampledocument.getElementById("elementID").style.fontSize = "14pt"; Valuestyle object. DefaultNone.
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. Exampledocument.getElementById("link3").tabIndex = 6; ValueInteger. Default0
Examplevar theTag = document.getElementById("elementID").tagName; ValueString. DefaultElement-specific.
Exampledocument.getElementById("elementID").title = "Hot stuff!"; ValueString. DefaultEmpty string.
Examplevar newElem = document.createElement("p"); newElem.id = document.uniqueID; ValueString. DefaultBrowser-generated.
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 ValueInteger serial number usable as a parameter for the removeBehavior( ) method. Parameters
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 ValueNone. Parameters
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 ValueReference to the appended node. Parameters
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 ValueReference to the newly added element object. Parameters
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 ValueBoolean value true if the binding is successful. Parameters
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 ValueNone. ParametersNone.
Returned ValueNone. ParametersNone.
Returned ValueNone. ParametersNone.
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 ValueReference to document fragment in memory. Parameters
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 ValueOne of the string values in the following table.
Parameters
contains(elementReference) Returns whether the current element contains the specified element. Returned ValueBoolean value: true | false. Parameters
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 ValueNone. Parameters
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 ValueThe 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
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 ValueNone. Parameters
Returned ValueBoolean value: true | false. ParametersNone.
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 ValueBoolean value (true | false) signifying whether the event fired successfully. Parameters
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 ValueNone. ParametersNone.
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 ValueString, which may contain leading or trailing spaces, depending on the structure of the text fragment inside the element. Parameters
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 ValueThe 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
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 ValueReference to an Attr object. Parameters
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 ValueReference to an Attr object. Parameters
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 ValueThe W3C DOM and Netscape 6 maintain attribute values exclusively as string data types. Parameters
Returned ValueTextRectangle object. ParametersNone.
Returned ValueArray of TextRectangle objects. ParametersNone.
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 ValueArray of zero or more element references. Parameters
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 ValueArray of zero or more element references. Parameters
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 ValueString. Parameters
hasAttribute("attributeName") Returns a Boolean value true if the current element has an attribute whose name matches the method parameter. Returned ValueBoolean value: true | false. Parameters
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 ValueBoolean value: true | false. Parameters
Returned ValueBoolean value: true | false. ParametersNone.
Returned ValueBoolean value: true | false. ParametersNone.
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.
Returned ValueReference to the inserted element object. Parameters
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 ValueNone. Parameters
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 ValueNone. Parameters
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 ValueReference to the inserted node object. Parameters
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 ValueBoolean value: true | false. Parameters
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 ValueNone. Parameters
Returned ValueNone. ParametersNone.
Returned ValueNone. ParametersNone.
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 ValueIn IE, Boolean true if successful; false if the attribute doesn't exist. No returned value in Netscape 6 (or W3C DOM specification). Parameters
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 ValueReference 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
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 ValueNone. Parameters
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 ValueBoolean value true if the removal is successful; otherwise false. Parameters
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 ValueA reference to the removed node. Parameters
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 ValueNone. Parameters
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 ValueBoolean true if the removal is successful; otherwise false. Parameters
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 ValueA reference to the removed node. Parameters
replaceAdjacentText("where", "newText") Replaces a contiguous block of text that is adjacent to the current element with new text. This method operates only on rendered text characters, and not HTML tags. The text to be removed (and the spot where new text goes) is governed by the first attribute, which consists of one of four values that determine where the insertion occurs, as follows.
Returned ValueString of the removed text. Parameters
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 ValueA reference to the removed node. Parameters
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 ValueReference to the removed node. Parameters
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 ValueNone. Parameters
Returned ValueNone. ParametersNone.
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 ValueNone. Parameters
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 ValueReference to a replaced Attr object (which is no longer part of the document tree) or null for an insertion. Parameters
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 ValueReference to a replaced Attr object (which is no longer part of the document tree) or null for an insertion. Parameters
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 ValueNone. Parameters
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 ValueNone. Parameters
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 ValueNone. Parameters
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 ValueReference to the node from which the method is invoked (i.e., the current node). Parameters
Copyright © 2003 O'Reilly & Associates. All rights reserved. |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|