To add these newly created elements to the DOM, we’ll use the
insertBefore
and
appendChild
methods. We’ll need to get references to the parent DOM element (
<div
id="content">
), and its first child:
const
parent
=
document
.
getElementById
(
'content'
);
const
firstChild
=
parent
.
childNodes
[
0
];
Now we can insert the newly created elements:
parent
.
insertBefore
(
p1
,
firstChild
);
parent
.
appendChild
(
p2
);
insertBefore
takes the element to inset first, and then a “reference node,” which is
the node to insert before.
appendChild
is very simple, appending the specified ele‐
ment as the last child.
Styling Elements
With the DOM API, you have complete and fine-grained control over element styl‐
ing. However, it is generally considered good practice to use CSS classes instead of
modifying the individual properties of an element. That is, if you want to change the
style of an element, create a new CSS class, and then apply that class to the element(s)
you wish to style. Using JavaScript, it is easy to apply an existing CSS class to an ele‐
ment. For example, if we wanted to highlight all paragraphs that contain the word
unique, we would first create a new CSS class:
.highlight
{
background
:
#ff0
;
font-style
:
italic
;
}
With that in place, we can find all
<p>
tags, and if they contain the word unique, add
the
highlight
class. Every element has a property
classList
, which contains all of
the classes (if any) the element has.
classList
has an
add
method that allows you to
add further classes. We’ll be using this example later in this chapter, so we put it in a
function called
highlightParas
:
function
highlightParas
(
containing
) {
if
(
typeof
containing
===
'string'
)
containing
=
new
RegExp(
`\\b
${
containing
}
\\b`
,
'i'
);
const
paras
=
document
.
getElementsByTagName
(
'p'
);
console
.
log
(
paras
);
for
(
let
p
of
paras
) {
if
(
!
containing
.
test
(
p
.
textContent
))
continue
;
p
.
classList
.
add
(
'highlight'
);
}
}
highlightParas
(
'unique'
);
And then if we want to remove the highlights, we can use
classList.remove
:
264 | Chapter 18: JavaScript in the Browser