1

I am looking at the following link which is a part of event delegation documentation.

In the link, we have the followig

let table = document.getElementById('bagua-table');

    let selectedTd;

    table.onclick = function(event) {
      let target = event.target;

      while (target != this) {
        if (target.tagName == 'TD') {
          highlight(target);
          return;
        }
        target = target.parentNode;
      }
    }

I am just unable to understand why the following while (target != this). I understand that the this keyword here refers to the entire table since that is the object in play but why write a loop in this manner?

Maybe my understanding of this is not as deep. If someone could please clarify.

Thanks

Kevin B
  • 94,570
  • 16
  • 163
  • 180
Jeff Benister
  • 468
  • 3
  • 12
  • Does this answer your question? [jQuery $(this) keyword](https://stackoverflow.com/questions/12481439/jquery-this-keyword) – omid May 31 '22 at 21:28

2 Answers2

1

What this does is, the target starts at the event's target - the innermost element the event was dispatched to. Then it searches the target, then its ancestor, then its ancestor, and so on. The first one that matches the condition target.tagname == 'TD', if any, will result in highlight being called and the loop ending. If no elements match, then the loop will continue until the target is this - the table - and will end at that point.

But this is pretty confusing code. Using .closest would be much easier, since it will find the first ancestor matching a selector.

table.onclick = (event) => {
  const td = event.target.closest('td');
  if (td) highlight(td);
};

If nested tables are a possibility, and you don't want the event to go outward past the table in question, include the table in the selector string:

table.onclick = (event) => {
  const td = event.target.closest('#bagua-table td');
  if (td) highlight(td);
};
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • Thank you. So in short, it goes up event chain until that object is found to be stopped. I see how the .closet would be a better way to understand this. Thank you. – Jeff Benister May 31 '22 at 21:31
1

In an event listener, this is equivalent to event.currentTarget, which is the element that the listener was added to (the table).

event.target is the nested element that was actually clicked on.

So the loop is walking up the DOM hierarchy (using target.parentNode) from the clicked element until it reaches the table that the listener was added to.

If it reaches a TD element along the way, it highlights that element and returns, which breaks out of the loop.

It's roughly equivalent to:

highlight(event.target.closest("TD"));
Barmar
  • 741,623
  • 53
  • 500
  • 612