All of the DOM methods that return a collection do not return a
JavaScript array, but an instance of HTMLCollection, which is an
“array-like” object. You can iterate over it with a for loop, but the
Array.prototype
methods (such as map, filter, and reduce)
won’t be available. You can convert an HTMLCollection to an array
by using the spread operator: [...document.getElementsByTag
Name(p)]
.
Querying DOM Elements
getElementById
,
getElementsByClassName
, and
getElementsByTagName
are useful,
but there’s a much more general (and powerful) method that can locate elements not
just by a single condition (ID, class, or name), but also by the element’s relationship to
other elements. The
document
methods
querySelector
and
querySelectorAll
allow
you to use CSS selectors.
CSS selectors allow you to identify elements by their name (
<p>
,
<div>
, etc.), their ID,
their class (or combination of classes), or any combination thereof. To identify ele‐
ments by name, simply use the name of the element (without angle brackets). So
a
will match all
<a>
tags in the DOM, and
br
will match all the
<br>
tags. To identify
elements by their class, use a period before the class name:
.callout
will match all
elements that have the class
callout
. To match multiple classes, just separate them
with periods:
.callout.fancy
will match all elements that have the class
callout
and
the class
fancy
. Lastly, they can be combined: for example,
a#callout2.cal
lout.fancy
will match
<a>
elements with ID
callout2
, and classes
callout
and
fancy
(it’s very rare to see a selector that uses element name, ID, and class(es)…but it
is possible).
The best way to get the hang of CSS selectors is to load the sample HTML provided in
this chapter in a browser, open the browser’s console, and try them out with
querySe
lectorAll
. For example, in the console, type
document.querySelectorAll('.cal
lout')
. All of the examples in this section will produce at least one result with
querySelectorAll
.
So far, we’ve been talking about identifying specific elements no matter where they
appear in the DOM. CSS selectors also enable us to locate elements according to their
position in the DOM.
If you separate multiple element selectors with a space, you can select nodes with a
specific ancestry. For example,
#content p
will select
<p>
elements that are descend‐
ants of whatever element has the ID
content
. Likewise,
#content div p
will select
<p>
elements that are inside a
<div>
that are inside an element with the ID
content
.
262 | Chapter 18: JavaScript in the Browser