skip to Main Content

I have a page which is generating html tables dynamically. I do not have any control as to how the tables are being generated but I can put JavaScript code in it.

What I am trying to do is that there are some tables which are empty i.e. they have only row and no rows. I want to hide / remove those tables using JavaScript.

All the tables have a class "card-table".

Is it possible to find all the tables with "card-table" class and if has less than 1 row then remove/hide it?

Any help is appreciated.

Thanks in advance.

I’m just trying using jQuery or JavaScript but I’m not sure how to traverse the tables using same class and remove / hide them.

3

Answers


  1. You can do something like this in jQuery

    $(document).ready(function() {
        $('table.card-table').each(function() {
            // If the table has less than 2 rows, hide it
            if ($(this).find('tr').length < 2) {
                $(this).hide();
            }
        });
    });
    
    Login or Signup to reply.
  2. Not showing tables with zero rows

    $(function() {
      $('table.card-table').each(function() {
        const $rows = $(this).find('tr');
        $(this).toggle($rows.length > 0); // show if more than 0
      });
    });
    

    Vanilla

    window.addEventListener('DOMContentLoaded', () => {
      document.querySelectorAll('table.card-table').forEach(table => {
        const rows = table.querySelectorAll('tr');
        table.hidden = rows.length === 0; // hide if 0
      });
    });
    
    Login or Signup to reply.
  3. Tables have a built-in API for accessing and counting rows and columns. Use it:

    for (const table of document.querySelectorAll('table.card-table')) {
      table.hidden = table.rows.length === 0;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search