HTML and CSS Reference
In-Depth Information
Specifying Node Relationships
• To access the parent of a node, use the reference
node
.parentNode
where
node
is a node object in the node tree.
• To reference the first child and last child of a node, use the following references:
node
.firstChild
node
.lastChild
• To reference the collection of all child nodes, use the following reference:
node
.childNodes
• To reference the previous and next siblings, use the following references:
node
.previousSibling
node
.nextSibling
Creating and Attaching Nodes
To display a dynamic table of contents, you must create the content of the TOC based on
the node structure of the current document. The document object model supports several
methods to create new content; these methods are listed in Figure 14-10.
Figure 14-10
Methods to create nodes
Method
Description
document.createAttribute(
att
)
Creates an attribute node with the name
att
document.createComment(
text
)
Creates a comment node containing the comment
text
document.createElement(
elem
)
Creates an element node with the name
elem
document.createTextNode(
text
)
Creates a text node containing the text string
text
node
.cloneNode(
deep
)
Creates a copy of
node
(If the Boolean parameter
deep
is
true, the copy extends to all descendants of
node
; other-
wise, only
node
is copied.)
Using these methods, you can create a wide variety of document objects. For exam-
ple, you would use the following expression to create a text node containing the text
Historic Documents Online
:
document.createTextNode(“Historic Documents Online”);
All of the methods described in Figure 14-10 create single nodes, with the exception of
the
cloneNode()
method. The
cloneNode()
method is useful when you need to create
a copy of an existing node, including any descendants of that node. Thus, the command
var newtitle = title.cloneNode(true);
creates a copy of the
title
node, including any descendants of that node. The
cloneNode()
method provides a quick and easy way to create elements and their con-
tent without having to create each node individually.