What is the DOM, and how does JavaScript change a web page?
When a browser loads an HTML page, it doesn't keep the HTML as text. It builds a tree of objects called the DOM (Document Object Model). Every element, attribute and piece of text becomes a node in that tree.
Why it matters: JavaScript doesn't edit your HTML file. It changes the DOM, and the browser updates what you see.
The basic things you'll do with the DOM:
- Find elements:
document.querySelector('.menu')gets the first matching element. - Change content: set
element.textContentto update text. - Change styles or classes:
element.classList.add('open')is usually cleaner than setting styles directly. - Create and add elements:
document.createElement('li')thenlist.append(item). - React to events:
button.addEventListener('click', handler).
Beginner tips:
- Make sure your script runs after the elements exist (use
deferon the script tag or place it at the end of the body). - Prefer
textContentoverinnerHTMLwhen inserting user-provided text, to avoid security issues. - Use the Elements panel in DevTools to see the live DOM, which can differ from your original HTML.
How frameworks fit in: React, Vue, Svelte and others still change the DOM; they just decide what to update for you based on your data.
What small DOM project helped you understand it best? A to-do list, a theme toggle, something else?
Comments · 2
Good intro. Worth adding that
querySelectorreturns the first match only, and the DOM is live, so changes show up on screen without reloading anything.Open dev tools and edit an element in the Elements panel. Seeing the page change is the moment it clicks for most people.