1

I have a 5×7 HTML table. On many queries, there are fewer than 35 items filling the complete table.

How can I "hide" the empty cells dynamically in this case, using jQuery (or any other efficient way)?

1
  • Are you talking about hiding whole rows or columns of empty cells? Or some other pattern? Commented Apr 13, 2010 at 18:19

5 Answers 5

3

Edit - Improved Version

// Grab every row in your table
$('table#yourTable tr').each(function(){
  if($(this).children('td:empty').length === $(this).children('td').length){
    $(this).remove(); // or $(this).hide();
  }
});

Not tested but seems logically sound.

// Grab every row in your table
$('table#yourTable tr').each(function(){
  var isEmpty = true;
  // Process every column
  $(this).children('td').each(function(){
    // If data is present inside of a given column let the row know
    if($.trim($(this).html()) !== '') {
      isEmpty = false;
      // We stop after proving that at least one column in a row has data
      return false;
    }
  });
  // If the whole row is empty remove it from the dom
  if(isEmpty) $(this).remove();
});
Sign up to request clarification or add additional context in comments.

2 Comments

This works only if all TD cells are blank for a particular column. Otherwise, if you remove the first cell, the remaining cells' contents are each shifted left by one (display error). If it's true that the TD cells are all blank for a whole column, just delete the column.
Is it worth assigning $this = $(this); inside the each function rather than converting to a jQuery object three times per row?
1

Obviously you'll want to adjust the selector to fit your specific needs:

$('td').each(function(){
  if ($(this).html() == '') {
    $(this).hide();
  }
});

1 Comment

I've had situations where $('td:empty').hide(); did not work in Safari so I don't use it. I wonder if it's more reliable in newer versions of jquery.
1
$('td:empty').hide();

Comments

1

How about CSS empty-cells

table {
    empty-cells: hide;
}

Comments

1

I'm voting for Ballsacian's answer. For some reason,

$('table#myTable tr:not(:has(td:not(:empty)))').hide();

has a bug. If you remove the outermost :not(), it does what you'd expect, but the full expression above crashes jQuery.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.