Lesson Objectives
By the end of this lesson, you will be able to:
- Select elements with
document.querySelector
andquerySelectorAll
. - Change element content, attributes, and styles.
- Listen for and handle events (
click
,input
, etc.).
1. Selecting DOM Elements
// single element const header = document.querySelector('h1') // list of elements const buttons = document.querySelectorAll('button')
2. Modifying the DOM
const box = document.getElementById('box') // change text box.textContent = 'Hello, DOM!' // change style box.style.backgroundColor = 'lightblue' // set attribute box.setAttribute('data-state', 'active')
3. Handling Events
const button = document.getElementById('actionBtn') button.addEventListener('click', (event) => { alert('Button clicked!') })
You can also listen on inputs:
const input = document.getElementById('nameInput') input.addEventListener('input', (e) => { console.log('Current value:', e.target.value) })
Task: Build a Color Picker
In your index.js
:
- Create a
<select>
with options for a few colors (red
,green
,blue
). - Create a
<div id="preview">
that shows a square. - When the user changes the select value, update the
<div>
âs background to the chosen color.
Bonus: Add a second slider input (
<input type="range">
) to adjust the squareâs opacity.
Reflection
- How do
textContent
,innerHTML
, andvalue
differ when you update elements? - Why is event delegation useful for many similar elements?
- How can you remove an event listener when itâs no longer needed?
Next Steps: Explore localStorage
to save user preferences (e.g. last-picked color) so they persist between page reloads.