DOM Manipulation and Performance

Efficient DOM manipulation is crucial for web application performance. Understanding the best practices and common pitfalls can significantly improve user experience.

Basic DOM Operations

// Selecting elements
const element = document.getElementById('myId');
const elements = document.querySelectorAll('.myClass');
const parent = element.parentNode;
const children = element.children;

// Creating and adding elements
const div = document.createElement('div');
div.textContent = 'New Element';
parent.appendChild(div);

// Removing elements
element.remove();
parent.removeChild(element);

// Modifying elements
element.textContent = 'New text';
element.innerHTML = '<span>HTML content</span>';
element.setAttribute('class', 'newClass');
element.classList.add('active');

Performance Optimization

// Bad: Multiple DOM updates
for (let i = 0; i < 1000; i++) {
  container.innerHTML += '<div>' + i + '</div>';
}

// Good: Document Fragment
const fragment = document.createDocumentFragment();
for (let i = 0; i < 1000; i++) {
  const div = document.createElement('div');
  div.textContent = i;
  fragment.appendChild(div);
}
container.appendChild(fragment);

// Better: Build HTML string
const html = Array.from({ length: 1000 }, 
  (_, i) => '<div>' + i + '</div>'
).join('');
container.innerHTML = html;

Event Handling

// Event delegation
document.getElementById('list').addEventListener('click', e => {
  if (e.target.matches('li')) {
    handleClick(e.target);
  }
});

// Debouncing events
function debounce(fn, delay) {
  let timeoutId;
  return function (...args) {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => fn.apply(this, args), delay);
  };
}

// Usage
const handleScroll = debounce(() => {
  // Handle scroll event
}, 100);

window.addEventListener('scroll', handleScroll);

Common Interview Follow-up Questions

  1. What is reflow and repaint?
  2. How do you optimize DOM updates?
  3. What's the difference between textContent and innerHTML?
  4. How does event bubbling affect performance?

Best Practices

  • Minimize DOM updates
  • Use document fragments for batch updates
  • Implement event delegation
  • Cache DOM queries
  • Be careful with innerHTML for security
  • Use modern APIs like IntersectionObserver