0

Suppose I have a table, some rows and cells. If I click a cell and I need to go to the table node I can do something like:

while (tcel) {
  if (tcel.nodeName === "TABLE") {
    tbl = tcel;
    break;
  }
  else {
    tcel = tcel.parentElement;
     // tcel will be lost
  }
}

I'm wondering if there's a way I can get to the table node without the loop, but instead if there's a method that knows that the tcel belongs to the table, like a relative parent?

Gakki Rez
  • 23
  • 4
  • 1
    have you tried using [`closest`](https://developer.mozilla.org/en-US/docs/Web/API/Element/closest)? – shrys Oct 22 '19 at 05:16

1 Answers1

0

You can use .closest to find an ancestor node that matches a particular selector:

const tbl = tcel.closest('table');

If no element is found, it will be null.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320