DOM Manipulation in 2026 — Modern Techniques and Best Practices

Learn how to manipulate the DOM efficiently: selecting elements, event delegation, animations, and performance optimization.

JavaScript Beginner 📖 9 min

Selecting Elements

const header = document.querySelector('#header');
const buttons = document.querySelectorAll('.btn');
const link = document.querySelector('[data-tooltip="Info"]');
const activeItems = document.querySelectorAll('.list-item.active');

Creating and Inserting Elements

const card = document.createElement('div');
card.className = 'card';
card.innerHTML = `
  <h3>New Card</h3>
  <p>Created with JavaScript</p>
`;

document.querySelector('#container').appendChild(card);

// Modern: insertAdjacentHTML
container.insertAdjacentHTML('beforeend', '<p>New paragraph</p>');

Event Delegation

const list = document.querySelector('#todoList');
list.addEventListener('click', (event) => {
  if (event.target.matches('.delete-btn')) {
    event.target.closest('li').remove();
  }
  if (event.target.matches('li')) {
    event.target.classList.toggle('completed');
  }
});

Performance Tips

// BAD: Multiple DOM queries
for (let i = 0; i < 100; i++) {
  document.querySelector('.item').style.color = 'red';
}

// GOOD: Query once, reuse
const item = document.querySelector('.item');

// Use DocumentFragment for batch inserts
const fragment = document.createDocumentFragment();
for (const item of items) {
  const li = document.createElement('li');
  li.textContent = item;
  fragment.appendChild(li);
}
list.appendChild(fragment); // Single reflow

Ready to Level Up Your Coding Skills?

Join Coderz Club and learn to code with challenges, battles, and an AI mentor.

Join Coderz Club Free →