JQuery gets tr after clicking on its contents

Let's pretend that

<table>
  <tr>
    <td><a class='ilink'> link text </a></td>
    <td></td>
    <td></td>
  <tr>
  <tr>
    <td><a class='ilink'> link text </a></td>
    <td></td>
    <td></td>
  </tr>
</table>

in jquery code, after clicking the link, I want to select the entire row of the table the link is in. But how can I find her?

+3
source share
3 answers

You can do this using the .closest()following:

$("a.ilink").click(function() {
  $(this).closest("tr").addClass("highlight");
});

If you have many lines, this will be more efficient (one copy of this compared to one for each <a>):

$("table").delegate("a.ilink", "click", function(){
  $(this).closest("tr").addClass("highlight");
});
+7
source
#EDIT remove...  better options listed
+1
source
$(document).ready(function(){
    $('a.ilink').click(function() {
        $('tr').removeClass('highlight');
        $(this).closest('tr').addClass('highlight');
    });
 });

Then you need a dedicated css class:

.hightlight { background-color:red; }
0
source

Source: https://habr.com/ru/post/1738542/


All Articles