Game Development Reference
In-Depth Information
You will note that the demonstration of the old way of selecting elements uses a very
defensive programming style. While trivial selections may not need such paranoiac
measures, a large application would definitely benefit from such an approach in case
a particular element is not found in the DOM, and an event listener is attempted to
be added to a variable holding a null reference. Either way, you can see how the new
selectors API solves this problem in this particular situation, since no matter what
other elements are possibly added to, or taken away from that #navOptions sub-
tree, the CSS query used in the querySelector("#navOptions img") state-
ment would still hold true, whereas nav.children[1] might not refer to the same
element, should the structure of #navOptions change.
Also, you will note that the call to querySelector will return null if no elements are
matched with the CSS query provided. When using the querySelectorAll inter-
face, remember that a list will be returned whenever a match is found, whether one
or more elements are selected. Thus, if only a single element is matched, you would
still need to index into the result set in order to match the only element returned.
<div id="wordsWritten">
<span class="correct">I</span>
<span class="correct">love</span>
<span class="correct">HTML5</span>
<span class="wrong">?</span>
</div>
<script>
var correctWords =
document.querySelectorAll("#wordsWritten
.correct");
// correctWords == [
// <span class="correct">I</span>,
// <span class="correct">love</span>,
// <span class="correct">HTML5</span>]
var wrongWords =
document.querySelectorAll("#wordsWritten
.wrong");
// wrongWords == [
Search WWH ::




Custom Search