Skip to main content
March 23, 2026Dan Rodney/10 min read

The DOM & Getting/Setting Properties

Master DOM Manipulation with JavaScript GetElementById

Core DOM Concepts You'll Master

Element Selection

Learn to target specific HTML elements using GetElementById() method. This is the foundation of DOM manipulation.

Property Manipulation

Discover how to get and set element properties like src, display, and classList to create dynamic interactions.

Visual Feedback

Implement user interface changes like border colors and image swapping to provide immediate visual feedback.

Topics Covered in This JavaScript Tutorial

This comprehensive lesson covers essential DOM manipulation techniques: selecting HTML elements with getElementById(), manipulating targeted elements dynamically, and getting and setting properties such as CSS classes. These foundational skills form the backbone of modern interactive web development.

Exercise Preview

ex prev color picker

Exercise Overview

In this hands-on exercise, you'll master working with the DOM (Document Object Model) to target specific elements within a webpage and dynamically modify their properties. This is fundamental to creating responsive, interactive user interfaces that adapt to user input in real-time.

Modern e-commerce sites rely heavily on interactive product displays, especially when products are available in multiple variations. You'll build a practical product color picker that allows users to select different color options and immediately see the corresponding product image. This exercise introduces the core concepts, which you'll expand upon in subsequent lessons to create a fully functional, production-ready component.

By the end of this tutorial, you'll understand how JavaScript bridges the gap between static HTML and dynamic user experiences—a critical skill for any modern web developer.

Product Color Picker Development Process

1

Setup Environment

Configure your development environment with proper folder structure and browser DevTools access

2

Element Selection

Master the GetElementById() method to target specific HTML elements in your webpage

3

Property Manipulation

Learn to modify element properties including images, styles, and CSS classes dynamically

4

Visual Implementation

Apply changes to create a functional color picker with proper user feedback mechanisms

Getting Started

Let's set up your development environment and explore the project structure. We'll be using Chrome's powerful DevTools to experiment with DOM manipulation in real-time—an essential workflow for professional JavaScript development.

  1. Navigate to the Product-Chooser-DOM folder located in Desktop > Class Files > JavaScript Class. Open this entire folder in your code editor (Visual Studio Code, Sublime Text, or similar) to access the complete project structure.
  2. In your code editor, open product.html from the Product-Chooser-DOM folder. Take a moment to review the HTML structure—notice the semantic markup and how elements are organized.
  3. Launch product.html in Chrome. We're specifically using Chrome because its DevTools provide the most comprehensive debugging and experimentation environment for JavaScript developers.
  4. Ctrl+click (Mac) or Right-click (Windows) anywhere on the page and select Inspect from the context menu. This opens Chrome's Developer Tools—your primary workspace for debugging and testing.
  5. At the top of the DevTools panel, click the Console tab. The Console is where you'll execute JavaScript commands and view output in real-time.
  6. Now let's begin experimenting with the document object model. The DOM represents your HTML as a tree structure that JavaScript can navigate and modify.

    In the Console, type document and press Return (Mac) or Enter (Windows). This accesses the root document object that contains your entire webpage.

  7. You should see #document appear in the Console. Hover your cursor over the word #document and observe how the entire page highlights in the browser. This visual feedback shows you exactly which DOM element you're targeting.
  8. Click the arrow next to #document to expand the tree structure. This reveals the complete HTML hierarchy, giving you a bird's-eye view of your page's structure.
  9. Expand the <body> element by clicking its arrow, then expand the <main> element within it. This hierarchical navigation is how JavaScript traverses your document structure.
  10. Hover over the two div tags nested inside <main> and notice how the corresponding content blocks highlight in the browser window. This visual connection between code and rendered output is crucial for understanding DOM relationships.

    Development Environment Setup

    0/4

TIP: Optimizing Console Text Size

Professional developers often spend hours working in the Console, so comfortable text sizing is essential. Adjust the Console text size using these shortcuts:

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

Selecting & Working with HTML Elements

While manipulating the entire document object is possible, real-world applications require precise targeting of specific HTML elements. JavaScript's document.getElementById() method provides this granular control, allowing you to select and modify individual page components.

This dot syntax pattern—object.method()—is fundamental to JavaScript and will become second nature as you advance. It represents the object-oriented approach that makes JavaScript so powerful for DOM manipulation.

  1. In the DevTools window, locate and click the inspector select element element selector button in the top-left corner. This tool lets you click any page element to inspect its HTML.
  2. Click directly on the product photo in the webpage. The DevTools will automatically highlight the corresponding HTML element.
  3. In the DevTools Elements panel, notice that the img tag with an ID of product-photo is now highlighted. This ID serves as a unique identifier that JavaScript can target.
  4. Switch to the Console tab to begin programmatic element selection.

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

    Element Selection Best Practice

    Use document.getElementById() to target specific HTML elements rather than manipulating the entire document. This dot syntax provides precise control over individual page elements.

    DOM Navigation Techniques

    Document Object

    The root object containing all HTML elements. Hover over #document in Console to highlight the entire page.

    Element Inspector

    Use the element selector button in DevTools to click and identify specific HTML elements with their IDs.

Understanding getElementById()

The document.getElementById('elementID') method is one of JavaScript's most fundamental DOM selection tools. It returns the element object with the specified ID attribute, which you can then store in a variable for repeated use. Critical details to remember:

  • The ID parameter must be passed as a string (in quotes)
  • IDs are case-sensitive and must match exactly
  • The method returns null if no matching element exists
  • The capitalization of ById must be exact for the method to function
  • Press Return (Mac) or Enter (Windows) to execute the command.
  • You should see <img id="product-photo" src="img/chair-beige.jpg"> returned in the Console. This represents the actual DOM element object.

    Hover over this output and notice that only the product image highlights in the webpage. You've successfully selected a specific element from the page structure. Now you can access and modify this element's properties using dot notation.

  • Press the Up Arrow key in the Console to recall your previous command. This keyboard shortcut saves significant time during development by avoiding repetitive typing.
  • Modify the command by appending the following code:

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

    This command demonstrates CSS property manipulation through JavaScript. You're accessing the element's style object and setting its display property to 'none', which will hide the element completely. Note that CSS property values must always be strings in JavaScript.

  • Execute the command and watch the product image disappear instantly. This real-time manipulation demonstrates JavaScript's power to modify page content dynamically without requiring a page reload.
  • Let's restore the image using the same technique. Press the Up Arrow key to recall your last command.
  • Modify the display value as shown:

    document.getElementById('product-photo').style.display = 'block';
  • Execute the command to restore the image visibility.

    These Console experiments provide immediate feedback and are invaluable for testing code snippets before implementing them in your actual JavaScript files. While Console changes are temporary (they reset when you refresh the page), this testing approach prevents errors in your production code.

    Keep this browser tab open—you'll need to reload the page to test the permanent code changes you'll make next.

  • Getting & Setting Properties

    The current product display shows a chair in beige, with additional color swatches representing available alternatives. However, clicking these swatches currently produces no response. Your goal is to create an interactive system where users can click any color swatch to instantly update the product image.

    While complete interactivity requires event handling functions (covered in upcoming lessons), this exercise focuses on the underlying property manipulation mechanics. You'll learn to programmatically change images and update visual indicators—skills that form the foundation of dynamic user interfaces.

    1. Return to product.html in your code editor to examine the HTML structure.
    2. Locate and study this HTML section:

      <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. Analyze the structural relationships:

      • Four button elements serve as color swatches for user interaction
      • Each button has a unique id corresponding to its color: beige, yellow, blue, and red
      • The product image has the ID product-photo for JavaScript targeting
      • The default image source is chair-beige.jpg, matching the initially selected swatch
      • Notice that the beige button includes a selected class, indicating the current choice
    4. In your code editor's file explorer, navigate to the img folder to examine the available assets.

      You'll find four product images with a consistent naming convention that directly corresponds to the button IDs:

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

      This naming consistency is a professional best practice that simplifies dynamic image swapping in JavaScript.

    5. In product.html, add a script tag in the document head, just before the closing </head> tag:

      <script></script>
      </head>
    6. Inside the script tag, create a variable to reference the product photo element:

      <script>
         let productPhoto = document.getElementById('product-photo');
      </script>

      Using descriptive variable names like productPhoto makes your code self-documenting and easier to maintain as projects grow in complexity.

    7. Add a second line to change the image source dynamically:

      <script>
         let productPhoto = document.getElementById('product-photo');
         productPhoto.src = 'img/chair-red.jpg';
      </script>

      This demonstrates direct property manipulation—you're changing the src attribute of the image element through JavaScript.

    8. Save your changes and reload the page in the browser.

      If nothing happens, don't worry—this is a common development scenario that teaches an important lesson about script execution timing. Let's diagnose the issue using the Console:
      • Ctrl+click (Mac) or Right-click (Windows) on the page and select Inspect
      • Click the Console tab in DevTools
      • You should see an error message indicating that the script couldn't find the element. Here's why:

        Browsers parse HTML sequentially from top to bottom. When your JavaScript executes in the <head> section, the HTML elements in the <body> haven't been created yet. Your script attempts to select an element that doesn't exist at execution time, causing the operation to fail.

        This timing issue is fundamental to web development. The solution is to ensure all DOM elements exist before JavaScript attempts to manipulate them.

    9. Switch back to your code editor to resolve this timing issue.
    10. Cut the entire <script> tag and its contents from the head section.
    11. Paste the script tag just above the closing </body> tag:

      <script>
            let productPhoto = document.getElementById('product-photo');
            productPhoto.src = 'img/chair-red.jpg';
         </script>
      </body>

      This placement ensures that all HTML elements are fully parsed and available before your JavaScript executes—a standard best practice in web development.

    12. Save and reload the page in your browser.

      Success! The product photo should now display the red chair instead of the default beige version. This demonstrates successful image source manipulation through JavaScript.

      Note that this is still a hard-coded change rather than a dynamic response to user interaction. You'll implement user-driven interactivity in subsequent exercises.

    13. Next, let's enhance the user interface by providing visual feedback about the selected color. Each swatch button should indicate when it's the active selection.

    14. Back in your code editor, add code to select the red button and modify its appearance:

      <script>
         let productPhoto = document.getElementById('product-photo');
         let colorButton = document.getElementById('red');
      
         productPhoto.src = 'img/chair-red.jpg';
         colorButton.style.borderColor = 'lime';
      </script>

      This approach demonstrates direct CSS manipulation through JavaScript's style object, setting the border color to provide immediate visual feedback.

    15. Save and reload the page to see the effect.

      The red button should now display a distinctive lime green border, clearly indicating the selected state.

    16. Let's examine how this change appears in the DOM. Ctrl+click (Mac) or Right-click (Windows) on the red button and select Inspect.

      In the DevTools Elements panel, notice that the button now has an inline style attribute containing the lime border CSS. While this approach works, it's not considered a professional best practice for larger applications.

    17. Let's implement a more maintainable approach using CSS classes. Modify your JavaScript as shown:

      <script>
         let productPhoto = document.getElementById('product-photo');
         let colorButton = document.getElementById('red');
      
         productPhoto.src = 'img/chair-red.jpg';
         colorButton.classList.add('selected');
      </script>

      The classList.add() method adds a CSS class to the element without overwriting existing classes. This approach separates styling concerns from JavaScript logic.

    18. Save and reload the page to observe the improved implementation.

      • The red button should now display a black border, styled by the pre-existing selected class in your CSS file.

      • Inspect the button element again and notice that it now has the selected class instead of an inline style attribute. This cleaner approach reflects professional development standards.

      This class-based approach offers several advantages: CSS designers can modify styling without touching JavaScript code, multiple CSS properties can be controlled with a single class addition, and the separation of concerns makes your codebase more maintainable as it scales.

    Project File Structure

    Color Swatches
    4
    Product Images
    4
    Button IDs
    4

    CSS Class vs Inline Style Approach

    FeatureclassList.add()style.property
    Code MaintainabilityHigh - CSS separateLower - Mixed concerns
    Developer CollaborationEasy for CSS devsRequires JS knowledge
    Multiple PropertiesOne line of codeMultiple JS lines
    PerformanceBetter - cached CSSDirect DOM updates
    Recommended: Use classList.add() for better maintainability and team collaboration
    Script Placement Critical Error

    JavaScript in the head section fails because it executes before HTML elements are created. Always place scripts at the bottom of the body for reliable element access.

    Property Manipulation Implementation

    1

    Element Storage

    Store selected elements in variables using let productPhoto = document.getElementById('product-photo')

    2

    Property Updates

    Modify properties like productPhoto.src = 'img/chair-red.jpg' to change image sources

    3

    Class Management

    Use classList.add('selected') to apply pre-defined CSS classes for styling

    Key Takeaways

    1GetElementById() method requires exact capitalization and returns HTML elements as objects that can be stored in variables
    2JavaScript execution order matters - place scripts at the bottom of the body to ensure all HTML elements exist before manipulation
    3Chrome DevTools Console provides an interactive environment for testing DOM manipulation code before implementing it permanently
    4Element properties can be modified using dot syntax, including src for images, style properties for CSS, and classList for class management
    5Using classList.add() is preferred over direct style manipulation for better code maintainability and team collaboration
    6The Up Arrow key in Console recalls previous commands, making iterative testing more efficient during development
    7Proper file structure with matching IDs and filenames enables dynamic content switching based on user interactions
    8DevTools element inspector helps identify specific HTML elements and their IDs for precise JavaScript targeting

    RELATED ARTICLES