Home > Enterprise >  Delete column if it's empty in html table
Delete column if it's empty in html table

Time:09-15

I want to delete the whole column if it's empty.

This code is the only one I found that works, just always every column is deleted except the last one even if it's empty. I don't know why. Any help is highly appreciated.

this is how my page looks :

enter image description here

/* loop over each th */
$('th').each(function(idx, el) {

  /* check every td in the same column, see if they contain any text */
  var check = !!$('tr').find('td:eq('   idx   ')').filter(function() {
    return $.trim($(this).text()).length;
  }).length;

  /* toggle the display of each th and td in this column, based on the check above */
  $('tr').find('td:eq('   idx   '), th:eq('   idx   ')').toggle(check);

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

CodePudding user response:

It seems to work just fine - perhaps it is your HTML

I added tbody and thead

/* loop over each th */
$('th').each(function(idx, el) {
  /* check every td in the same column, see if they contain any text */
  var check = !!$('tbody tr').find('td:eq('   idx   ')').filter(function() {
    return $.trim($(this).text()).length;
  }).length;

  /* toggle the display of each th and td in this column, based on the check above */
  $('tr').find('td:eq('   idx   '), th:eq('   idx   ')').toggle(check);

});
tr, td { border: 1px solid black; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<table>
  <thead>
    <tr>
      <th>0</th>
      <th>1</th>
      <th>2</th>
      <th>3</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>0</td>
      <td>1</td>
      <td></td>
      <td>3</td>
    </tr>
    <tr>
      <td>0</td>
      <td>1</td>
      <td></td>
      <td>3</td>
    </tr>
    <tr>
      <td>0</td>
      <td>1</td>
      <td></td>
      <td>3</td>
    </tr>
    <tr>
      <td>0</td>
      <td>1</td>
      <td></td>
      <td>3</td>
    </tr>
    <tr>
      <td>0</td>
      <td>1</td>
      <td></td>
      <td>3</td>
    </tr>
    <tr>
      <td>0</td>
      <td>1</td>
      <td></td>
      <td>3</td>
    </tr>
    <tr>
      <td>0</td>
      <td>1</td>
      <td></td>
      <td>3</td>
    </tr>
    <tr>
      <td>0</td>
      <td>1</td>
      <td></td>
      <td>3</td>
    </tr>
  </tbody>
</table>

  • Related