Lesson 12 of 18
DOM Manipulation 📄
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')); // trueUse 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?
What does classList.toggle('dark') do?
What is the DOM?