Figure 18-1: The basic document object model hierarchy window frame self top parent history document location text radio button select textarea checkbox reset option link form anchor pas
Trang 2The Document
and Body
Objects
User interaction is a vital aspect of client-side JavaScript
scripting, and most of the communication between
script and user takes place by way of the documentobject
and its components Understanding the scope of the
docu-mentobject within each of the object models you support is
key to implementing successful cross-browser applications
Review the documentobject’s place within the original
object hierarchy Figure 18-1 clearly shows that the document
object is a pivotal point for a large percentage of JavaScript
objects
Figure 18-1: The basic document object model hierarchy
window frame self top parent
history document location
text radio button select
textarea checkbox reset option
link form anchor
password submit
18
In This Chapter
Accessing arrays of objects contained by the documentobject
Writing new document content to
a window or frame Using the BODY element for IE window measurements
Trang 3340 Part III ✦ Document Objects Reference
In fact, the documentobject and all that it contains is so big that I have divided its discussion into many chapters, each focusing on related object groups This chapter looks at the documentobject and bodyobject (which have conceptual relationships), while each of the succeeding chapters in this part of the book details objects contained by the documentobject
I must stress at the outset that many newcomers to JavaScript have the expecta-tion that they can, on the fly, modify secexpecta-tions of a loaded page’s content with ease: replace some text here, change a table cell there However, understanding that these capabilities — an important part of what is called Dynamic HTML — are avail-able only in more recent browsers, specifically IE4+ and NN6+, is very important Not only do these browsers expose every HTML element to script languages, but they also automatically reflow the page when the size of content changes under script control Pages on all previous browsers are limited to a small set of modifi-able objects, such as images and form elements (NN4 also has a layer object that is useful for DHTML, but that object is unique to NN4 only.)
If your application requires compatibility with all scriptable browsers, you will
be limited to changing only a handful of other invisible properties after the page loads If these compatible pages need to modify their contents based on user input
or timed updates, consider designing your pages so that scripts write the contents; then let the scripts rewrite the entire page with your new settings
Document Object
Properties Methods Event Handlers
activeElement attachEvent()† onActivate†
alinkColor captureEvents() onBeforeCut†
all† clear() onBeforeDeactivate† anchors clearAttributes()† onBeforeEditFocus† applets close() onBeforePaste† attributes† createAttribute() onClick†
bgColor createElement() onContextMenu† body createEventObject() onControlSelect† charset createStyleSheet() onCut†
characterSet createTextNode() onDblClick†
childNodes† detachEvent()† onDrag†
cookie elementFromPoint() onDragEnd†
defaultCharset execCommand() onDragEnter†
designMode focus()† onDragLeave†
doctype getElementById() onDragOver†
document
Trang 4Properties Methods Event Handlers
documentElement getElementsByName() onDragStart†
domain getElementsByTagName()† onDrop†
embeds getSelection() onHelp†
expando handleEvent() onKeyDown†
fgColor hasFocus()† onKeyPress†
fileCreatedDate mergeAttributes()† onKeyUp†
fileModifiedDate open() onMouseDown†
fileSize queryCommandEnabled() onMouseMove†
firstChild† queryCommandIndterm() onMouseOut†
forms queryCommandState() onMouseOver†
frames queryCommandSupported() onMouseUp†
height queryCommandText() onPaste†
ids queryCommandValue() onPropertyChange†
images recalc() onReadyStateChange†
implementation releaseCapture()† onResizeEnd†
lastChild† releaseEvents() onResizeStart†
lastModified routeEvent() onSelectionChange
layers setActive()† onStop
linkColor write()
links writeln()
location
media
mimeType
namespaces
namespaceURI
nextSibling†
nodeName†
nodeType†
ownerDocument†
parentNode†
Continued
Trang 5342 Part III ✦ Document Objects Reference
Properties Methods Event Handlers
parentWindow plugins previousSibling†
protocol readyState†
referrer scripts security selection styleSheets tags
title uniqueID†
URL URLUnencoded VlinkColor width
†See Chapter 15.
Syntax
Accessing documentobject properties or methods:
[window.]document.property | method([parameters])
About this object
A documentobject encompasses the totality of what exists inside the content region of a browser window or window frame (excluding toolbars, status lines, and
so on) The document is a combination of the content and interface elements that make the Web page worth visiting In more recent browsers, which treat HTML ele-ments as nodes of a hierarchical tree, the documentobject is the root node — that from which all other nodes grow
Because the documentobject isn’t explicitly represented in an HTML document
by tags or any other notation, the original designers of JavaScript and object mod-els decided to make the documentobject the portal to many settings that were rep-resented in HTML as belonging to the BODY element That element’s tag contains attributes for document-wide attributes, such as background color (BGCOLOR) and link colors in various states (ALINK, LINK, and VLINK) The BODY element also
document
Trang 6served as an HTML container for forms, links, and anchors The documentobject,
therefore, assumed a majority of the role of the BODY element But even then, the
documentobject became the most convenient place to bind some properties that
extend beyond the BODY element, such as the TITLE element and the URL of the
link that referred the user to the page When viewed within the context of the HTML
source code, the original documentobject is somewhat schizophrenic Even so, the
documentobject has worked well as the basis for references to original object
model objects, such as forms, images, and applets
This, of course, was before every HTML element, including the BODY element,
was exposed as an object via modern object models Amazingly, even with the IE4+
object model and W3C DOM — both of which treat the BODY element as an object
separate from the documentobject — script compatibility with the original object
model is quite easily accomplished The documentobject has assumed a new
schizophrenia, splitting its personality between the original object model and the
one that places the documentobject at the root of the hierarchy, quite separate
from the BODY element object it contains The object knows which “face” to put on
based on the rest of the script syntax that follows it This means that quite often
there are multiple ways to achieve the same reference For example, you can use
the following statement in all scriptable browsers to get the number of form objects
in a document:
document.forms.length
In IE4+, you can also use
document.tags[“FORM”].length
And in the W3C DOM as implemented in IE5+ and NN6, you can use
document.getElementsByTagName(“FORM”).length
The more modern versions provide generic ways of accessing elements (the
tagsarray in IE4+ and the getElementsByTagName()method in the W3C DOM) to
meet the requirements of object models that expose every HTML (and XML)
ele-ment as an object
Promoting the BODY element to the ranks of exposed objects presented its own
challenges to the new object model designers The BODY element is the true
“owner” of some properties that the original documentobject had to take on by
default Most properties that had belonged to the original documentobject
were renamed in their transfer to the BODY element For example, the original
document.alinkColorproperty is the body.aLinkproperty in the new model
But the bgColorproperty has not been renamed For the sake of code
compatibil-ity, the current versions of browsers recognize both properties, even though the
W3C DOM (in an effort to push the development world ahead) has removed the old
versions as properties of what it conceives as the documentobject
As confusing as all of this may sound on the surface, understanding when to
refer to the original documentobject and when to use the new syntax doesn’t take
long It all depends on what you hang off the right edge of the reference Original
properties and methods are recognized as using the original documentobject; new
properties and methods summon the powers of the new documentobject It’s all
quite automatic Thankfully
Trang 7344 Part III ✦ Document Objects Reference
Properties
activeElement
NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5 Compatibility ✓ ✓ ✓
In IE4+, a script can examine the document.activeElementproperty to see which element currently has focus The value returned is an element object refer-ence You can use any of the properties and methods listed in Chapter 15 to find out more about the object Be aware that not all elements in all operating systems receive focus For example, buttons in IE4 for the Macintosh do not receive focus Although the element used to generate a mouse or keyboard event will most likely have focus (except for IE4/Mac buttons), don’t rely on the activeElement property to find out which element generated an event The IE event.srcElement property is far more reliable
Example on the CD
Related Items:event.srcElementproperty
alinkColor
bgColor
fgColor
linkColor
vlinkColor
Value: Hexadecimal triplet or color name string Mostly Read/Write
NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5 Compatibility ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓
These five properties are the script equivalent of the <BODY>tag attributes of the same name (although the property names are case-sensitive) All five settings can
be read via scripting, but the ability to change some or all of these properties varies widely with browser and client platform Table 18-1 shows a summary of which browsers and platforms can set which of the color properties
On the
CD-ROM
document.alinkColor
Trang 8Table 18-1 Setting Document Colors on the Fly
(Browser Versions)
Navigator Internet Explorer
Color Property Windows Mac UNIX Windows Mac UNIX
bgColor All 4+ 4+ All All 4+
All others 6 6 6 All All 4+
If you experiment with setting document.bgColoron Mac or UNIX versions of
Navigator 2 and 3, you may be fooled into thinking that the property is being set
correctly While the property value may stick, these platforms do not refresh their
windows properly: If you change the color after all content is rendered, the swath of
new color obscures the content until a reload of the window The safest,
backward-compatible scripted way of setting document color properties is to compose the
content of a frame or window by script and set the <BODY>tag color attributes
dynamically when document.write()puts the content into the window
Values for all color properties can be either the common HTML hexadecimal
triplet value (for example, “#00FF00”) or any of the Netscape color names Internet
Explorer recognizes these plain language color names, as well But also be aware
that some colors work only when the user has the monitor set to 16- or 24-bit color
settings
If you are scripting exclusively for IE4+ and NN6, you should use the document
bodyobject to access these properties
Example on the CD with Listing 18-1
Related Items:body.aLink, body.bgColor, body.link, body.text, body.vLink
properties
anchors
NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5 Compatibility ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓
Anchor objects (described in Chapter 21) are points in an HTML document
marked with <A NAME=””>tags Anchor objects are referenced in URLs by a hash
value between the page URL and anchor name Like other object properties that
contain a list of nested objects, the document.anchorsproperty (notice the plural)
On the
CD-ROM
Trang 9346 Part III ✦ Document Objects Reference
delivers an indexed array of anchors in a document Use the array references to pinpoint a specific anchor for retrieving any anchor property
Anchor arrays begin their index counts with 0: The first anchor in a document, then, has the reference document.anchors[0] And, as is true with any built-in array object, you can find out how many entries the array has by checking the length property For example
var anchorCount = document.anchors.length
The document.anchorsproperty is read-only To script navigation to a particu-lar anchor, assign a value to the window.locationor window.location.hash object, as described in Chapter 17’s locationobject discussion
Example on the CD with Listing 18-2
Related Items:anchor, locationobjects; document.linksproperty
applets
NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5 Compatibility ✓ ✓ ✓ ✓ ✓ ✓
The appletsproperty refers to Java applets defined in a document by the
<APPLET>tag An applet is not officially an object in the document until the applet loads completely
Most of the work you do with Java applets from JavaScript takes place via the methods and variables defined inside the applet Although you can reference an applet according to its indexed array position within the appletsarray, you will more likely use the applet object’s name in the reference to avoid any confusion Note that applets are not accessible to JavaScript in IE/Mac For more details, see the discussion of the applet object in Chapter 32 and the LiveConnect discussion in Chapter 44
Example on the CD
Related Items:appletobject
bgColor
See alinkColor
On the
CD-ROM
On the
CD-ROM
document.bgColor
Trang 10NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5 Compatibility ✓ ✓ ✓ ✓
The document.bodyproperty is a shortcut reference to the BODY element
object in modern object models As you can see in the discussion of the BODY
ele-ment object later in this chapter, that object has many key properties that govern
the look of the entire page Because the documentobject is the root of all
refer-ences within any window or frame, the document.bodyproperty is easier to use to
get to the BODY properties, rather than longer references normally used to access
HTML element objects in both the IE4+ and W3C object models
Example on the CD
Related Items: BODY element object.
charset
NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5 Compatibility ✓ ✓ ✓
The charsetproperty reveals the character set used by the browser to render
the current document (the NN6 version of this property is called characterSet)
You can find possible values for this property at
ftp://ftp.isi.edu/in-notes/iana/assignments/character-sets
Each browser and operating system has its own default character set Values
may also be set via a <META>tag
Example on the CD
Related Items:characterSet, defaultCharsetproperties
On the
CD-ROM
On the
CD-ROM