I have a table which contains 'n' rows dynamically generated. All <td>
's may or may not contain data. I want to hide or delete '<tr>
' if all it's td's are empty.
I don't know how to parse through all <td>
's and make sure it's empty or not.
example table as follows,
<table id='ex_table'>
<tr>
<td>one</td>
<td>two</td>
</tr>
<tr>
<td></td>
<td>one</td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
</table>
In the above table last row need to be hidden since all it's <td>
's are empty. I prefer jquery to do this.
I have a table which contains 'n' rows dynamically generated. All <td>
's may or may not contain data. I want to hide or delete '<tr>
' if all it's td's are empty.
I don't know how to parse through all <td>
's and make sure it's empty or not.
example table as follows,
<table id='ex_table'>
<tr>
<td>one</td>
<td>two</td>
</tr>
<tr>
<td></td>
<td>one</td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
</table>
In the above table last row need to be hidden since all it's <td>
's are empty. I prefer jquery to do this.
- Take a look at this question – Patsy Issa Commented Dec 3, 2013 at 8:14
5 Answers
Reset to default 8You don't actually have to inspect the td
elements. You can select the rows and use .filter
to filter out those with text content, i.e. only keep those which are empty:
$('#ex_table tr').filter(function() {
return $.trim($(this).text()) === '';
}).hide(); // or .remove()
This works because .text
gets the bined inner text of all descendants and $.trim
removes whitespace characters that might occur due to your HTML formatting (but are not actually content).
If you have cells which contain HTML elements but no text content (e.g. icons styled through CSS), and you want to keep those, you'd have actually have to test whether a cell contains HTML or not. The approach is basically the same as testing for text content
$('#ex_table tr').filter(function() {
return $(this).children().filter(function() {
return $.trim($(this).html()) !== '';
}).length === 0;
}).hide();
only this time we count the number of cells in a row that contain HTML. If there is none, the row is considered empty.
try something like this
$(function(){
$('#ex_table tr').each(function(){
var val = $(this).text().trim();
if(val == ''){
$(this).remove();
}
})
})
Try this:
$('#ex_table tr').each(function){
if($(this).text()==''){
$(this).remove();
}
}
Straight jQuery you say?
EDIT: I'd use Felix's answer.. just change ".hide()" to ".remove()" if you'd like to delete the element.
$('tr').each(function(){
var hasValue = false;
$(this).children().each(function(){
if ($(this).html() != "")
hasValue = true;
});
if (!hasValue)
$(this).remove();
});
Try this code
var hide;
$("tbody").find("tr").each(function(){
hide=true;
$(this).find("td").each(function(){
if($(this).html()!='') {
hide=false;
}
});
if(hide==true) {
$(this).hide();
}
});