The DOM & Getting/Setting Properties

Free JavaScript Tutorial

Learn how to manipulate HTML elements using JavaScript in our tutorial where you will get hands-on experience with the Document Object Model (DOM), and develop a product color picker that changes the product image based on the user's color selection.

This exercise is excerpted from Noble Desktop’s JavaScript for Front-End training materials and is compatible with JavaScript updates through 2023. To learn current skills in JavaScript with hands-on training, check out our Front-End Web Development Certificate, Full-Stack Web Development Certificate, and coding classes in-person and live online.

Note: These materials are provided to give prospective students a sense of how we structure our class exercises and supplementary materials. During the course, you will get access to the accompanying class files, live instructor demonstrations, and hands-on instruction.

Topics covered in this JavaScript tutorial:

Selecting HTML elements with getElementById(), Manipulating selected elements, Getting & setting properties (such as adding a class)

JavaScript Development Certificate: Live & Hands-on, In NYC or Online, 0% Financing, 1-on-1 Mentoring, Free Retake, Job Prep. Named a Top Bootcamp by Forbes, Fortune, & Time Out. Noble Desktop. Learn More.

Exercise Preview

ex prev color picker

Exercise Overview

In this exercise you’ll learn to work with the DOM (Document Object Model) to target objects in a document (webpage), getting and setting their properties.

When products are available in multiple colors, users need to be able to choose the color. Starting in this exercise (and finishing in later exercises) you’ll use JavaScript to make a product color picker that lets a user choose a color and then see a photo of the product in the color they selected.

Getting Started

  1. For this exercise we’ll be working with the Product-Chooser-DOM folder located in Desktop > Class Files > JavaScript Class. Open that folder in your code editor if it allows you to (like Visual Studio Code does).
  2. In your code editor, open product.html from the Product-Chooser-DOM folder.
  3. Preview product.html in Chrome. (We’re using Chrome because we’ll be using its DevTools.)
  4. Ctrl–click (Mac) or Right–click (Windows) anywhere on the page and choose Inspect from the menu.
  5. At the top of the DevTools window, click on the Console tab.
  6. Let’s experiment with hiding and showing various objects in this page.

    In the Console, type document and hit Return (Mac) or Enter (Windows).

  7. You should see #document return in the Console. Hover over the word #document and notice that the whole page is highlighted.
  8. Click the arrow next to #document to expand it. This is the whole HTML document, and contains everything on the page.
  9. Click the arrow next to <body> to expand it, the expand <main>
  10. Hover over the two div tags inside <main> and notice that those blocks of content highlight in the browser.

    TIP: Adjusting the Console’s Text Size

    You can adjust the size of the Console text as follows:

    • Mac: Cmd-Plus(+) enlarges the text. Cmd-Minus(-) reduces the text. Cmd-0 resets to the default size.
    • Windows: Ctrl-Plus(+) enlarges the text. Ctrl-Minus(-) reduces the text. Ctrl-0 resets to the default size.

Selecting & Working with HTML Elements

We don’t typically want to make changes to the whole document, but rather specific HTML elements within the document. We can get specific objects using the JavaScript method document.getElementById(). This dot syntax will become more familiar as we continue to dig deeper into accessing elements and their properties.

  1. At the top left of the DevTools window, click the inspector select element button.
  2. In the page, click on the photo.
  3. In the DevTools, notice that the img tag with and ID of product-photo is highlighted.
  4. In the DevTools, click on the Console tab.

  5. In the Console, type document.getElementById('product-photo');

    About getElementById()

    The document.getElementById(‘elementID’) method gets the element whose id is a string that is passed in as the argument (in the parentheses). The element arrives is an object (which is often saved to a variable for future reference). Please note that the capitalization of ById in the name of this method must be correct for the code to function.

  6. Hit Return (Mac) or Enter (Windows).
  7. You should see <img id="product-photo" src="img/chair-beige.jpg"> in the Console.

    Hover over this and notice that only the image in the page highlights. So far we’ve selected the whole element whose ID is product-photo. We can get more specific and talk to this element’s styles by using dot syntax again.

  8. To save yourself some typing, press the Up Arrow key in the Console. This will show your last command so you don’t have to type it again. Very handy!
  9. Add the following bold code:

    document.getElementById('product-photo').style.display = 'none';
    

    This says to get the element with the ID product-photo and set its display property to none, which will hide the image. Note that the property value ('none') must be a string.

  10. Hit Return (Mac) or Enter (Windows) to execute the code and notice that the image disappears!
  11. Let’s get the image to reappear. In the Console, press the Up Arrow key again to show your last command.
  12. Change the code as shown in bold:

    document.getElementById('product-photo').style.display = 'block';
    
  13. Hit Return (Mac) or Enter (Windows). The image should reappear.

    While changes made in the Console are not permanent, it’s a great way to test small pieces of code.

    NOTE: Leave this page open in the browser, so you can reload it to see the changes you make in the code.

Getting & Setting Properties

Notice the product photo is showing the chair in one of its available colors. There are color swatches showing the other colors, but if you click on them they won’t do anything yet. When a user clicks one of these color swatches, we want the photo to change to the color they clicked on.

Making something happen when you click requires a function, which you’ll learn later. So for now, we’ll simply focus on making sure we can change the image. Later we’ll make it work when clicking a button (and making all the buttons work).

  1. Switch back to product.html in your code editor.
  2. In your code editor, take note of the following HTML:

       <div class="color-swatches">
          <button class="swatch selected" id="beige"></button>
          <button class="swatch" id="yellow"></button>
          <button class="swatch" id="blue"></button>
          <button class="swatch" id="red"></button>
       </div>
    </div>
    <div class="col photo">
        <img id="product-photo" src="img/chair-beige.jpg">
    </div>
    
  3. Notice the following:

    • The 4 buttons are “color swatches” a user may click to choose that color product.
    • Each button has an id for its color: beige, blue, red, and yellow.
    • The img tag has an id of product-photo.
    • The image src of chair-beige.jpg is what appears when the page first loads.
  4. In your code editor’s file explorer, open the img folder.

    Notice there are 4 product images, one for each color (and the color name exactly matches the id we have in HTML):

    • chair-beige.jpg
    • chair-blue.jpg
    • chair-red.jpg
    • chair-yellow.jpg

  5. In product.html add a script tag right before the end of the head.

       <script></script>
    </head>
    
  6. Inside the script tag, get the product-photo div:

    <script>
       let productPhoto = document.getElementById('product-photo');
    </script>
    
  7. Change the image source to the red chair by adding the following bold code:

    <script>
       let productPhoto = document.getElementById('product-photo');
       productPhoto.src = 'img/chair-red.jpg';
    </script>
    
  8. Save and reload the page in the browser.

    Hmm, nothing happened. Let’s check the Console for errors:
    • Ctrl–click (Mac) or Right–click (Windows) on the page, choose Inspect.
    • At the top of the DevTools window, click on the Console tab.
    • You should see an error message. Why?

      Browsers read code from top to bottom. The HTML for the photo is down in the <body>. Because the JS that references this object is at the top of the file (before the element has actually been created) our JS code fails! To avoid this problem, it’s a best practice to put JS at the bottom of the HTML instead of at the top. This ensures all elements have been created before the JS is executed.

  9. Switch back to your code editor.
  10. Cut the entire <script> tag (and its contents) from the head.
  11. Paste it just above the closing </body> tag:

       <script>
          let productPhoto = document.getElementById('product-photo');
          productPhoto.src = 'img/chair-red.jpg';
       </script>
    </body>
    
  12. Save and reload the page in the browser.

    The product photo should now be the red chair!

    This hard-coded change does not look at what button the user clicks, which you’ll do in a later exercise.

  13. Each button has a light gray border that we’ll want to change it to another color when the user clicks (so they know which color is currently selected).

  14. Back in your code editor, get the red button and change its border color by adding the following bold code:

    <script>
       let productPhoto = document.getElementById('product-photo');
       let colorButton = document.getElementById('red');
    
       productPhoto.src = 'img/chair-red.jpg';
       colorButton.style.borderColor = 'lime';
    </script>
    
  15. Save and reload the page in the browser.

    The red button should now have a lime green border.

  16. Ctrl–click (Mac) or Right–click (Windows) on the red button and choose Inspect.

    In the DevTools Elements tab, notice the button has inline CSS (a style attribute) for the lime border.

  17. Let’s see how to use a class that’s already been defined in the CSS. Back in your code editor, change the last line of JavaScript as shown below in bold:

    <script>
       let productPhoto = document.getElementById('product-photo');
       let colorButton = document.getElementById('red');
    
       productPhoto.src = 'img/chair-red.jpg';
       colorButton.classList.add('selected');
    </script>
    
  18. Save and reload the page in the browser.

    • The red button should now have a black border.

    • Notice in the DevTools Elements tab the button now has a selected class and no more style attribute. We have a rule for .selected in our CSS file.

    NOTE: The advantage of using a class instead of specifying CSS directly in your JS, is it makes the CSS easier to find and edit for other developers (especially those who don’t know JS). Also the CSS class can set many CSS properties, keeping your JS clean with just one line of code to add the class.

How to Learn JavaScript

Master JavaScript with hands-on training. JavaScript is one of the world's most widely-used coding languages. Learn JavaScript and its libraries to start creating interactive websites and mobile apps.

Yelp Facebook LinkedIn YouTube Twitter Instagram