JavaScript DOM Manipulation
How JavaScript changes what you see on the page, live.
What is the DOM?
The DOM (Document Object Model) is a tree-like representation of your HTML page that JavaScript can read and modify. Every element becomes a 'node' you can select and change.
Selecting Elements
You typically select elements using methods like document.getElementById() or document.querySelector(), then change their content, style, or attributes.
const title = document.querySelector('h1');
title.textContent = 'Updated by JS!';
title.style.color = 'green';Handling Events
Events like clicks, key presses, and form submissions let your page respond to user interaction. You attach a function to an event using addEventListener, which runs whenever that event happens.
button.addEventListener('click', () => {
alert('Button clicked!');
});đ Real-World Use
When you 'like' a post and the heart icon instantly turns red without the page reloading, that's DOM manipulation â JavaScript directly updated that one element instead of reloading the whole page.
đĄ Pro Tip
Avoid manipulating the DOM inside a loop repeatedly (e.g., updating the page 1000 times in a for-loop) â it's slow. Batch your changes and update the DOM once, or use a framework like React which optimizes this for you.
đ§Ē Quick Self-Test
Check what you just learned â no pressure, just practice.
1. What does the DOM represent?
2. Which method attaches a function to run on a click?