function
removeParaHighlights
() {
const
paras
=
document
.
querySelectorAll
(
'p.highlight'
);
for
(
let
p
of
paras
) {
p
.
classList
.
remove
(
'highlight'
);
}
}
When removing the highlight class, we could have reused the
same paras variable, and simply called remove('highlight') on
every paragraph element; it will do nothing if the element doesn’t
already have the class. However, it’s likely that the removal will
come at some later point in time, and there may have been high‐
lighted paragraphs added by other code: if our intention is to clear
all highlighting, performing a query is the safer method.
Data Attributes
HTML5 introduced data attributes, which allow you to add arbitrary data to HTML
elements; this data isn’t rendered by the browser, but it does allow you to add infor‐
mation to elements that can easily be read and modified by JavaScript. Let’s modify
our HTML by adding a button that we will eventually hook up to our
highlightPa
ras
function, and another one that we’ll hook up to
removeParaHighlights
:
<
button
data-action
=
"highlight"
data-containing
=
"unique"
>
Highlight paragraphs containing "unique"
</
button
>
<
button
data-action
=
"removeHighlights"
>
Remove highlights
</
button
>
We’ve called our data attributes
action
and
contains
(the names are up to us), and
we can use
document.querySelectorAll
to find all elements that have
"highlight"
as their action:
const
highlightActions
=
document
.
querySelectorAll
(
'[data-action="highlight"]'
);
This introduces a new type of CSS selector. So far, we’ve seen selectors that can match
specific tags, classes, and IDs. The square bracket syntax allows us to match elements
by any attribute…in this case, a specific data attribute.
Because we only have one button, we could have used
querySelector
instead of
quer
ySelectorAll
, but this allows us to have multiple elements that are designed to trig‐
ger the same action (which is quite common: think about actions that you can access
through a menu, link, or toolbar, all on the same page). If we take a look at one of the
elements in
highlightActions
, we note that it has a
dataset
property:
highlightActions
[
0
].
dataset
;
// DOMStringMap { containing: "unique", action: "highlight" }
Data Attributes | 265