Q:

Get ID of table when clicked on td function

I am trying to get the id of table when clicked on the td of the table.  My code looks like:

<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<table id="table_1">
  <thead>
    <th>First Name</th>
    <th>Last Name</th>
  </thead>
  <tbody>
    <tr>
      <td onclick="editUnit()">John</td>
      <td>Doe</td>
    </tr>
    <tr>
      <td>Jane</td>
      <td>Doe</td>
    </tr>
  </tbody>
</table>
<script>
  function editUnit() {
    let tableId = $(this).closest('table').attr('id');
    alert(tableId);
  }
</script>

I have also tried with $(this).parents('table').attr('id'); , however, still the same result of undefined. 
jsfiddle

A:

Your problem is that assigning the listener inline on the HTML, when the function is called, the this context is not pointing to td, that's why you get undefined. 
So, you have at least two options here:

The "not so good" option: pass this on the listener and get as parameter on the function, like this:

function editUnit(td) {
  let tableId = $(td).closest('table').attr('id');
  console.log(tableId);
}
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<table id="table_1">
  <thead>
    <th>First Name</th>
    <th>Last Name</th>
  </thead>
  <tbody>
    <tr>
      <td onclick="editUnit(this)">John</td>
      <td>Doe</td>
    </tr>
    <tr>
      <td>Jane</td>
      <td>Doe</td>
    </tr>
  </tbody>
</table>

The "better" option: assign an id (or even a class) to the <td> and bind the listener on the script part, not HTML, this way this context will be correct, like this:

document.getElementById("clickableTd").onclick = editUnit;

function editUnit() {
  let tableId = $(this).closest('table').attr('id');
  console.log(tableId);
}
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<table id="table_1">
  <thead>
    <th>First Name</th>
    <th>Last Name</th>
  </thead>
  <tbody>
    <tr>
      <td id="clickableTd">John</td>
      <td>Doe</td>
    </tr>
    <tr>
      <td>Jane</td>
      <td>Doe</td>
    </tr>
  </tbody>
</table>

