How do you get the ID of the clicked button inside an onclick event handler in JavaScript? | A1Lab@FahadM to JavaScriptEnglish • 4 days ago

How do you get the ID of the clicked button inside an onclick event handler in JavaScript?

message-square
0

To get the id of the clicked button reliably in JavaScript, use event.currentTarget.id inside an addEventListener("click", ...) handler (or this.id inside a regular function handler attached directly via button.onclick). Using event.currentTarget guarantees you read the element that owns the listener even if a nested child element (such as an <span> or <svg> icon inside the <button>) is actually clicked.


1. Reading event.currentTarget.id on Direct Button Listeners

Attaching "click" with addEventListener and reading event.currentTarget.id works with modern arrow functions, keeps listeners modular, and always points to the bound <button> rather than a child node inside it:

// Read the clicked button's ID safely via event.currentTarget
function bindButtonIdLogger(buttonId) {
  const buttonEl = document.getElementById(buttonId);
  if (!(buttonEl instanceof HTMLButtonElement)) {
    return;
  }

  buttonEl.addEventListener("click", (event) => {
    const clickedButton = event.currentTarget;
    const id = clickedButton instanceof HTMLElement ? clickedButton.id : "";
    console.log("Clicked button ID:", id || "(no id set)");
  });
}

bindButtonIdLogger("save-draft-btn");
  • Accurate target on nested markup: If <button id="save-draft-btn"><span>Save</span></button> is clicked on the <span>, event.target is the <span>, while event.currentTarget is still <button id="save-draft-btn">.
  • Safe fallback: Handles buttons that do not have an id attribute cleanly without mutating the DOM.

2. Delegating Clicks Across Multiple Buttons with .closest("button")

When many buttons share a container (such as a toolbar or action list), attach a single "click" listener on the parent container and resolve the clicked button via event.target.closest("button") so you don’t bind dozens of separate listeners:

// Delegate click events on a container and extract the matched button's ID
function bindToolbarButtonIds(containerId, onButtonClick) {
  const containerEl = document.getElementById(containerId);
  if (!(containerEl instanceof HTMLElement) || typeof onButtonClick !== "function") {
    return;
  }

  containerEl.addEventListener("click", (event) => {
    const targetNode = event.target;
    if (!(targetNode instanceof Element)) {
      return;
    }

    const buttonEl = targetNode.closest("button");
    if (!buttonEl || !containerEl.contains(buttonEl)) {
      return;
    }

    onButtonClick(buttonEl.id, buttonEl);
  });
}

bindToolbarButtonIds("editor-toolbar", (id) => {
  console.log("Toolbar action triggered by ID:", id);
});
  • Scales to dynamic buttons: Works for buttons added or removed inside the container later without re-binding.
  • Scans within container: Checking containerEl.contains(buttonEl) ensures nested buttons outside the intended scope are ignored.

3. Common Traps to Avoid

Reading a button’s id inside click handlers frequently runs into a few subtle pitfalls:

  • Using event.target.id when buttons contain icons or <span> labels: Clicking an inner <i>, <svg>, or <span> makes event.target that child element, which may have no id or a different id—use event.currentTarget.id or .closest("button").id.
  • Using this.id inside an arrow function: Arrow functions do not bind their own this; inside button.addEventListener("click", (e) => ...), this is not the button—use e.currentTarget.id.
  • Duplicating identical IDs across multiple buttons: HTML id values must be unique per document; document.getElementById() only ever returns the first matching element.

TL;DR: Read event.currentTarget.id on direct button click listeners (or event.target.closest("button")?.id when delegating on a parent container) rather than relying on event.target.id or this.id inside arrow functions.