JS-151-API
  • JavaScript Library
  • 02-DOM-Manipulation
    • Overview
    • DOM Explained
    • Example Setup
    • Selecting Elements
    • Events
    • Complete Example
  • 03-API Fundamentals
    • 0-Getting Started
      • Welcome
    • 1-Intro-To-APIs
      • Intro
      • Client
      • Requests
      • JSON
      • API Endpoints
      • Server
      • Response
      • Statelessness
      • REST
    • 2-Asynchronous-Programming
      • Intro
      • Callbacks
      • Promises
      • Promises Continued
      • Chaining Promises
    • 3-Fetch
      • Fetch Intro
      • Star Wars
        • Star Wars API
        • Star Wars Setup
        • Star Wars JS
      • Random Photo
        • Unsplash
        • Unsplash Setup
        • Unsplash JS
    • 4-Apps
      • 01-New York Times
        • 00-App Intro
        • 01-HTML/CSS/API Key
        • 02-Variables
        • 03-Event Listeners
        • 04-fetchResults
          • 01-fetchResults()
          • 02-preventDefault()
          • 03-fetch() method
          • 04-Dates
        • 05-displayResults
          • 01-Logging JSON
          • 02-Working with JSON
          • 03-Link Display
          • 04-Results Navigation
          • 05-Results Update
          • 06-Keywords
          • 07-Images
        • 06-Pagination
          • 01-Pagination Intro
          • 02-Pagination Functions
        • 07-Next Steps
      • 02-YouTube
        • html
        • youtube.css
        • youtube.js
      • 03-GoogleMaps
        • Setup
        • HTML and CSS files
        • API Key
        • JS Setup
        • Adding Your Location
        • Listeners
        • Custom Options
Powered by GitBook
On this page
  1. 02-DOM-Manipulation

Selecting Elements

PreviousExample SetupNextEvents

Last updated 7 years ago

Let's play with a paragraph tag. Create a paragraph tag with sample text inside.

<body>
    <!-- All of our HTML code will go here -->
    <p id="testParagraph">sample text</p>

Now let's use JavaScript to manipulate this paragraph tag! Let's change the color of the text to blue.

<script type="text/javascript">
    /* All of our JavaScript code will go here */
    document.getElementById('testParagraph').style.color = 'blue';
</script>

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

    document.getElementById('testParagraph').style.color

    which would return the value. In fact, let's do that now. Use console.log() so we can see the value.

    document.getElementById('testParagraph').style.color = 'blue';
    console.log(document.getElementById('testParagraph').style.color);

    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:

document.getElementsByTagName("p");
document.getElementsByClassName("classHere");

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:

document.getElementById("idHere")
document.querySelectorAll("p.classNameHere")

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:

<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>

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.

<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>

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:

    <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>

    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.

Sample Log
Console Blue
New Tag