0

I have function where I passed table:

function isEmpty(properTable){
}

var isEmpty1 = isEmpty($("#daysTable tbody"));
var isEmpty2 = isEmpty($("#daysTable2 tbody"));

and I don't know how I can find out whether table is empty or how many rows that table has. I need sth like this:

function isEmpty(properTable){
        if((properTable tr).length > 0){
            return false;
        }
        else{
            return true;
        }
}

and of course It doesn't work.

mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • @Wendelin because that would remove nodes, not count them. "This method removes not only child (and other descendant) elements, but also any text within the set of matched elements. " – j08691 Sep 06 '19 at 17:07
  • Use `function isEmpty(sel){ return $(sel).is(':empty'); }` and call like: `isEmpty('#daysTable tbody') // boolean` – Roko C. Buljan Sep 06 '19 at 17:10

2 Answers2

1

Used .find() with your properTable argument to count the rows in the table body:

Change

if((properTable tr).length > 0){

To

if(properTable).find('tr').length === 0){
j08691
  • 204,283
  • 31
  • 260
  • 272
0

Perhaps you meant

const isEmpty = (properTable) =>  $("tr", properTable).length === 0;

var isEmpty1 = isEmpty($("#daysTable1 tbody"));
var isEmpty2 = isEmpty($("#daysTable2 tbody"));

console.log(isEmpty1, isEmpty2);

// alternative

console.log(
  $("#daysTable1 tbody").is(":empty"),
  $("#daysTable2 tbody").is(":empty"),
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="daysTable1">
  <thead>
    <tr>
      <th>Head 1</th>
      <th>Head 2</th>
    </tr>
  </thead>
  <tbody></tbody>
</table>
<table id="daysTable2">
  <thead>
    <tr>
      <th>Head 1</th>
      <th>Head 2</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Data</td>
      <td>Data</td>
      <td>Data</td>
    </tr>
  </tbody>
</table>
mplungjan
  • 169,008
  • 28
  • 173
  • 236