Find elements and respond to events
Use DOM methods to update a page when someone acts.
- Select an element with querySelector
- Change textContent and classList
- Attach an event listener without inline JavaScript
A selector finds an element in the DOM. document.querySelector("#message") finds the first matching element or returns null. A browser event is a signal such as a click, input or submit. Pass a function to addEventListener; the browser calls it later when the event happens.
1const button = document.querySelector("#reveal");
2const message = document.querySelector("#message");
3button.addEventListener("click", () => {
4 message.textContent = "Your order is ready";
5 message.classList.add("visible");
6});In a real checkout, the HTML might contain <button id="reveal">Show status</button> and <p id="message" role="status"></p>. CSS can style .visible. Use textContent for user supplied text: it treats text as text instead of interpreting it as HTML. Check that a selected element exists before using it on pages where the markup can differ.
Try it
Up to 15 XPTrace the click
Follow a click from the person through the browser event, JavaScript handler and DOM update. Predict the next message before revealing it.
Key takeaways
Find elements with querySelector and handle a possible null result.
addEventListener registers a callback for a future event.
Use textContent for untrusted text and classList for CSS state.
Lesson quiz
2 questions · pass with 2 correct · up to 50 XP
Passing this quiz completes the lesson and keeps your streak going. Questions you miss come back in review sessions later.
Practice: write JavaScript
Write the program, run it against the test cases, and use the feedback to build your JavaScript skills.
Wire a click counter
The starter creates a button and a status paragraph in the isolated exercise page. Add a click listener to the button that increments count and updates the paragraph with Clicks: N. The test simulates the number of clicks in input and prints the paragraph text.
- Three clicks
- No clicks
JavaScript runs in a sandboxed browser frame with a 1.5 second time limit. Input is available as the string variable input.
Questions about this lesson
Stuck? Ask. Figured something out? Share it. Explaining is one of the best ways to learn.
Loading posts…