← JavaScript tutorial

JavaScript

DOM Manipulation

The DOM (Document Object Model) is the browser's live, in-memory representation of the page. document.getElementById() finds an element; once you have it, you can change its content, its style, or attach an event listener so it reacts to user interaction.

Example: a counter that reacts to clicks

<button id="btn">Click me</button>
<p id="output">Button not clicked yet.</p>

<script>
  let clicks = 0;
  document.getElementById("btn").addEventListener("click", function () {
    clicks++;
    document.getElementById("output").textContent = "Clicked " + clicks + " time(s).";
  });
</script>

.addEventListener("click", ...) attaches a function that runs every time that specific element is clicked — nothing happens until the click actually occurs; the function just waits, registered and ready. This is the fundamental mechanism behind essentially every interactive element on the web: a listener waiting for an event, and a function that runs in response to update the page. Everything from a "like" button to a full single-page app is built from more elaborate versions of this exact same pattern.

Try it yourself