Selecting Elements
Last updated
Last updated
Let's play with a paragraph tag. Create a paragraph tag with sample text inside.
Now let's use JavaScript to manipulate this paragraph tag! Let's change the color of the text to blue.
Now your paragraph should have blue text. Let's look at that line of code in more depth:
document
is the overall DOM, the overall HTML document/page
getElementById
is a method on our DOM that finds one particular element based on its ID
After we've found that element, style
is a property of that HTML element which controls that element's style
color
is the property (of style
) that we want to access
= 'blue'
: the =
is the assignment operator; we are setting the style equal to blue
. We do not have to set the value. We could just write
which would return the value. In fact, let's do that now. Use console.log()
so we can see the value.
Refresh the page and you should see "blue" in the console.
We used the getElementById
method to pick which element we wanted to style. You might wonder... so, will we have to put IDs on EVERY element we want to interact with?
Of course not! That would be painfully tedious... There are other ways we can select elements. Two such ways include:
But... there might be multiple paragraph tags on the page! Or multiple elements might have the same class applied (in fact, there probably WILL be multiple elements with the same class). Both of these methods return an HTMLCollection
, which is very similar to an array. These selectors are rarely used, so we won't clutter your already-full-brain with uncommon examples.
The 2 most common ways to select an element are:
We already gave an example of the first one, now let's look at the 2nd one. As you can probably guess, the querySelectorAll
uses CSS-style selectors. This also returns a pseudo-array-like list of matching elements called a Node List
.
Let's do a quick example with that too:
Produces...
The style
property is one of the most common properties to change. Another useful property is called innerText
(and a very similar one named innerHTML
).
Let's do that now, and let's use querySelectorAll
to do it. Since querySelectorAll
returns an array-like NodeList, we need to use array-notation when selecting an element from it, even if there is only one element.
What's the difference between innerText
and innerHTML
?
innerText
will only reference the text displayed on the screen.
innerHTML
will reference all HTML elements inside the tag. Let's do a quick test:
This will create an entire HTML element inside the tag. If we inspect the page, we can see a whole new tag has been inserted into the existing paragraph tag:
If we wanted to remove elements, we can do the same thing in reverse! Simply set the innerHTML
to be blank and it will erase the contents.