I have a 5×7 HTML table. On many queries, there are fewer than 35 items filling the plete table.
How can I "hide" the empty cells dynamically in this case, using jQuery (or any other efficient way)?
I have a 5×7 HTML table. On many queries, there are fewer than 35 items filling the plete table.
How can I "hide" the empty cells dynamically in this case, using jQuery (or any other efficient way)?
Share Improve this question edited Dec 10, 2021 at 15:37 Michael e lately 9,4228 gold badges68 silver badges94 bronze badges asked Apr 13, 2010 at 18:13 T.T.T.T.T.T. 34.6k47 gold badges135 silver badges172 bronze badges 1- Are you talking about hiding whole rows or columns of empty cells? Or some other pattern? – e100 Commented Apr 13, 2010 at 18:19
5 Answers
Reset to default 3Edit - 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();
});
Obviously you'll want to adjust the selector to fit your specific needs:
$('td').each(function(){
if ($(this).html() == '') {
$(this).hide();
}
});
$('td:empty').hide();
How about CSS empty-cells
table {
empty-cells: hide;
}
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.