Log a Button's Label on Click with the DOM Event API
Data Structure DesignModel answerLast updated
Wire up a click handler on a page button that logs its label to the console, and explain what the event object's target property refers to, including nested-element cases.
A web page contains a single button whose id is my-button.
Write JavaScript that does the following:
- Finds the button using
document.querySelector. - Registers a click handler using
addEventListener. - When the button is clicked, writes the button's visible text to the console.
Then explain, in a few sentences, what e.target refers to inside your handler (where e is the argument passed to the callback).
In your answer, also cover:
- When the script must run relative to the page being parsed, so the button actually exists.
- What changes if the button contains child elements (for example an icon wrapped in a
<span>). - How you would make the code safe if the button might be missing.
Hints
Hint 1
`querySelector` accepts a CSS selector, so think about how an id is written in CSS.
Hint 2
The callback receives an event object. Compare the element where the event started with the element the listener is attached to.
Hint 3
Consider what happens when the script executes before the button has been parsed, and when the button contains nested markup.
Model answer
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The task tests whether you understand how the browser's event model works: selecting an element, attaching a listener, and reading the event object. Give working code first, then show depth on the details.
- Select the element with
document.querySelector('#my-button'). The argument is a CSS selector, so the id needs the#prefix. Forgetting it ('my-button') searches for a<my-button>tag and returnsnull. - Attach the handler with
addEventListener('click', handler). Compared with assigningonclick, this allows several listeners on one element and supports options such asonce,passiveandsignal. - Log the text from inside the handler.
Minimal solution
const button = document.querySelector('#my-button');
button.addEventListener('click', (e) => {
console.log(e.target.textContent);
});
More robust solution
document.addEventListener('DOMContentLoaded', () => {
const button = document.querySelector('#my-button');
if (!button) {
console.warn("No element with id 'my-button' found.");
return;
}
button.addEventListener('click', (e) => {
console.log(e.currentTarget.textContent.trim());
});
});
Changes from the minimal version:
- Waiting for
DOMContentLoaded(or loading the script withdefer, or placing it at the end of<body>) ensures the button exists when queried. - The null check avoids
TypeError: Cannot read properties of nullwhen the element is absent. currentTargetis used instead oftarget, andtrim()removes whitespace introduced by HTML formatting.
What e.target refers to
e is the event object (a MouseEvent for clicks) that the browser passes to the callback.
e.targetis the element where the event originated: the innermost element the user actually clicked.e.currentTargetis the element the running listener is attached to. Here, always the button.
For a plain <button>Submit</button> the two are identical and the log prints Submit.
They diverge when the button has children:
<button id="my-button"><span>★</span> Save</button>
If the user clicks the star, e.target is the <span>, so e.target.textContent is "★", not the whole label. The listener on the button still fires because of event bubbling: the event is dispatched at the span and then travels up through its ancestors. e.currentTarget (or this in a regular function handler) always gives the button, so it is the safer choice when you want the button's full text.
Why it works
querySelector('#my-button')returns the first match; ids should be unique, so that is the button.clickfires for mouse clicks, taps, and keyboard activation (Enter or Space on a focused button), so the behavior is accessible by default.textContentreturns the concatenated text of the element and its descendants with no markup.
Complexity
- Setup: attaching a listener is O(1). Selection by id is fast in practice, though
querySelectoris O(n) in the size of the DOM in the worst case. - Each click: O(k), where k is the size of the button's text content.
- Space: O(1), one closure and one element reference.
Edge cases and follow-ups
- Script runs too early. A script in
<head>withoutdeferruns before the button exists, soquerySelectorreturnsnull. Fix withdefer, script placement, orDOMContentLoaded. getElementById. An alternative that takes the bare id ('my-button', no#).textContentvsinnerText.innerTextis layout-aware (it respectsdisplay: none) and can trigger reflow;textContentreturns raw text and is cheaper.- Arrow functions and
this. Arrow functions do not bindthisto the element. Usee.currentTarget, or a regularfunctionif you wantthis. - Duplicate listeners. Running the setup twice with inline anonymous functions attaches two listeners and logs twice. The same named function reference passed twice is only registered once.
- Cleanup. Keep a named function to call
removeEventListener, or use{ once: true }or anAbortControllersignal. - Buttons inside forms. A
<button>defaults totype="submit"inside a<form>, so the click may also submit the form. Usetype="button"ore.preventDefault()if that is unwanted. - Dynamically created buttons. Use event delegation: attach one listener to a stable ancestor and test with
closest. This is the main real-world use ofe.target.
document.addEventListener('click', (e) => {
const btn = e.target.closest('#my-button');
if (btn) console.log(btn.textContent.trim());
});
Common mistakes
- Writing
querySelector('my-button')without#. - Querying the element before it exists in the DOM.
- Assuming
e.targetis always the button. - Using
thisinside an arrow function and getting the wrong value. - Forgetting that a button in a form can trigger a submit and page reload.
How to present it
State the code, define e.target in one sentence (the element that originated the event), then volunteer the nested-element caveat and the currentTarget fix. That short sequence shows you understand bubbling, not just the syntax.