Archive for April 20th, 2008

20
Apr

Hiding Tables with Empty Body Elements With jQuery

I needed a quick, client-side way to hide empty tables. I thought that something like this should have done the trick with jQuery:

$(document).ready(function(){
  $('tbody:empty').parents('table').hide();
});

Basically, we’re just finding all tbody elements that are empty using the :empty filter and hiding the parent table element.

But, as it turns out, the tables that were being generated had whitespace inside their tbody elements, so they weren’t technically empty since :empty considers text nodes, even whitespace, as non-empty (as per the jQuery documentation).

One solution is to simply trim the whitespace from inside the tbody elements before checking if they’re empty:

$(document).ready(function(){
  $('tbody').each(function(){
    $(this).html($.trim($(this).html()))
  });
  $('tbody:empty').parents('table').hide();
});