HTML and CSS Reference
In-Depth Information
FIGURE 1-16
A message showing the number of
<p>
elements with the specified class name
subPara
This example adds a little more text to the message box so that it looks different from the
previous example, but the idea is the same. All
<p>
elements with the
subPara
class assigned
to them were returned in a
NodeList
. You can see that the call returned four HTML elements.
When selecting elements in the DOM by class name, the
NodeList
contains all elements
whose class matches the specified class—not just elements of the same type. If, for example,
you assigned the class
subPara
to one of your
<div>
elements and then ran the function
again, the returned
NodeList
would contain the four
<p>
elements and the
<div>
element
because they all have the same class. This is important when you intend to iterate over the
elements and do something to them. In Figure 1-17, the same JavaScript code is run, but with
an added
subPara
class attribute to a
<div>
element.
FIGURE 1-17
The same script run with a
<div>
assigned the class name
subPara
This message box is now actually incorrect, because the
NodeList
contains a single
<div>
element and the four
<p>
elements. Keep this behavior in mind concerning the
getElementsByClassName
method.
All the methods you have looked at so far to find elements in the DOM provide a specific
implementation for a specific purpose. If you want a single element by its unique ID, you use
the
getElementById
method; if you want to find an element or all the elements of a specific
CSS class, you use the
getElementsByClassName
method. Now look at some examples that
use the much more flexible
querySelector
and
querySelectorAll
methods.
The
querySelector
and
querySelectorAll
methods allow you to achieve most of what you've
already done with the other methods. Both methods take a parameter in the form of a CSS
Search WWH ::
Custom Search