CSS Apprentice CSS Apprentice - 7 months ago 8
Javascript Question

Remove A Cell If It's Column Doesn't Have A Header Section

Is there an easy way to check if a cell's column has a

thead
above it in a table? I want to
.remove('td')
if it's not in a column with a
thead
.

Visual:



stating the obvious but to reiterate with illustration, since the last cell doesn't have a header above it I want it to be deleted from the DOM



table {border: 1px solid;}
td, th {
border: 1px solid;
width: 75px;
}
th {height: 40px;}
td {height: 75px;}

<table>
<thead>
<tr>
<th colspan="2">Header</th>
<th colspan="2">Header</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td> <!-- SHOULD BE REMOVED -->
</tr>
</tbody>
</table>





jsFiddle: https://jsfiddle.net/CSS_Apprentice/7dvt9tam/

Answer

Calculate the total colspan values (= the max cells allowed / row)
Than using the :gt() selector, get rid of all the exceeding TD elements

$("table").each(function(){
  var maxCell = 0;
  $(this).find("th").prop("colspan", function(i,v){
    maxCell += v;
  });
  $(this).find("td:gt("+(maxCell-1)+")").remove();
});
table {border: 1px solid;}
td, th {
    border: 1px solid;
    width: 75px;
}
th {height: 40px;}
td {height: 75px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <thead>
    <tr>
      <th colspan="2">Header</th>
      <th colspan="2">Header</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
    </tr>
  </tbody>
</table>

The above works even if you don't define the colspan attr:

  <th>Header</th>
  <th colspan="2">Header</th>

jsBin example

Comments