-
You've now got a lot of tools
in your toolbox for finding elements.
-
And those will work great
a lot of the time.
-
But there is one final tool
that's the most powerful of them all:
-
the ability to find elements
based on any CSS selector.
-
Do you remember CSS selectors?
-
The basic ones were
finding by tag name,
-
or ID
-
or class
-
But there are many
more advanced selectors:
-
descendant selectors, attribute selectors,
combined class plus element selectors--
-
this would be a good time
for you to review CSS selectors
-
if you've forgotten all of those.
-
For example, what if I wanted
to specifically style only the elements
-
with class name "animal"
that are inside a paragraph?
-
Let's stick a `` tag in
and do that.
-
So I would first write `p`,
-
and then a space, to say that
I'm looking inside ``s,
-
and then dot animal to say that
I'm looking for any elements
-
with class name "animal".
-
And I'll just color them red.
-
Beautiful.
-
Now, I could use the same CSS selector
to find those elements in JavaScript,
-
using the
`document.querySelectorAll()` method.
-
So I'll change this line here.
-
And I need to pass the CSS selector
as the argument,
-
as a string in quotes.
-
And there, the paragraph
is about cats again.
-
You could pass any valid
CSS selector to that function,
-
and it will return back
a collection of elements
-
that you can then loop through.
-
Do you remember last time
how we said
-
that `getElementsByTagName()`
returns an HTML collection
-
that looks a lot like an array?
-
Well this method returns a `NodeList`,
which is also a lot like an array,
-
in that we can use the brackets on it,
we can check the length, all of that.
-
And you probably won't run into
the differences between
-
a NodeList and an HTMLCollection
when you're using these methods.
-
But you are welcome to look them up
if you'd like to learn more about them.
-
Okay, now, there's also a method
that will look up CSS selectors,
-
and return only one element,
if you know your CSS selector
-
is only selecting one thing.
-
In practice, it's not really as useful,
-
because you usually have
an ID that you can use in that case.
-
But I'll show it to you just in case.
-
So here, instead of `getElementById`,
I could actually say:
-
`document.querySelector("`
-
and then for the actual query,
to make it be an ID, I just add that hash.
-
Ta-da.
-
So, as you see, this is really similar
to `querySelectorAll()`,
-
except we're only selecting one,
so it's just `querySelector()`,
-
and we just pass in some CSS selector
that we expect to get back one element.
-
So when should you use
each of these tools in your toolbox?
-
The first ones that I showed you
tend to perform better.
-
So I suggest using those when you can.
-
But if you're in a situation where
you need to use a complex CSS selector,
-
and you can't use those,
then `querySelectorAll()` is your friend.
-
Try it out in the next challenge,
-
then get ready to see way more ways
that you can manipulate this webpage.