JSTAcademy
0 XP
Dashboard
Crash Courses
DOM Manipulation & Events
10 min
Basic+150 XP
Crash Courses · Basic

DOM Manipulation & Events

Select, modify, and respond to user interactions in the browser DOM directly.
10 min read+150 XP on completionCert: JavaScript Crash Course
Tap any word in the text below to start reading from there.

DOM Manipulation & Events

React abstracts the DOM, but understanding it separates developers who can debug at any level from those who are lost without a framework.

Selecting Elements

const btn = document.querySelector('#submit')
const nav = document.querySelector('nav.primary')
const cards = document.querySelectorAll('.card')
const arr = [...cards]  // spread NodeList to use array methods

const container = document.querySelector('.grid')
const items = container.querySelectorAll('.item')  // scope to container

Reading and Writing

element.textContent = 'Safe text'           // escapes HTML — use for user data
element.innerHTML = '<strong>Bold</strong>' // renders HTML — NEVER with user input (XSS)

element.setAttribute('aria-expanded', 'true')
element.dataset.id    // shortcut for data-id attribute

element.classList.add('active')
element.classList.remove('hidden')
element.classList.toggle('open')

input.value     // form input value
input.checked   // checkbox

Creating Elements

const card = document.createElement('div')
card.className = 'card'
card.textContent = title
parent.appendChild(card)
parent.prepend(card)    // at start
card.after(sibling)     // after existing node
card.remove()

Events

function handleClick(event) {
  event.preventDefault()           // stop form submit / link nav
  event.stopPropagation()          // stop bubbling
  console.log(event.target)        // element that triggered
  console.log(event.currentTarget) // element listener is on
}

btn.addEventListener('click', handleClick)
btn.removeEventListener('click', handleClick)  // same reference required
btn.addEventListener('click', handleClick, { once: true })  // auto-removes

Event Delegation

const list = document.querySelector('#product-list')

list.addEventListener('click', (e) => {
  const item = e.target.closest('[data-product-id]')
  if (!item) return
  handleProductClick(item.dataset.productId)
})

closest() walks up the DOM to find the nearest ancestor matching a selector essential when click lands on a child of the intended target.

Why This Matters for React

React's virtual DOM optimizes over these raw operations:

  • key props let React match DOM nodes during reconciliation
  • useRef gives you a direct DOM handle (ref.current = element)
  • React state updates are async batched then applied as minimal DOM mutations
0%