Michael Ouroumis logoichael Ouroumis
← Back to course

DOM Manipulation & Events

Learn how to select, update, and respond to user interactions in the browser DOM.

Lesson Objectives

By the end of this lesson, you will be able to:

  1. Select elements with document.querySelector and querySelectorAll.
  2. Change element content, attributes, and styles.
  3. 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:

  1. Create a <select> with options for a few colors (red, green, blue).
  2. Create a <div id="preview"> that shows a square.
  3. 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

  1. How do textContent, innerHTML, and value differ when you update elements?
  2. Why is event delegation useful for many similar elements?
  3. 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.

Try It Yourself

// 1. grab elements
const select = document.getElementById('colorSelect')
const range = document.getElementById('opacityRange')
const preview = document.getElementById('preview')

// 2. update function
function updatePreview() {
  const color = select.value
  const opacity = range.value
  preview.style.backgroundColor = color
  preview.style.opacity = opacity
}

// 3. add listeners
select.addEventListener('change', updatePreview)
range.addEventListener('input', updatePreview)

// 4. initial render
updatePreview()