Reputation:
How to check if my html table is empty. Remember that the following table must be considered as empty table as there are no rows except headings.
<table style="float: left;text-align: center;" id="Table1"">
<th style="width: 11%;">Item Id</th>
<th style="width: 44%;">Item Name</th>
<th style="width: 11%;">Quantity</th>
<th style="width: 18%;">Trade Price</th>
<th style="width: 16%;">Price</th>
<th style="width: 7%;" id="non-printable">Delete</th>
</table>
These headings are fixed and I'm generating rows using javascript. I have to reset my javascript counter if table is empty. How can I check that the table is empty using javascript or jquery?
I'm incrementing in another counter while I am adding row with javascript.
Upvotes: 2
Views: 17820
Reputation: 50674
You know a table is empty if it only contains one row (as a row is dynamically added around your table headers). So you can try and select all the rows within your table and check the length of the collection returned. If the length is less than or equal to 1 then you know that the table is empty. Otherwise, if it is greater then you know that it has rows within the table.
See example below:
const isEmpty = document.querySelectorAll("#Table1 tr").length <= 1;
console.log(isEmpty);
<table style="float: left;text-align: center;" id="Table1">
<th style="width: 11%;">Item Id</th>
<th style="width: 44%;">Item Name</th>
<th style="width: 11%;">Quantity</th>
<th style="width: 18%;">Trade Price</th>
<th style="width: 16%;">Price</th>
<th style="width: 7%;" id="non-printable">Delete</th>
</table>
Upvotes: 0
Reputation: 5079
If you want to check if your table is empty, you need to check if the number of rows is 0.
if ($('#Table1 tr').length == 0) {
//...do something here
}
Upvotes: 7
Reputation: 48600
You can count the rows in the table body. Set your table up accordingly.
console.log(document.querySelectorAll('#Table1 tbody tr').length); // 0
document.querySelector('#Table1 tbody').appendChild(document.createElement('TR'));
console.log(document.querySelectorAll('#Table1 tbody tr').length); // 1
<table style="float: left;text-align: center;" id="Table1">
<thead>
<th style="width: 11%;">Item Id</th>
<th style="width: 44%;">Item Name</th>
<th style="width: 11%;">Quantity</th>
<th style="width: 18%;">Trade Price</th>
<th style="width: 16%;">Price</th>
<th style="width: 7%;" id="non-printable">Delete</th>
</thead>
<tbody>
</tbody>
</table>
Upvotes: 2
Reputation: 842
You can use the rows and length properties of the table to determine the amount of rows there are.
var rows = $('#Table1').rows.length;
Upvotes: 0