How to traverse all columns of a table with jquery and hide if it is empty

0

I have a table html with 15 lines and I need to go through all the columns and check if there is any value, if Column is equal to empty then hidden column, this example below hides the position 5 column, but how to traverse the columns?.

$('#btnBuscar').on('click', function () {

    //Percorro todas as colunas
    //Se coluna vazia então oculto essa coluna

    $('.grid td:nth-child(5), th:nth-child(5)').hide();

});
    
asked by anonymous 17.06.2017 / 05:10

1 answer

2

You need to go through the table using $ .each, and add a bookmark to have control of the elements that will be deleted, for example ...

$(document).ready(function(){
	$('.ocultar').on('click', function(){
  	var i = 1;
  	$('table.click tr td').each(function(el){
    
    	if($(this).text() == '') {
      
      	$('table.click td:nth-child('+i+'), th:nth-child('+i+')').hide(); 
        
        }
        
        i++;
      
    })
  })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><tableclass="click">

<tr>
  <th>Nome</th>
  <th>Nome</th>
  <th>Nome</th>
  <th>Nome</th>
  <th>Nome</th>
  <th>Nome</th>
  <th>Nome</th>
  <th>Nome</th>
  <th>Nome</th>
  <th>Nome</th>
</tr>
<tr>
  <td>teste1</td>
  <td></td>
  <td>teste3</td>
  <td>teste4</td>
  <td></td>
  <td>teste6</td>
  <td>teste7</td>
  <td></td>
  <td>teste9</td>
  <td>teste10</td>
  
</tr>

</table>
<button class="ocultar">
Ocultar
</button>
    
17.06.2017 / 05:54