Lesson 12 of 18

DOM Manipulation 📄

🎯 Grades 9–12 ⏱ ~35 minutes 💚 Intermediate

What You'll Learn

  • Select HTML elements with JavaScript
  • Change element text and styles
  • Create and remove elements

What Is the DOM?

The DOM (Document Object Model) is how JavaScript sees your HTML. Every element on your page is an object in the DOM tree that JavaScript can read and change.

JavaScript
// Select elements
const heading = document.getElementById('main-title');
const para = document.querySelector('p');        // first p
const allCards = document.querySelectorAll('.card'); // all .card

// Read
console.log(heading.textContent);  // get text
console.log(heading.innerHTML);    // get HTML inside

// Write
heading.textContent = 'New Heading Text';
para.innerHTML = 'Text with <strong>bold</strong> inside';

Changing Styles

JavaScript
const box = document.getElementById('myBox');

// Inline styles
box.style.backgroundColor = '#00C853';
box.style.fontSize = '24px';

// Better: toggle classes
box.classList.add('active');
box.classList.remove('hidden');
box.classList.toggle('dark-mode');  // add if absent, remove if present
console.log(box.classList.contains('active')); // true
💡
Use Classes!

Changing classes is cleaner than setting inline styles. Define the .active, .hidden styles in your CSS — then just toggle classes with JavaScript.

Creating Elements

JavaScript
// Create a new element
const newCard = document.createElement('div');
newCard.classList.add('card');
newCard.textContent = 'I was created by JavaScript!';

// Add to the page
document.getElementById('grid').appendChild(newCard);
📄">Dynamic Content

Add a button to your HTML. When clicked (add onclick='changeContent()' for now), have JavaScript change the page heading text and background color. You are making a page interactive!

Quick Check

What does document.querySelector('.card') return?

AAll elements with class card
BThe first element with class card
CAn error if none exist

What does classList.toggle('dark') do?

AAdds dark class permanently
BRemoves the dark class if present, adds it if absent
CSets the class to dark always

What is the DOM?

AA CSS property
BJavaScript's representation of the HTML page as objects
CA type of database