Jquery rows toogle class independant table

Viewed 45

I got two tables and I would click on any row and toggle the class. At the same time, I would toggle the same row of the second table with the same content.

$("table tr").on("click", function() {
  $(this).toggleClass("blue");
});
.blue {
  background-color: rgb(3, 135, 255);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr>
    <td>Ryan Astruld</td>
  </tr>
  <tr>
    <td>John Lisbon</td>
  </tr>
  <tr>
    <td>David Parsons</td>
  </tr>
  <tr>
    <td>In The End (cover)</td>
  </tr>
</table>
<hr>
<table>
  <tr>
    <td>David Parsons</td>
  </tr>
  <tr>
    <td>Ryan Astruld</td>
  </tr>
  <tr>
    <td>In The End (cover)</td>
  </tr>
  <tr>
    <td>John Lisbon</td>
  </tr>
</table>

Thanks for the help.

2 Answers

Get the content of the current row, then use that to find the matching rows in all the tables and toggle them.

$("table tr").on("click", function() {
  var content = $(this).text().trim();
  $("table").find("tr").filter(function() {
    return $(this).text().trim() == content;
  }).toggleClass("blue");
});
.blue {
  background-color: rgb(3, 135, 255);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr>
    <td>Ryan Astruld</td>
  </tr>
  <tr>
    <td>John Lisbon</td>
  </tr>
  <tr>
    <td>David Parsons</td>
  </tr>
  <tr>
    <td>In The End (cover)</td>
  </tr>
</table>
<hr>
<table>
  <tr>
    <td>David Parsons</td>
  </tr>
  <tr>
    <td>Ryan Astruld</td>
  </tr>
  <tr>
    <td>In The End (cover)</td>
  </tr>
  <tr>
    <td>John Lisbon</td>
  </tr>
</table>

You can make use of the .index() of the currently clicked row:

$("table tr").on("click", function(){
    var index = $(this).closest('tr').index();
    $("table").each(function(){
      $(this).find('tr').eq(index).toggleClass("blue");
    });
});
.blue{
  background-color: rgb(3,135,255);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr>
    <td>Ryan Astruld</td>
  </tr>
  <tr>
    <td>John Lisbon</td>
  </tr>
  <tr>
    <td>David Parsons</td>
  </tr>
  <tr>
    <td>In The End (cover)</td>
  </tr>
</table>
<hr>
<table>
  <tr>
    <td>David Parsons</td>
  </tr>
  <tr>
    <td>Ryan Astruld</td>
  </tr>
  <tr>
    <td>In The End (cover)</td>
  </tr>
  <tr>
    <td>John Lisbon</td>
  </tr>
</table>

Related