CodeMasteryLab
Section 10

DOM Manipulation & Events

Real-world DOM skills — selecting, creating, modifying elements, event handling, delegation, and performance best practices.

DOM Manipulation & Events

DOM and events are the foundation of frontend development and are heavily tested in practical rounds.

Selecting Elements

document.getElementById('id');
document.querySelector('.class');
document.querySelectorAll('div.card'); // NodeList

Creating & Modifying Elements

const div = document.createElement('div');
div.className = 'card';
div.textContent = 'Hello'; // safe (no XSS)
div.innerHTML = '<span>Hello</span>'; // careful with user input!
document.body.appendChild(div);

Event Handling

btn.addEventListener('click', handler);
btn.removeEventListener('click', handler);

// Event object
btn.addEventListener('click', (e) => {
  e.preventDefault();  // prevent form submit / link navigation
  e.stopPropagation(); // stop bubbling
  console.log(e.target); // element clicked
});

Event Delegation

// Instead of attaching listener to every li:
document.querySelector('ul').addEventListener('click', (e) => {
  if (e.target.tagName === 'LI') {
    console.log('Clicked:', e.target.textContent);
  }
});

Event delegation is memory-efficient and handles dynamically added elements.