DOM Button Click Listener and Event Target
Easy · Software Engineering Fundamentals · Software Engineer · Technical Screen
Prompt
Suppose a web document contains an HTML <button> element identified by id="my-button". Write client-side JavaScript using document.querySelector and addEventListener that responds to every activation of that button by printing the button's visible label text via console.log. In addition, explain what e.target points to inside your event callback and when it can differ from the <button> element itself.
Scope & Expectations
- Select
#my-buttonsafely withdocument.querySelectorafter the DOM has been parsed, and attach a'click'callback withaddEventListener. - Read and log clean button text while handling surrounding whitespace in multi-line HTML markup.
- Clearly distinguish
e.targetfrome.currentTargetunder DOM event bubbling, including what happens when the button contains nested child elements such as an icon<span>.
Step-by-step walkthrough
Understand the goal and the HTML setup
When a browser loads an HTML page, it builds the DOM (Document Object Model): an in-memory tree of JavaScript objects where every HTML tag (
<button>,<span>,<body>) is a node your code can find and interact with.Suppose the page has this markup:
<button id="my-button">Publish</button> <script src="app.js" defer></script>Our client-side script needs three pieces:
- Grab the
#my-buttonDOM node viadocument.querySelector. - Subscribe a
'click'callback withaddEventListener. - Print the trimmed button label via
console.logand clarify howe.targetbehaves relative toe.currentTarget.
- Grab the
Find the button with document.querySelector
A CSS selector is a short pattern string (the same syntax used in stylesheets) that describes which HTML elements to match:
'button'matches a tag name,'.primary'matches a class, and'#my-button'matchesid="my-button".document.querySelector(selector)walks the DOM in document order and returns the first matching element, ornullif nothing matches:// The leading '#' is essential: 'my-button' without '#' searches for a <my-button> tag! const button = document.querySelector('#my-button');Two real-world habits prevent
"Cannot read properties of null"crashes here:- Run after the HTML is parsed: If a plain
<script src="app.js"></script>sits inside<head>withoutdefer, it executes before the browser has read<body>, so#my-buttondoes not exist yet andquerySelectorreturnsnull:text Without defer in <head>: parse <head> -> run app.js (button is null!) -> parse <button> With defer in <head>: parse <head> -> parse <button> -> DOM ready -> run app.js (found!)Addingdefer(or<script type="module">, placing<script>right before</body>, or wrapping code indocument.addEventListener('DOMContentLoaded', ...)) guarantees the button is in the DOM first. - Guard against missing elements: Checking
if (button)keeps shared scripts safe on pages that do not include#my-button.
- Run after the HTML is parsed: If a plain
Register a click listener with addEventListener
An event listener (also called a callback) is a function you hand to the browser so the browser can call it later whenever a specific user action occurs.
button.addEventListener('click', listener)subscribes your function to'click'events on that button and passes anEventobject (e) into your function on each click:button.addEventListener('click', (e) => { // Runs every time the user activates the button });Why
addEventListeneris much better than older alternatives:- Multiple listeners coexist peacefully: Assigning
button.onclick = handlerBoverwritesbutton.onclick = handlerA. CallingaddEventListenerappends to an internal list so analytics, UI feedback, and business logic all run without stepping on one another. - Built-in lifecycle options: A third argument supports
{ once: true }(auto-remove after one click),{ signal }(cleanly cancel via anAbortController), and{ capture: true }. - Clean separation and security: Inline
<button onclick="...">mixes JavaScript into HTML markup and is blocked by strict Content Security Policies (CSP). - Built-in keyboard accessibility: Because the element is a native
<button>(not a<div>), browsers automatically fire the exact same'click'event when a keyboard user focuses the button and pressesEnterorSpace.
- Multiple listeners coexist peacefully: Assigning
Read and clean the button's textContent
Every DOM element exposes
textContent, which returns the raw text inside that element and all of its descendants without parsing HTML tags. (Its cousininnerTextcomputes CSS visibility and layout reflow — forcing the browser to recalculate element geometry — sotextContentis faster and standard when you simply want the element's text.)One small trap is multi-line HTML indentation:
<button id="my-button"> Publish </button>Look at the exact characters
textContentreads from that markup:Raw textContent: "\n Publish\n" (1 newline + 2 spaces + 7 letters + 1 newline = 11 chars) textContent.trim(): "Publish" (leading and trailing whitespace stripped = 7 chars)Calling
.trim()strips surrounding spaces and newlines while leaving inner spaces (like"Publish Draft") intact.What e.target means (and how it differs from e.currentTarget)
When you click on a page, event bubbling means the click event starts on the deepest element directly under your pointer and then travels upward from parent to parent (
<span> -> <button> -> <body> -> document -> window), triggering any click listeners along the way.Inside your listener
(e) => { ... }, the event objectecarries two element references that look similar at first glance:e.target: the innermost element where the click actually originated. It stays the same as the event bubbles up the DOM tree.e.currentTarget: the element whose event listener is currently running — here, always<button id="my-button">.
See what happens in two different HTML cases:
Case A: Plain text inside the button HTML: <button id="my-button">Publish</button> Click on "Publish" (text nodes cannot be event targets, so the target is the <button>): e.target -> <button id="my-button"> e.currentTarget -> <button id="my-button"> e.target.textContent.trim() -> "Publish" (matches!) Case B: Button contains a child icon <span> HTML: <button id="my-button"><span class="icon">*</span> Publish</button> <button id="my-button"> <-- listener attached here (e.currentTarget) |-- <span class="icon">*</span> <-- user's mouse clicks right on the star (e.target) +-- " Publish" Click directly on the star: e.target -> <span class="icon"> e.target.textContent.trim() -> "*" (WRONG: missed "Publish"!) e.currentTarget -> <button id="my-button"> e.currentTarget.textContent.trim() -> "* Publish" (RIGHT: always reads the whole button!)So in this question's context: -
e.targetrefers to the specific DOM element that received the click — which is<button id="my-button">itself if the button only contains plain text, or a nested child element (like an icon<span>or<svg>) if the button has children and the click lands on that child. - Readinge.currentTarget.textContent.trim()(orbutton.textContent.trim()) guarantees you always log the button's full text content even if child elements are added later.Complete JavaScript solution and how to verify it
Putting everything together cleanly:
// Loaded after the DOM is parsed (e.g. <script src="app.js" defer></script>) const button = document.querySelector('#my-button'); if (button) { button.addEventListener('click', (e) => { // e.target is the innermost clicked element (the button itself if it has no child tags, // or a child like <span> if the user clicked an icon inside the button). // e.currentTarget is always the element this listener was attached to (#my-button). console.log(e.currentTarget.textContent.trim()); }); }(Note: for a plain
<button id="my-button">Publish</button>with no child tags,console.log(e.target.textContent.trim())prints the exact same"Publish", becausee.target === button.)How to verify your solution in three quick checks: 1. Mouse click: Open the page and browser DevTools Console, click the button, and confirm
Publishis printed once per click. 2. Keyboard activation: PressTabuntil#my-buttonis focused, then pressEnterorSpace—Publishlogs again. 3. Nested child element: Temporarily change the markup to<button id="my-button"><span>*</span> Publish</button>and click directly on*—e.currentTarget.textContent.trim()still logs* Publishrather than just*.
Intuition & how it works
Think of the browser's DOM (Document Object Model) — the in-memory tree of objects representing every HTML tag on the page — as an office building directory, and addEventListener as leaving a callback number at a specific room (#my-button) with instructions: "Whenever someone knocks ('click'), run this function and hand me a report (e) about the knock."
Simpler-looking shortcuts break down quickly in real web pages. Writing onclick="..." directly inside HTML mixes logic into markup and is blocked by modern Content Security Policies, while assigning button.onclick = fn silently overwrites any click listener registered earlier by another script. Forgetting the # in querySelector('my-button') or running the script before the HTML finishes parsing returns null and crashes immediately, and reading e.target.textContent blindly logs the wrong text the moment someone places an icon <span> inside the button.
Walk through a concrete 4-step trace on <button id="my-button">\n Publish\n</button>:
- Parse: The browser parses the HTML into DOM nodes, creating the
<button>withid="my-button". - Select & subscribe: The deferred script runs
document.querySelector('#my-button')to grab that button node and callsaddEventListener('click', handler)to subscribe to clicks. - Dispatch: The user clicks
"Publish"; the browser creates a click event objectewhere bothe.target(where the click started) ande.currentTarget(where our listener lives) point to<button id="my-button". - Log: Inside the listener,
e.currentTarget.textContentreads the 11 raw characters"\n Publish\n",.trim()removes the surrounding whitespace to leave"Publish"(7 characters), andconsole.logprintsPublish.
Key points
- CSS selector lookup: A CSS selector is a pattern string that matches HTML elements;
document.querySelector('#my-button')uses#to matchid="my-button"and returns the element ornull. Ensure the DOM exists first via<script defer>,<script type="module">, placing the script at the end of<body>, orDOMContentLoaded. addEventListeneradvantages: An event listener is a callback function invoked when an event fires. Unlikebutton.onclick = ...,addEventListener('click', fn)allows multiple independent listeners on the same button and supports options like{ once: true }and{ signal }.e.targetvse.currentTarget: Because of event bubbling (events start on the deepest clicked element and travel upward through ancestor elements),e.targetis the innermost element actually clicked, whilee.currentTargetis always the element the listener was attached to (#my-button). When the button has no child elements,e.targetande.currentTargetare identical; when it contains<span class="icon">*</span>, clicking the icon makese.targetthe<span>whilee.currentTargetremains the<button>.textContent.trim():textContentreads raw text without triggering a costly layout reflow (recalculating visual styles and positions, whichinnerTextcan force), and.trim()cleans up newlines and indentation from multi-line HTML.- Native
<button>accessibility: Using<button>instead of a styled<div>gives keyboard users (Tab+Enter/Space) the exact same'click'event automatically.
Common mistakes
- Omitting
#indocument.querySelector('my-button'): Without#, the browser searches for a custom<my-button>tag, getsnull, and throwsTypeError: Cannot read properties of null (reading 'addEventListener'). - Running
<script>in<head>withoutdefer: The script executes before<body>is parsed, so#my-buttonis not in the DOM yet andquerySelectorreturnsnull. - Passing
'onclick'instead of'click':addEventListener('onclick', fn)listens for a nonexistent event named"onclick"; no error is thrown, and clicks silently do nothing. - Calling the handler immediately (
addEventListener('click', logText())): The parentheses invokelogText()once during page load and pass its return value (undefined) as the listener instead of passing the functionlogTextitself. - Reading
e.target.textContenton buttons with icons or badges: Clicking a child<span>logs only that child's text instead of the whole button's label; usee.currentTarget.textContent.trim(). - Using
thisinside an arrow function(e) => { console.log(this.textContent); }: Arrow functions do not bindthisto the clicked element (thisinherits the outer scope, oftenwindow); usee.currentTarget. - Reading
e.currentTargetasynchronously afterawaitor insidesetTimeout: Per the DOM standard, the browser resetse.currentTargettonullas soon as synchronous event dispatch finishes — captureconst label = e.currentTarget.textContent.trim();before awaiting.
Follow-up questions
- How can you handle clicks across hundreds of dynamically rendered buttons without registering a separate listener on each one? Use event delegation, which attaches a single click listener to a stable parent container (like a
<ul>ordocument) and relies on event bubbling. Inside the listener, callconst btn = e.target.closest('button.item-action'); ifbtnis non-null, logbtn.textContent.trim(), which works automatically even for buttons inserted into the DOM later. - How do you detach an event listener cleanly during component teardown so closures do not leak memory? Either keep a reference to the exact same named function (
button.removeEventListener('click', handleClick)— passing two separate inline arrow functions will not match!) or pass anAbortControllersignal viabutton.addEventListener('click', fn, { signal: controller.signal })and callcontroller.abort()on teardown to detach one or many listeners at once. - How do preventDefault and stopPropagation differ when handling a button click inside an HTML form?
e.preventDefault()cancels the browser's built-in default action (for example, stopping a<button>inside a<form>— whose defaulttypeis"submit"— from reloading the page), while still letting the event bubble upward.e.stopPropagation()stops the event from bubbling to parent listeners, while still allowing the browser's default form submission to happen unless prevented.
Follow-up questions
- How can you handle clicks across hundreds of dynamically rendered buttons without registering a separate listener on each one?
- How do you detach an event listener cleanly during component teardown so closures do not leak memory?
- How do preventDefault and stopPropagation differ when handling a button click inside an HTML form?
Similar questions
- Versioned In-Memory Recipe Store
- Navigating a Data Science Internship Behavioral Screen
- Ten-Pin Bowling Score Calculator
- Conversion Probability Modeling for Real-Time Ad Auctions
- Quota-Aware In-Memory File Store
- Piecewise-Linear Interpolation on Sorted Arrays
More The Trade Desk interview questions
- Navigating a Data Science Internship Behavioral Screen Easy
- Ten-Pin Bowling Score Calculator Medium
- Conversion Probability Modeling for Real-Time Ad Auctions Easy Pro
- Versioned In-Memory Recipe Store Medium Pro
- Quota-Aware In-Memory File Store Medium Pro
- Piecewise-Linear Interpolation on Sorted Arrays Easy Pro