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...
Sample Log
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.
<body>
<!--All of our HTML code will go here -->
<p id="testParagraph">sample text</p>
<p class="sampleClass">This paragraph has a class of 'sampleClass'</p>
<script type="text/javascript">
/* All of our JavaScript code will go here */
console.log(document.querySelectorAll("p.sampleClass"));
</script>
</body>
<script type="text/javascript">
/* All of our JavaScript code will go here */
console.log(document.querySelectorAll("p.sampleClass"));
document.querySelectorAll("p.sampleClass")[0].innerText = "My text was changed!";
</script>
<script type="text/javascript">
/* All of our JavaScript code will go here */
console.log(document.querySelectorAll("p.sampleClass"));
document.querySelectorAll("p.sampleClass")[0].innerHTML = "<span>I am a whole new element!</span>";
</script>