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-button safely with document.querySelector after the DOM has been parsed, and attach a 'click' callback with addEventListener.
  • Read and log clean button text while handling surrounding whitespace in multi-line HTML markup.
  • Clearly distinguish e.target from e.currentTarget under DOM event bubbling, including what happens when the button contains nested child elements such as an icon <span>.

Step-by-step walkthrough

  1. 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:

    1. Grab the #my-button DOM node via document.querySelector.
    2. Subscribe a 'click' callback with addEventListener.
    3. Print the trimmed button label via console.log and clarify how e.target behaves relative to e.currentTarget.
  2. 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' matches id="my-button".

    document.querySelector(selector) walks the DOM in document order and returns the first matching element, or null if 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:

    1. Run after the HTML is parsed: If a plain <script src="app.js"></script> sits inside <head> without defer, it executes before the browser has read <body>, so #my-button does not exist yet and querySelector returns null: 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!) Adding defer (or <script type="module">, placing <script> right before </body>, or wrapping code in document.addEventListener('DOMContentLoaded', ...)) guarantees the button is in the DOM first.
    2. Guard against missing elements: Checking if (button) keeps shared scripts safe on pages that do not include #my-button.
  3. 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 an Event object (e) into your function on each click:

    button.addEventListener('click', (e) => {
      // Runs every time the user activates the button
    });
    

    Why addEventListener is much better than older alternatives:

    • Multiple listeners coexist peacefully: Assigning button.onclick = handlerB overwrites button.onclick = handlerA. Calling addEventListener appends 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 an AbortController), 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 presses Enter or Space.
  4. 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 cousin innerText computes CSS visibility and layout reflow — forcing the browser to recalculate element geometry — so textContent is 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 textContent reads 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.

  5. 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 object e carries 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.target refers 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. - Reading e.currentTarget.textContent.trim() (or button.textContent.trim()) guarantees you always log the button's full text content even if child elements are added later.

  6. 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", because e.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 Publish is printed once per click. 2. Keyboard activation: Press Tab until #my-button is focused, then press Enter or Space — Publish logs 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 * Publish rather 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>:

  1. Parse: The browser parses the HTML into DOM nodes, creating the <button> with id="my-button".
  2. Select & subscribe: The deferred script runs document.querySelector('#my-button') to grab that button node and calls addEventListener('click', handler) to subscribe to clicks.
  3. Dispatch: The user clicks "Publish"; the browser creates a click event object e where both e.target (where the click started) and e.currentTarget (where our listener lives) point to <button id="my-button".
  4. Log: Inside the listener, e.currentTarget.textContent reads the 11 raw characters "\n Publish\n", .trim() removes the surrounding whitespace to leave "Publish" (7 characters), and console.log prints Publish.

Key points

  • CSS selector lookup: A CSS selector is a pattern string that matches HTML elements; document.querySelector('#my-button') uses # to match id="my-button" and returns the element or null. Ensure the DOM exists first via <script defer>, <script type="module">, placing the script at the end of <body>, or DOMContentLoaded.
  • addEventListener advantages: An event listener is a callback function invoked when an event fires. Unlike button.onclick = ..., addEventListener('click', fn) allows multiple independent listeners on the same button and supports options like { once: true } and { signal }.
  • e.target vs e.currentTarget: Because of event bubbling (events start on the deepest clicked element and travel upward through ancestor elements), e.target is the innermost element actually clicked, while e.currentTarget is always the element the listener was attached to (#my-button). When the button has no child elements, e.target and e.currentTarget are identical; when it contains <span class="icon">*</span>, clicking the icon makes e.target the <span> while e.currentTarget remains the <button>.
  • textContent.trim(): textContent reads raw text without triggering a costly layout reflow (recalculating visual styles and positions, which innerText can 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 # in document.querySelector('my-button'): Without #, the browser searches for a custom <my-button> tag, gets null, and throws TypeError: Cannot read properties of null (reading 'addEventListener').
  • Running <script> in <head> without defer: The script executes before <body> is parsed, so #my-button is not in the DOM yet and querySelector returns null.
  • 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 invoke logText() once during page load and pass its return value (undefined) as the listener instead of passing the function logText itself.
  • Reading e.target.textContent on buttons with icons or badges: Clicking a child <span> logs only that child's text instead of the whole button's label; use e.currentTarget.textContent.trim().
  • Using this inside an arrow function (e) => { console.log(this.textContent); }: Arrow functions do not bind this to the clicked element (this inherits the outer scope, often window); use e.currentTarget.
  • Reading e.currentTarget asynchronously after await or inside setTimeout: Per the DOM standard, the browser resets e.currentTarget to null as soon as synchronous event dispatch finishes — capture const 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> or document) and relies on event bubbling. Inside the listener, call const btn = e.target.closest('button.item-action'); if btn is non-null, log btn.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 an AbortController signal via button.addEventListener('click', fn, { signal: controller.signal }) and call controller.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 default type is "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

Similar questions

More The Trade Desk interview questions

All 7 The Trade Desk questions →