Interacting with the DOM

The Document Object Model (DOM) represents the page as a tree of nodes. You can query elements, listen for events, and modify the page structure or content on the fly.

// Select elements
const button = document.querySelector('button');
const items = document.querySelectorAll('.item');

// Event handling
button.addEventListener('click', () => {
  items.forEach(item => item.classList.toggle('active'));
});

// Creating elements
const newItem = document.createElement('li');
newItem.textContent = 'New Item';
document.querySelector('ul').appendChild(newItem);

// Updating elements
const heading = document.getElementById('main-heading');
heading.textContent = 'Updated Title';

Key Methods

  • querySelector, querySelectorAll — select elements using CSS selectors
  • getElementById, getElementsByClassName — legacy selection methods
  • addEventListener — attach event listeners to elements
  • createElement, appendChild, removeChild — dynamically add or remove nodes
  • textContent, innerHTML — update element content