Edgar Navasardyan Edgar Navasardyan - 1 month ago 9
Javascript Question

Getting the inner-most row in the embedded tables

I have a table with nested tables.And the problem is that in mouse event listener, I would like to grab the deepest row. I've found this which is almost what I am looking for, but I am not experienced enough to use this example to solve my issue. The key to success is making alert box to display "2" instead of "1" in the below given JSFIddle

<table>
<tbody>
<tr id='1'><td>A
<table>
<tbody>
<td><tr id='2'>B</tr></td>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>


NOTE: For simplicity, I presented two levels, but would like to ask you consider the general case when any level of embedded structures might be possible.

UPDATE: See the updated JSFiddle corrected for NewToJS's comment

Answer

Event.stopPropagation() Prevents further propagation of the current event in the capturing and bubbling phases.

$(function() {
  $(document).on('mouseover', 'tr', function(e) {
    e.stopPropagation();
    console.log(this.id);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<table>
  <tbody>
    <tr id='1'>
      <td>A
        <table>
          <tbody>
            <tr id='2'>
              <td>B</td>
            </tr>
            <tr id='3'>
              <td>C</td>
            </tr>
          </tbody>
        </table>
      </td>
    </tr>
  </tbody>
</table>

Comments