Java Reference
In-Depth Information
For example, consider the following HTML:
<p class="sub-title">This is a <span>special</span> paragraph element
that contains <span>some text</span></p>.
Using the
querySelector()
method, you can retrieve the first
<span/>
element in this HTML with
the following code:
var firstSpan = document.querySelector(".sub-title span");
The provided CSS selector matches all
<span/>
elements contained within a parent element with a
CSS class of
sub‐title
. This HTML contains two such
<span/>
elements, but
querySelector()
only returns the first: the
<span/>
element containing the text “
special
.” Just as with the previous
examples, you can modify the element's text color with its
style
property:
<script>
var firstSpan = document.querySelector(".sub-title span");
firstSpan.style.color = "red";
</script>
If you wanted to retrieve all of the
<span/>
elements in this HTML, you want to use the fourth
method,
querySelectorAll()
, like this:
var spans = document.querySelectorAll(".sub-title span");
And just as with the
getElementsByTagName()
example, you can use a loop and modify all the
elements contained within the
spans NodeList
:
<script>
var spans = document.querySelectorAll(".sub-title span");
var length = spans.length;
for (var i = 0; i < length; i++) {
spans[i].style.color = "red";
}
</script>
Note
The
querySelector()
and
querySelectorAll()
methods aren't
actually part of the DOM standard. They're defined within the W3C's
Selectors API, which is one of the components to be consolidated with
DOM level 3 into DOM level 4. You can use these methods on
Element
objects, too.
Creating Elements and Text
The
Document
object also boasts some methods for creating elements and text, shown in the
following table.