Lesson · JavaScript Basics
Select elements and respond to events
Browser JavaScript can connect user actions to meaningful changes in a document.
What you will learn
- Select an element with querySelector
- Register a click handler
- Update text safely
The document object model
In a browser, document represents the parsed page as a tree of nodes. Methods such as querySelector find an element using a CSS selector. This API does not exist in a plain Node process unless a page-like environment is provided, so run this example from an HTML page.
Listen for an event
An event listener registers a function that should run when an event occurs, such as a button click. The browser calls the function in response to the action; registering the listener does not itself perform the action. Keep the handler small and focused on the resulting state change.
Update text safely
textContent replaces an element's text without parsing it as HTML. This is a good default when displaying a value supplied by a user or another source. Avoid inserting untrusted text with innerHTML, which asks the browser to parse it as markup and can create security problems.
Make the page meaningful
A control should have a visible label and keyboard behavior appropriate to its purpose. A real button supports keyboard activation, unlike a generic span with a click handler. The message should remain understandable when the user does not see color or animation.
Keep selection and behavior testable
A selector should match the markup the page actually serves. If a script is reused on pages without the button, handle a missing element deliberately before adding a listener. For dynamic lists, event delegation can reduce listeners, but begin with one clear listener and confirm the interaction with a keyboard as well as a pointer.
const button = document.querySelector('#greet-button');
const message = document.querySelector('#message');
button.addEventListener('click', () => {
message.textContent = 'Hello, learner!';
});
Practice exercise
Add a button and an empty paragraph to an HTML page; update the paragraph when the button is clicked.
Show a hint
Give each element an id that matches the selectors in the example.
Show one possible solution
Use a button with id='greet-button', a paragraph with id='message', and load the script after those elements or after the document has parsed.
Quick check
textContent treats the value as text, which is appropriate for a plain message.