aspirinemaga
aspirinemaga

Reputation: 3937

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?

Upvotes: 4

Views: 8325

Answers (2)

user4639281
user4639281

Reputation:

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>

Upvotes: 3

Jordan Running
Jordan Running

Reputation: 106027

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>

Upvotes: 8

Related Questions