GGistDev

DOM Basics in JavaScript

Interact with the Document Object Model to read and update the page and respond to user events.

Selecting elements

Use modern query APIs.

document.getElementById('id')
document.querySelector('.btn')
document.querySelectorAll('li') // NodeList

Reading and writing

const el = document.querySelector('#title')
el.textContent = 'Hello'        // safe text
el.innerHTML = '<em>Hi</em>'    // parse as HTML (avoid with untrusted input)
el.classList.add('active')
el.setAttribute('aria-label', 'title')

Creating and inserting

const li = document.createElement('li')
li.textContent = 'Item'
document.querySelector('ul').append(li) // or prepend, before, after

Events

Add listeners and remove when done.

function onClick(e) { console.log('clicked', e.target) }
const btn = document.querySelector('button')
btn.addEventListener('click', onClick)
// btn.removeEventListener('click', onClick)

Use event delegation for lists/grids.

document.addEventListener('click', e => {
  if (e.target.matches('.item')) { /* ... */ }
})

Layout and performance

Batch DOM writes/reads; avoid layout thrash. Use requestAnimationFrame for visual updates and IntersectionObserver for lazy loading.

Summary

  • Use query selectors, classList, and attributes for manipulation
  • Create elements with createElement; append efficiently
  • Add/remove event listeners; delegate for dynamic lists