↑
Main Page
HTML DOM
The variable
oHtml
now contains an
HTMLElement
object representing
<html/>
. If you want to get the
<head/>
and
<body/>
elements using
oHtml
, this works:
var oHead = oHtml.firstChild;
var oBody = oHtml.lastChild;
You can also use the
childNodes
property to accomplish the same thing. Just pretend that it’s a regular
JavaScript
Array
and use square-bracket notation:
var oHead = oHtml.childNodes[0];
var oBody = oHtml.childNodes[1];
You can also get the number of child nodes by using the
childNodes.length
property:
alert(oHtml.childNodes.length); //outputs “2”
Note that the square-bracket notation is a convenient implementation of the
NodeList
in JavaScript. The
formal method of retrieving child nodes from the childNodes list is the
item()
method:
var oHead = oHtml.childNodes.item(0);
var oBody = oHtml.childNodes.item(1);
The HTML DOM also defines
document.body
as a pointer to the
<body />
element:
var oBody = document.body;
With the three variables
oHtml
,
oHead
, and
oBody
, you can play around to determine their relationship
to one another:
alert(oHead.parentNode == oHtml); //outputs “true”
alert(oBody.parentNode == oHtml); //outputs “true”
alert(oBody.previousSibling == oHead); //outputs “true”
alert(oHead.nextSibling == oBody); //outputs “true”
alert(oHead.ownerDocument == document); //outputs “true”
This little snippet of code tests to make sure that the
parentNode
property of both
oBody
and
oHead
point to
oHtml
, as well as uses the
previousSibling
and
nextSibling
properties to establish their
relationship to one another. The last line assures that the
ownerDocument
property of
oHead
actually
does point back to the document.
There is some discrepancy among browsers regarding what is and isn’t a
Text
node.
Some browsers, such as Mozilla, consider any white space between elements a
Text
node; whereas others, such as Internet Explorer, ignore the white space altogether.
Because it’s hard to determine which white space to consider as a
Text
node using
the Mozilla method, this book uses the Internet Explorer method.
168
Chapter 6
09_579088 ch06.qxd 3/28/05 11:37 AM Page 168
Free JavaScript Editor
Ajax Editor
©
→