If you separate multiple elements selectors with a greater-than sign (
>
), you can select
nodes that are direct children. For example,
#content > p
will select
<p>
elements
that are children of an element with ID
content
(contrast this with
"#content p
“).
Note that you can combine ancestry and direct child selectors. For example,
body .content > p
will select
<p>
tags that are direct children of elements with class
content
that are descendants of
<body>
.
There are more sophisticated selectors, but the ones covered here are the most com‐
mon. To learn more about all the selectors available, see the
.
Manipulating DOM Elements
Now that we know how to traverse, get, and query elements, what do we do with
them? Let’s start with content modification. Each element has two properties,
text
Content
and
innerHTML
, that allow you to access (and change) the element’s content.
textContent
strips out all HTML tags and provides text data only, whereas
innerHTML
allows you to create HTML (which results in new DOM nodes). Let’s see
how we can access and modify the first paragraph in our example:
const
para1
=
document
.
getElementsByTagName
(
'p'
)[
0
];
para1
.
textContent
;
// "This is a simple HTML file."
para1
.
innerHTML
;
// "This is a <i>simple</i> HTML file."
para1
.
textContent
=
"Modified HTML file"
;
// look for change in browser
para1
.
innerHTML
=
"<i>Modified</i> HTML file"
;
// look for change in browser
Assigning to textContent and innerHTML is a destructive opera‐
tion: it will replace whatever is in that element, no matter how big
or complex. For example, you could replace the entire page con‐
tents by setting innerHTML on the <body> element!
Creating New DOM Elements
We’ve already seen how to implicitly create new DOM nodes by setting an element’s
innerHTML
property. We can also explicitly create new nodes with
document.crea
teElement
. This function creates a new element, but it doesn’t add it to the DOM;
you’ll have to do that in a separate step. Let’s create two new paragraph elements; one
will become the first paragraph in
<div id="content">
, and the other will become
the last:
const
p1
=
document
.
createElement
(
'p'
);
const
p2
=
document
.
createElement
(
'p'
);
p1
.
textContent
=
"I was created dynamically!"
;
p2
.
textContent
=
"I was also created dynamically!"
;
Manipulating DOM Elements | 263