Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to find the number of rows of any table using jQuery?

I am setting up various HTML tables on my web page and want to find a way of knowing the number of rows each of them contain in jQuery without using classes or id in the tables. Is this possible?

I have already tried linking up an HTML button with a click event handler to get the closest table and compute its length, but I seem to be doing something wrong here.

I would like to find the length of any table to be able to change the action of the button, depending on the number of rows left in the table.

The actual output of rowCount is 1, whenever I try it on any size table.

$(document).on("click", "button.x-cross", function() {
  var rowCount = $(this).closest("table >tr").length;

  // Conditions using the rowCount variable

  return false;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr>
    <td>
      <span>First row</span>
    </td>
    <td>
      <button type="button" class="x-cross">X</button>
    </td>
  </tr>
</table>
like image 988
Louis Durand Avatar asked Jan 26 '26 22:01

Louis Durand


1 Answers

The issue in your code is that the table is the closest parent element to the button, not table > tr, hence that selector doesn't find anything. If you separate the selector in to closest() and then find(), it works:

$(document).on("click", "button.x-cross", function() {
  var rowCount = $(this).closest("table").find('tr').length;
  console.log(rowCount);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr>
    <td>
      <span>First row</span>
    </td>
    <td>
      <button type="button" class="x-cross">X</button>
    </td>
  </tr>
</table>

<table>
  <tr>
    <td>
      <span>First row</span>
    </td>
  </tr>
  <tr>
    <td>
      <span>Second row</span>
    </td>
  </tr>
  <tr>
    <td>
      <span>Third row</span>
    </td>
    <td>
      <button type="button" class="x-cross">X</button>
    </td>
  </tr>
</table>
like image 157
Rory McCrossan Avatar answered Jan 29 '26 10:01

Rory McCrossan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!