Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the closest ancestor from current event in Javascript

I'm having trouble selecting a closest <tr> element from a click event.

Currently, to make it work I select an exact number of elements in the list from event.path.

I would like it to be more flexible without needing to depend on the current path position number.

HTML:

<tr>
  <td class="col-site">Stringname</td>
</tr>

JavaScript:

event.path[1].classList.add(this.openedClassState);

Using event.closest('tr') is not working, and I get this error:

Uncaught TypeError: event.closest is not a function

Does anyone know why?

like image 258
aspirinemaga Avatar asked Sep 01 '25 16:09

aspirinemaga


2 Answers

It looks like you're calling event.closest, which doesn't seem right. Did you mean to do element.closest, or perhaps event.target.closest?

function handleClick(event) {
  const tr = event.target.closest('tr');
  tr.style.backgroundColor = 'red';
}


document.querySelectorAll('td').forEach(td => 
  td.addEventListener('click', handleClick));
td{border:1px solid blue}
<table>
  <tr>
    <td>Click</td>
    <td>me</td>
  </tr>
</table>
like image 85
Jordan Running Avatar answered Sep 05 '25 03:09

Jordan Running


There is no closest method on the Event object. You need to either look for event.target.closest or just cache the reference to the element you're binding your event listener to, then use the closest method for that element.

const tds = document.querySelectorAll('td');

for(const td of tds) {
  td.addEventListener('click', event => {
    console.log(event.target.closest('tr').id);
    console.log(td.closest('tr').id); // this does the same thing
  }, false);
}
<table>
  <tr id="TR1">
    <td>Some text</td>
  </tr>
  <tr id="TR2">
    <td>Some text</td>
  </tr>
  <tr id="TR3">
    <td>Some text</td>
  </tr>
</table>

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!