Tải bản đầy đủ (.pdf) (10 trang)

JavaScript Bible, Gold Edition part 33 pps

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (123.56 KB, 10 trang )

168
Part III ✦ Document Objects Reference
for inserting, removing, reading, or writing attribute name–value pairs within the
node map. To a script, the value of the
attributes property can behave the same
in both IE5 and the W3C DOM provided that scripts don’t have to dig too deeply
into the nature of each object model’s idea of what an attribute object is.
In IE5, an attribute object is a relatively simple object consisting of
nodeName,
nodeValue, and specified properties. In the W3C DOM, an attribute object is
something more substantial, primarily because it inherits all the properties of the
Node object. Table 5-9 compares the properties of an attribute object in NN6 and IE5.
Table 15-9 Attribute Object Properties in NN6 and IE5
NN6 IE5
attributes
childNodes
firstChild
lastChild
name
nextSibling
nodeName nodeName
nodeType
nodeValue nodeValue
ownerDocument
parentNode
previousSibling
specified specified
value
Admittedly, the three properties implemented in IE5 are the most important, but
the shortcut approach negates the object-oriented system of the W3C DOM.
All of this is a long way to explain the W3C DOM


getAttributeNode() method,
which returns a W3C DOM attribute object. The sole parameter of the method is a
case-insensitive string version of the attribute’s name. You can then use any of the
properties shown in Table 15-9 to get or set attribute values. Of course, HTML
attributes are generally exposed as properties of HTML elements, so it is usually
easier to read or write the object’s properties directly.
Example on the CD-ROM
On the
CD-ROM
elementObject.getAttributeNode()
169
Chapter 15 ✦ Generic HTML Element Objects
Related Items: attributes property; getAttribute(),
removeAttributeNode(), setAttributeNode() methods.
getBoundingClientRect()
Returns: TextRectangle object.
NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5
Compatibility ✓✓
IE5+ assigns to every content-holding element a rectangle that describes the
space that the element occupies on the page. This rectangle is called a bounding
rectangle, and it is expressed in the IE5/Windows object model as a
TextRectangle
object (even when the content is an image or some other kind of object). A
TextRectangle object has four properties (top, left, bottom, and right) that are
the pixel coordinates that define the rectangle. The
getBoundingClientRect()
method returns a TextRectangle object that describes the bounding rectangle of
the current object. You can access an individual measure of an object’s bounding
rectangle, as in the following example:
var parTop = document.all.myP.getBoundingClientRect().top

For elements that consist of text, such as paragraphs, the dimensions of individual
TextRectangles for each line of text in the element influence the dimensions of the
bounding rectangle. For example, if a paragraph contains two lines, and the second
line extends only halfway across the width of the first line, the width of the second
line’s
TextRectangle object is only as wide as the actual text in the second line. But
because the first line extends close to the right margin, the width of the encompass-
ing bounding rectangle is governed by that wider, first line
TextRectangle.
Therefore, an element’s bounding rectangle is as wide as its widest line and as tall as
the sum of the height of all
TextRectangle objects in the paragraph.
Another method,
getClientRects(), enables you to obtain a collection of line-
by-line
TextRectangle objects for an element. Neither method is implemented in
IE5/Mac.
Example (with Listing 15-27) on the CD-ROM
Related Items: getClientRects() method; TextRectangle object (Chapter 19).
getClientRects()
Returns: Array of TextRectangle objects.
On the
CD-ROM
elementObject.getClientRects()
170
Part III ✦ Document Objects Reference
NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5
Compatibility ✓✓
The getClientRects() method returns an array of all TextRectangle objects
that fall within the current object the moment the method is invoked. Each

TextRectangle object has its own top, left, bottom, and right coordinate prop-
erties. You can then, for example, loop through all objects in this array to calculate
the pixel width of each line. If you want to find out the aggregate height and/or max-
imum width of the entire collection, you can use the
getBoundingClientRect()
method as a shortcut. This method is not implemented in IE5/Mac.
Example on the CD-ROM
Related Items: getBoundingClientRect() method; TextRectangle object
(Chapter 19).
getElementsByTagName(“tagName”)
Returns: Array of element objects.
NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5
Compatibility ✓✓✓
The getElementsByTagName() method returns an array of all elements of the
current object whose tags match the tag name supplied as the sole parameter to the
method. The tag name parameter must be in the form of a string and is case-insensi-
tive. The group of elements returned in the array includes only those elements that
are within the containment scope of the current object. Therefore, if you have two
table objects in a document and you invoke the
getElementsByTagName(“td”)
method on one of them, the list of returned table cell elements is confined to those
cells within the current table object. The current element is not included in the
returned array.
The W3C DOM (but not implemented in IE5.x/Windows) accepts a wildcard char-
acter (
“*”) as a parameter to the getElementsByTagName() method. The resulting
array of elements is similar to what IE4+ returns via the
document.all collection.
See Chapter 14 for ideas on simulating
document.all in NN6 using this technique.

Internet Explorer provides additional alternate syntax for this method: the
tags() method of the all collection. This alternate syntax also works in IE4 (see
the
all property earlier in this chapter).
On the
CD-ROM
elementObject.getElementsByTagName()
171
Chapter 15 ✦ Generic HTML Element Objects
Example on the CD-ROM
Related Items: getElementById(), tags() methods.
getExpression(“attributeName”)
Returns: String.
NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5
Compatibility ✓✓
The getExpression() method (not implemented in IE5/Mac) returns the text of
the expression that was assigned to an element’s attribute via the
setExpression()
method. The returned value is not the value of the expression, but rather the expres-
sion itself. If you want to find out the current value of the expression (assuming that
the variables used are within the scope of your script), you can use the
eval() func-
tion on the call to
getExpression(). This action converts the string to a JavaScript
expression and returns the evaluated result.
One parameter, a string version of the attribute name, is required.
Example on the CD-ROM
Related Items: document.recalc(), removeExpression(), setExpression()
methods.
hasChildNodes()

Returns: Boolean.
NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5
Compatibility ✓✓✓
The hasChildNodes() method returns true if the current object has child
nodes nested within; it returns
false otherwise. A child node is not necessarily the
same as a child element, so the following two expressions return
true when the
current object has at least one child node:
document.getElementById(“myObject”).hasChildNodes()
document.getElementById(“myObject”).childNodes.length > 0
On the
CD-ROM
On the
CD-ROM
elementObject.hasChildNodes()
172
Part III ✦ Document Objects Reference
You cannot use the second expression interchangeably with the following state-
ment (which uses the IE-only
children property):
document.getElementById(“myObject”).children.length > 0
You generally use the hasChildNodes() method in a conditional expression to
make sure such nodes exist before performing operations on them:
if (document.getElementById(“myObject”).hasChildNodes() {
statements that apply to child nodes
}
Example on the CD-ROM
Related Items: childNodes property; appendChild(), removeChild(),
replaceChild() methods.

insertAdjacentElement(“location”,
elementObject)
Returns: Object.
NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5
Compatibility ✓✓
The insertAdjacentElement() method (not implemented in IE5/Mac) inserts
an element object (coming from a variety of sources) in a specific position relative
to the current object. Both parameters are required. The first must be one of four
possible case-insensitive locations for the insertion, shown in the following table:
Location Description
beforeBegin Before the current element’s start tag
afterBegin After the start tag, but before any nested content
beforeEnd Before the end tag, but after all other nested content
afterEnd After the end tag
These locations are relative to the current object. The element type of the cur-
rent object (a block-level or inline element) has great bearing on how the inserted
element is rendered. For example, suppose you create a B element (using
docu-
ment.createElement()
) and assign some inner text to it. You then use
insertAdjacentElement() in an effort to insert this B element before some text
in a P element. Because a P element is a block-level element, the location
On the
CD-ROM
elementObject.insertAdjacentElement()
173
Chapter 15 ✦ Generic HTML Element Objects
beforeBegin places the new B element before the start tag of the P element. This
means, however, that the bold text appears in a text line above the start of the P
element because a

<P> tag begins a new block at the left margin of its container
(unless instructed otherwise by style sheets). The resulting HTML looks like the
following:
<B>The new element.</B><P>The original paragraph element.</P>
To make the new B element a part of the P element — but in front of the existing
P element’s content — use the
afterBegin location. The resulting HTML looks like
the following:
<P><B>The new element.</B>The original paragraph element.</P>
To complete the demonstration of the four location types, the following is the
result of the
beforeEnd location:
<P>The original paragraph element. <B>The new element.</B></P>
and this is the result of the afterEnd location:
<P>The original paragraph element.</P><B>The new element.</B>
The object to be inserted is a reference to an element object. The object refer-
ence can come from any expression that evaluates to an element object or, more
likely, from the result of the
document.createElement() method. Bear in mind
that the object generated by
document.createElement() initially has no content,
and all attribute values are set to default values. Moreover, the object is passed to
insertAdjacentElement() by reference, which means that there is only one
instance of that object. If you attempt to insert that object in two places with two
statements, the object is moved from the first location to the second. If you need to
copy an existing object so that the original is not moved or otherwise disturbed by
this method, use the
cloneNode() method to specify the true parameter to cap-
ture all nested content of the node.
Do not use this method to insert new table elements into a table. Instead, use the

many table-specific insertion methods that better treat rows, columns, and cells of
a table (see Chapter 27). And if you wish to insert an element that surrounds the
current element or wraps all of the content of the current element, use the
applyElement() method.
Example on the CD-ROM
Related Items: document.createElement(), applyElement() methods.
insertAdjacentHTML(“location”, “HTMLtext”)
insertAdjacentText(“location”, “text”)
Returns: Nothing.
On the
CD-ROM
elementObject.insertAdjacentHTML()
174
Part III ✦ Document Objects Reference
NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5
Compatibility ✓✓ ✓
These two methods insert HTML or straight text at a location relative to the
current element. They are intended for use after a page loads, rather than inserting
content while the page loads (in which case you can use
document.write() wher-
ever you need evaluated content to appear on the page).
The first parameter must be one of four possible case-insensitive locations for
the insertion, shown in the following table:
Location Description
beforeBegin Before the current element’s start tag
afterBegin After the start tag, but before any nested content
beforeEnd Before the end tag, but after all other nested content
afterEnd After the end tag
These locations yield the same results as described in the
insertAdjacentElement() function discussed earlier.

Whether you use
insertAdjacentHTML() or insertAdjacentText() depends
on the nature of your content and what you want the browser to do with it. If the
content contains HTML tags that you want the browser to interpret and render as if
it were part of the page source code, then use the
insertAdjacentHTML() method.
All tags become objects in the document’s object model. But if you want only to
display some text (including HTML tags in their “raw” form), use
insertAdjacentText(). The rendering engine does not interpret any tags
included in the string passed as the second parameter. Instead, these tags are dis-
played as characters on the page. This distinction is identical to the one between
the
innerHTML and innerText properties.
The difference between
insertAdjacentHTML() and
insertAdjacentElement() is the nature of the content that you insert. The for-
mer enables you to accumulate the HTML as a string, while the latter requires the
creation of an element object. Also, the two methods in this section work with IE4+
(including Mac versions), whereas
insertAdjacentElement() requires the newer
object model of IE5 and later.
If the HTML you pass as the second parameter of
insertAdjacentHTML()
contains <SCRIPT> tags, you must set the DEFER attribute in the opening tag. This
prevents script statements from executing as you insert them.
For inserting new elements into an existing table, use the variety of table object
methods for managing rows, columns, and cells (see Chapter 27).
elementObject.insertAdjacentHTML()
175
Chapter 15 ✦ Generic HTML Element Objects

Example on the CD-ROM
Related Items: innerText, innerHTML, outerText, outerHTML properties;
insertAdjacentElement(), replaceAdjacentText() methods.
insertBefore(newChildNodeObject[,
referenceChildNode])
Returns: Node object.
NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5
Compatibility ✓✓✓
The insertBefore() method is the W3C DOM syntax for inserting a new child
node into an existing element. Node references for both parameters must be valid
Node objects (including those that document.createElement() generates).
The behavior of this method might seem counter-intuitive at times. If you include
the second parameter (a reference to an existing child node of the current ele-
ment), the new child node is inserted before that existing one. But if you omit the
second parameter (or its value is
null), the new child node is inserted as the last
child of the current element — in which case, the method acts the same as the
appendChild() method. The true power of this method is summoned when you
specify that second parameter; from the point of view of a parent element, you can
drop a new child into any spot among its existing children.
Bear in mind that the
insertBefore() method works from a parent element.
Internet Explorer provides additional methods, such as
insertAdjacentElement(), to operate from the perspective of what will become a
child element.
Example (with Listing 15-28) on the CD-ROM
Related Items: appendChild(), replaceChild(), removeChild(),
insertAdjacentElement() methods.
item(index | “index” [, subIndex])
Returns: Object.

NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5
Compatibility ✓✓✓✓
On the
CD-ROM
On the
CD-ROM
elementObjectCollection.item()
176
Part III ✦ Document Objects Reference
The item() method works with most objects that are themselves collections of
other objects. In the W3C DOM framework, these kinds of objects are known as
named node lists (for objects such as nodes and attributes) or HTML collections
(for objects such as elements of a form). While the W3C DOM defines the
item()
method, it does so with a single numeric parameter that is the index value of the
desired object within the collection. NN6 implements this version. If you know the
index number of the item, you can use JavaScript array syntax instead. The follow-
ing two statements return the same object reference:
document.getElementById(“myTable”).childNodes.item(2)
document.getElementById(“myTable”).childNodes[2]
And for IE’s all object, the index value for a given element is the same as the
element’s
sourceIndex property.
IE4+ extends the possibilities by also allowing a string of the ID of an object within
the collection. (Integer values are required for the
attributes, rules, and
TextRectangle objects, however.) Additionally, if the collection has more than one
object with the same ID (never a good idea except when necessary), a second
numeric parameter enables you to select which identically named group you want
(using zero-based index values within that subgroup). This obviously does not apply

to collections, such as attributes and rules, which have no ID associated with them.
The method returns a reference to the object specified by the parameters.
Example on the CD-ROM
Related Items: All object element properties that return collections (arrays) of
other objects.
mergeAttributes(“sourceObject”)
Returns: Nothing.
NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5
Compatibility ✓✓
The mergeAttributes() method (not implemented in IE5/Mac) is a convenient
way to propagate attributes in newly created elements without painstakingly adding
attributes one at a time. Once you have an object whose attributes can function as a
prototype for other elements, those attributes (except for the
ID attribute) can be
applied to a newly created element instantaneously.
Example (with Listing 15-29) on the CD-ROM
On the
CD-ROM
On the
CD-ROM
elementObject.mergeAttributes()
177
Chapter 15 ✦ Generic HTML Element Objects
Related Items: clearAttributes(), cloneNode(), removeAttributes()
methods.
normalize()
Returns: Nothing.
NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5
Compatibility ✓
In the course of appending, inserting, removing, and replacing child nodes of an

element, it is conceivable that two text nodes can end up adjacent to each other.
While this typically has no effect on the rendering of the content, some XML-centric
applications that rely heavily on the document node hierarchy to interpret content
properly may not like having two text nodes sitting next to each other. The “proper”
form of a node hierarchy is for a single text node to be bounded by other node
types. The
normalize() method sweeps through the child nodes of the current
node object and combines adjacent text nodes into a single text node. The effect
obviously impacts the number of child nodes of an element, but it also cleanses the
nested node hierarchy.
Example on the CD-ROM
Related Items: document.createTextNode(), appendChild(), insertBefore(),
removeChild(), replaceChild() methods.
releaseCapture()
setCapture(containerBoolean)
Returns: Nothing.
NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5
Compatibility ✓✓
You can instruct a single object on an IE5+/Windows page to capture all mouse
events (
onmousedown, onmouseup, onmousemove, onmouseout, onmouseover,
onclick, and ondblclick) via the IE-specific setCapture() method. This type of
event capture is somewhat similar to event capture mechanisms of NN4 and NN6
(which are quite different in and of themselves). However, the syntax is entirely
different, as is the overall approach to the code that handles events (see Chapter 29
on the
Event object).
On the
CD-ROM
elementObject.releaseCapture()

×