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

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
Setup Environment
Configure your development environment with proper folder structure and browser DevTools access
Element Selection
Master the GetElementById() method to target specific HTML elements in your webpage
Property Manipulation
Learn to modify element properties including images, styles, and CSS classes dynamically
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.
- 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.
- 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.
- Launch product.html in Chrome. We're specifically using Chrome because its DevTools provide the most comprehensive debugging and experimentation environment for JavaScript developers.
- 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.
- 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.
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.
- 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.
- 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.
- 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. 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/4Open Product-Chooser-DOM folder in code editorLocated in Desktop > Class Files > JavaScript Class directory
Preview product.html in Chrome browserChrome is required for DevTools functionality we'll be using
Access Chrome DevTools ConsoleRight-click page and select Inspect, then click Console tab
Test document object interactionType 'document' in Console to verify DOM access is working
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.
- In the DevTools window, locate and click the
element selector button in the top-left corner. This tool lets you click any page element to inspect its HTML. - Click directly on the product photo in the webpage. The DevTools will automatically highlight the corresponding HTML element.
- 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.
Switch to the Console tab to begin programmatic element selection.
In the Console, type:
document.getElementById('product-photo');Element Selection Best PracticeUse 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
nullif no matching element exists - The capitalization of ById must be exact for the method to function
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.
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.
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.
- Return to product.html in your code editor to examine the HTML structure.
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>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
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.
In product.html, add a script tag in the document head, just before the closing </head> tag:
<script></script> </head>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
productPhotomakes your code self-documenting and easier to maintain as projects grow in complexity.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.
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.
- Switch back to your code editor to resolve this timing issue.
- Cut the entire
<script>tag and its contents from the head section. 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.
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.
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.
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.
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.
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.
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.
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
CSS Class vs Inline Style Approach
| Feature | classList.add() | style.property |
|---|---|---|
| Code Maintainability | High - CSS separate | Lower - Mixed concerns |
| Developer Collaboration | Easy for CSS devs | Requires JS knowledge |
| Multiple Properties | One line of code | Multiple JS lines |
| Performance | Better - cached CSS | Direct DOM updates |
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
Element Storage
Store selected elements in variables using let productPhoto = document.getElementById('product-photo')
Property Updates
Modify properties like productPhoto.src = 'img/chair-red.jpg' to change image sources
Class Management
Use classList.add('selected') to apply pre-defined CSS classes for styling