Larry Martell
Larry Martell

Reputation: 3756

From a click event on a table cell get selector for row

I have a td in a table that is created thusly:

I have a click handler on this and when it's clicked I need to do something to another td on this row. In the event handler I can get the id of the td with e.target.id but from that I have not figured out how to get the selector for the tr so I can get at the other td.

tr = document.createElement('tr');
input = document.createElement('select');
input.setAttribute('id', 'new=#=' + fld[0] + '=@=' + NEW_ROWS);
.
.
.

div = document.createElement('div');
td = document.createElement('td');
div.appendChild(input)
td.appendChild(div);
tr.appendChild(td);

Upvotes: 0

Views: 525

Answers (2)

mplungjan
mplungjan

Reputation: 178403

Delegate from the tbody

$("tbody").on("click","td",function() {
  const $row = $(this).closest("tr");
  const $cell = $row.find("td").eq(2); // or whatever cell you need
  // do something with cell
})

Upvotes: 1

Barmar
Barmar

Reputation: 782653

You don't need a selector, just use DOM navigation functions.

var row = e.target.closest("tr");

will return the <tr>, and then you can use row.querySelector("...") to select something within that row.

Upvotes: 1

Related Questions