for). Fortunately, the DOM provides methods to locate HTML elements more
directly.
While writing your own traversal function is a good exercise, the
DOM API provides the TreeWalker object, which allows you to
iterate through all of the elements in the DOM (optionally filtering
by certain element types). For more information, see the MDN
documentation for
.
Some Tree Terminology
The concept of a tree is straightforward and intuitive, and lends itself to similarly
intuitive terminology. A node’s parent is its direct parent (that is, not a “grandparent”)
and a child is a direct child (not a “grandchild”). The term descendant is used to refer
to a child, or a child’s child, or so on. The term ancestor is used to refer to a parent,
the parent’s parent, and so on.
DOM “Get” Methods
The DOM provides “get” methods that allow you to quickly locate specific HTML
elements.
The first of these is
document.getElementById
. Every HTML element on a page may
be assigned a unique ID, and
document.getElementById
can retrieve an element by
its ID:
document
.
getElementById
(
'content'
);
// <div id="content">...</div>
Browsers don’t do anything to enforce the uniqueness of IDs
(though an HTML validator will catch these issues), so it is incum‐
bent on you to ensure that IDs are unique. As the construction of
web pages gets more complicated (with components coming from
multiple sources), it’s becoming increasingly difficult to avoid
duplicate IDs. For this reason, I recommend using them carefully
and sparingly.
document.getElementsByClassName
returns a collection of elements that have the
given class name:
const
callouts
=
document
.
getElementsByClassName
(
'callout'
);
And
document.getElementsByTagName
returns a collection of elements that have the
given tag name:
const
paragraphs
=
document
.
getElementsByTagName
(
'p'
);
Some Tree Terminology | 261