TechTalks
Chapter 3 of 3

DOM Manipulation

The DOM (Document Object Model) is a tree-like representation of your HTML page. JavaScript can read and modify the DOM to create dynamic, interactive web pages.

Selecting Elements

Selecting elementsjavascript
// Select by ID
const title = document.getElementById('main-title');

// Select first match (CSS selector)
const btn = document.querySelector('.btn-primary');

// Select ALL matches
const items = document.querySelectorAll('.list-item');

Modifying Elements

Changing content and stylesjavascript
const title = document.querySelector('h1');

// Change text
title.textContent = 'New Title';

// Change HTML
title.innerHTML = 'New <em>Title</em>';

// Change styles
title.style.color = '#6366f1';
title.style.fontSize = '2rem';

// Toggle classes
title.classList.add('highlighted');
title.classList.toggle('active');

Event Listeners

Handling clicksjavascript
const button = document.querySelector('#submit-btn');

button.addEventListener('click', (event) => {
  event.preventDefault();
  console.log('Button clicked!');
});

// Remove listener
const handler = () => console.log('clicked');
button.addEventListener('click', handler);
button.removeEventListener('click', handler);

Creating Elements

Creating and appending elementsjavascript
// Create a new element
const card = document.createElement('div');
card.className = 'course-card';
card.innerHTML = `
  <h3>New Course</h3>
  <p>Learn something new today!</p>
`;

// Add it to the page
document.querySelector('#course-list').appendChild(card);

In modern frameworks like React and Next.js, you rarely manipulate the DOM directly — the framework handles it. But understanding the DOM is essential for debugging and foundational knowledge.