'Hide table row when cell is empty

I'm having an issue where I can't seem to find an answer to, but I can't imagine it's not possible.

I have a table with two columns: the left column contains a label, the right side contains a value. However, the value can be empty. The label is fixed text.

What I want is to hide the entire row if the right cell of the row (the value) is empty.

For example:

<table>
 <tr>
  <td class="label">number of users:</td>
   <td class="value">8</td>
 </tr>
 <tr>
  <td class="label">total number of people:</td>
  <td class="value"></td>
 </tr>
</table>

Since the last row does not contain a value, I want the entire row to be hidden.

I can hide the cell using td:empty, but that's not enough. I tried to work around this by setting the height of the row to 0px and make it expand when the 'value'-cell is shown, but I can't get that to work either since the label cell already expands the row.

Anyone knows how I can tackle this problem using just HTML/CSS?

css


Solution 1:[1]

There's no parent selector in css, so you can't do this with css.

You may use jQuery:

$('td').each(function(){
  if($(this).is(:empty)){
     $(this).closest('tr').hide();
  }
});

Or in shorter form,

$('tr:has("td:empty")').hide();

See the docs: :empty, :has,closest and each

Solution 2:[2]

An HTML/CSS solution exists if you don't mind throwing out <table> <tr> and <td>. You can get the same end result with CSS - including still rendering like a table:

CSS:

/* hide if empty */
.hideIfEmpty:empty { display: none; }

/* label style */
.hideIfEmpty::before { font-weight:bold; }

/* labels */
.l_numberofusers::before { content:"Number of users: "; } 
.l_numberofpeople::before { content: "Number of people:"; }
.l_numberofdogs::before { content: "Number of dogs:" }

/* table like rows/cells */
.table { display: table; }
.row { display: table-row; }
.cell { display: table-cell; }

HTML

<!-- if the div.hideIfEmpty is empty, it'll be hidden; 
     labels come from CSS -->

<div class="table">
  <div class="row hideIfEmpty l_numberofusers"><span class="cell">8</span></div>
  <div class="row hideIfEmpty l_numberofpeople"><span class="cell">12</span></div>
  <div class="row hideIfEmpty l_numberofdogs"></div>
</div>

The caveat is that your <div> has to be empty to hide the row, and values in the <div> must have a class .cell applied to them.

Result:

Number of users:           8
Number of people:          12

This will make your CSS very long if you have many labels/rows since you have to have one rule for every row to populate the label.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Paul Sturm