DOM Manipulation
Interacting with the Page
The DOM (Document Object Model) is how JavaScript talks to HTML. Using DOM methods, you can select elements, change content and styles, create new elements, and respond to user actions - all without reloading the page.
The DOM is a puppet show. HTML is the puppets on stage. JavaScript is the puppeteer pulling strings. With DOM methods, you can make any puppet move, change costume, appear, disappear, or respond when the audience clicks them - live, without resetting the stage.
🔑 Key Concepts
getElementById, querySelector, querySelectorAll - pick any element like a CSS selector.
textContent, innerHTML, style, classList.add/remove/toggle - change what users see.
addEventListener responds to clicks, keypresses, form submits, and more user interactions.
💻 Code Examples
⚠️ Common Mistakes
Running DOM code before page loads
Put script at end of body, or use DOMContentLoaded event, or defer attribute on script tag.
Setting innerHTML with user input
Use textContent for plain text. Sanitize any HTML from user input to prevent XSS attacks.
querySelector returns null - not checked
Always check if querySelector returned null before using the result, or your code will crash.
📋 Quick Reference
Live Code Playground
Edit the code and press ▶ Run to see output instantly.