Hiding Tables with Empty Body Elements With jQuery
If you're new here, you may want to subscribe to my RSS feed or follow me on Twitter. Thanks for visiting!
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();
});
About this entry
You’re currently reading “Hiding Tables with Empty Body Elements With jQuery,” an entry on MirthLab
- Published:
- Sunday, April 20th, 2008 at 11:57 am
- Author:
- Mark Quezada
- Category:
- Web Development
- Tags:
- html, javascript, jquery, tables

No comments
Jump to comment form | comments rss