KatInterview

Log a Button's Label on Click with the DOM Event API

Data Structure DesignModel answer
EasyModel answerData Structure Designjavascriptdomevent-handling

Last 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:

  1. Finds the button using document.querySelector.
  2. Registers a click handler using addEventListener.
  3. 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.