How to Get the ID of the Clicked Element in jQuery

To get the id of the clicked element in jQuery, read this.id inside the click handler: $("button").on("click", function () { console.log(this.id); }). $(this).attr("id") returns the same value. This guide shows each way to get an element’s id with jQuery, the difference between this, event.currentTarget and event.target, why arrow functions break this.id, how to get ids of dynamically added elements with event delegation, and how to select an element by id.

Every page was opened in Microsoft Edge 153.0.4234.48 with jQuery 3.7.1; the screenshots were taken after real mouse clicks, and the outputs are the browser console messages. Reference: .on() and .attr() in the jQuery API documentation.

Get the id of the clicked element

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Get the ID of the clicked element</title>
  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  <style>body { font-family: Segoe UI, Arial; margin: 24px; } button { padding: 8px 14px; margin: 4px; }</style>
</head>
<body>
  <h3>Choose a plan</h3>
  <button id="basic">Basic</button>
  <button id="standard">Standard</button>
  <button id="premium">Premium</button>
  <p id="result">Click a button</p>

  <script>
    $("button").on("click", function () {
      const id = this.id;                        // id of the clicked element
      console.log("clicked:", id);
      $("#result").text("You clicked the button with id: " + id);
    });
  </script>
</body>
</html>

Console output after clicking Premium, Basic and Standard:

clicked: premium
clicked: basic
clicked: standard
Microsoft Edge page with three plan buttons where jQuery shows the id of the clicked button, standard
The page after the clicks: the last clicked button was standard.

Inside a jQuery event handler written as a regular function, this is the DOM element the handler is attached to. this.id reads its id property directly, without creating a jQuery object.

this.id vs attr(‘id’) vs event.target.id

These look interchangeable until the click lands on a child element. Here the user clicks the icon <span> inside the button:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>this.id vs event.target.id</title>
  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  <style>body { font-family: Segoe UI, Arial; margin: 24px; } button { padding: 8px 14px; margin: 4px; }</style>
</head>
<body>
  <button id="save-btn"><span id="save-icon">&#128190;</span> Save</button>
  <table id="out" border="1" cellpadding="6"></table>

  <script>
    $("#save-btn").on("click", function (event) {
      const rows = {
        "this.id": this.id,
        "$(this).attr('id')": $(this).attr("id"),
        "$(this).prop('id')": $(this).prop("id"),
        "event.currentTarget.id": event.currentTarget.id,
        "event.target.id": event.target.id,        // the element really clicked (the icon)
      };
      for (const [how, id] of Object.entries(rows)) {
        console.log(how, "->", id);
        $("#out").append(`<tr><td><code>${how}</code></td><td>${id}</td></tr>`);
      }
    });
  </script>
</body>
</html>

Console output after clicking the icon:

this.id -> save-btn
$(this).attr('id') -> save-btn
$(this).prop('id') -> save-btn
event.currentTarget.id -> save-btn
event.target.id -> save-icon
Edge page table comparing this.id, jQuery attr id, prop id, event.currentTarget.id and event.target.id after clicking an icon inside a button
event.target is the icon; the other four give the button’s id.
ExpressionReturns
this.idid of the element the handler is bound to (fastest)
$(this).attr("id")the id attribute; undefined if the element has none
$(this).prop("id")the id property; "" if the element has none
event.currentTarget.idsame element as this, also works in arrow functions
event.target.idthe innermost element actually clicked (may be a child)

Arrow functions: use event.currentTarget

An arrow function does not get its own this, so this.id is not the button. Use the event object instead:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Arrow function and this</title>
  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  <style>body { font-family: Segoe UI, Arial; margin: 24px; } button { padding: 8px 14px; margin: 4px; }</style>
</head>
<body>
  <button id="export">Export</button>

  <script>
    $("#export").on("click", () => {
      console.log("this.id in an arrow function:", this.id);     // this is window here
    });
    $("#export").on("click", (event) => {
      console.log("event.currentTarget.id:", event.currentTarget.id);
    });
  </script>
</body>
</html>

Console output after clicking Export:

this.id in an arrow function: undefined
event.currentTarget.id: export

Get the id of dynamically added elements (event delegation)

$(".done").on("click", ...) only binds to elements that exist when it runs. Attach the handler to a parent that always exists and pass a selector as the second argument; jQuery then handles clicks on matching children added later. closest() gets the id of the surrounding row:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Event delegation</title>
  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  <style>body { font-family: Segoe UI, Arial; margin: 24px; } button { padding: 8px 14px; margin: 4px; }</style>
</head>
<body>
  <ul id="tasks">
    <li id="task-1">Write report <button class="done">Done</button></li>
  </ul>
  <button id="add">Add task</button>
  <p id="result"></p>

  <script>
    let next = 2;
    $("#add").on("click", function () {
      $("#tasks").append(`<li id="task-${next}">New task ${next++} <button class="done">Done</button></li>`);
    });

    // one handler on the list also works for buttons added later
    $("#tasks").on("click", ".done", function () {
      const taskId = $(this).closest("li").attr("id");   // id of the parent <li>
      console.log("done:", taskId);
      $("#result").text("Marked " + taskId + " as done");
    });
  </script>
</body>
</html>

Console output after adding two tasks and clicking Done on task 3:

done: task-3
Edge page with a task list where jQuery event delegation handles a Done button added after page load and shows the parent li id task-3
The handler works for task-3, which was added after the page loaded.

Get the id of an element without a click

Select the element and call attr("id"). To collect the ids of several elements, use map() and get():

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Get element IDs</title>
  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  <style>body { font-family: Segoe UI, Arial; margin: 24px; } button { padding: 8px 14px; margin: 4px; }</style>
</head>
<body>
  <div class="card" id="card-nyc">New York</div>
  <div class="card" id="card-sf">San Francisco</div>
  <div class="card">No id</div>
  <input id="email" value="ana@example.com">

  <script>
    console.log($(".card").first().attr("id"));          // id of the first match
    console.log($(".card").map(function () { return this.id; }).get());   // all ids
    console.log($(".card").eq(2).attr("id"));             // no id attribute -> undefined
    console.log($(".card")[2].id === "");                 // the DOM property is ""
    console.log($("#email").val());                       // get the value of an element by id
  </script>
</body>
</html>

Console output:

card-nyc
['card-nyc', 'card-sf', '']
undefined
true
ana@example.com

Select an element by id in jQuery

Use $("#id"). If the id contains characters that have a meaning in CSS selectors (like . or :), escape it with $.escapeSelector(). An empty result is a jQuery object with length 0, not null:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Select by ID</title>
  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  <style>body { font-family: Segoe UI, Arial; margin: 24px; } button { padding: 8px 14px; margin: 4px; }</style>
</head>
<body>
  <p id="order.total">$120.00</p>
  <p id="status">Shipped</p>

  <script>
    console.log($("#status").text());                          // select by id
    console.log($("#order.total").length);                     // 0: the dot is read as a class
    console.log($("#" + $.escapeSelector("order.total")).text());
    console.log($("#missing").length === 0 ? "no element with id missing" : "found");
  </script>
</body>
</html>

Console output:

Shipped
0
$120.00
no element with id missing

Want more JavaScript and TypeScript tutorials? Start with these:

Frequently asked questions

How do I get the id of the clicked element in jQuery?

In the handler, use this.id or $(this).attr("id"): $("button").on("click", function () { alert(this.id); });

What is the difference between this.id and event.target.id?

this is the element the handler is attached to; event.target is the element actually clicked, which can be a child like an icon.

Why is this.id undefined in my click handler?

The handler is probably an arrow function, where this is not the element. Use event.currentTarget.id or a regular function.

How do I get the id of a dynamically created element?

Use event delegation: $("#parent").on("click", ".child", function () { console.log(this.id); });

Should I use attr(‘id’) or prop(‘id’)?

Both return the id. attr() gives undefined when there is no id attribute; prop() and this.id give an empty string.

How do I select an element by id in jQuery?

$("#myId"). Escape special characters with $("#" + $.escapeSelector(id)).