HTML and CSS Reference
In-Depth Information
Figure 14-9
element node properties
Property
Description
node
.children
A collection of all of the element nodes contained within
node
node
.firstElementChild
The first element within
node
node
.lastElementChild
The last element within
node
node
.nextElementSibling
The next sibling element to
node
node
.previousElementSibling
The previous sibling element to
node
node
.childElementCount
The number of child elements within
node
node
.children.length
The number of child elements within
node
For example, in the HTML fragment
<article>
<h1>The U.S. Constitution</h1>
<h2>Preamble</h2>
<p>
We the People of the United States, in Order
to form a more perfect Union ...
</p>
</article>
the
children.length
property for the
article
element returns a value of 3, indicating
that the article contains three child element nodes—representing the
h1
,
h2
, and
p
ele-
ments. Note that the element node properties are not supported by versions of Internet
Explorer before IE9, though they are supported by other major browsers.
Problem Solving: Nodes and White Space
One source of confusion when working with nodes is the treatment of white space within an
HTML file. The document object model specifies that the white space between element tags
should be treated as a text node. Therefore, the HTML fragment
<h1>The U.S. Constitution</h1>
<h2>Preamble</h2>
contains five nodes: two element nodes (for the
h1
and
h2
elements), two text nodes (for
the text strings
The U.S. Constitution
and
Preamble
), and one more text node you don't see
representing the line return between the closing
</h1>
tag and the opening
<h2>
tag.
One source of confusion is that versions of Internet Explorer before IE9 did not count
white space nodes as text nodes, so the above HTML fragment would have only four nodes
under the IE DOM. This has been corrected in IE9, and all current browsers should count
both text nodes and white space nodes.
Now that you've learned how an HTML document is composed of different types of
nodes, you'll explore how to use JavaScript to create new nodes that can be attached to
existing documents.