I am attempting to iterate through a HTML table using jQuery and delete empty rows. The page is driven by ASP.NET and with certain permission, items in the table will be hid
I think it is better to use the '.parent()' method, because a 'tr' tag is always the next parent from a 'td' tag.
Your code appears to work just fine. Try running the following on its own to see what I mean:
<html>
<head>
<title>jQuery Tests</title>
<script src="http://code.jquery.com/jquery-1.5.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('tr').each(function () {
$(this).find('td').each(function () {
if ($(this).text().trim() == "") {
$(this).closest("tr").remove();
};
});
});
});
</script>
</head>
<body>
<table cellpadding="0" cellspacing="0" border="1">
<tr>
<td></td>
<td>testing</td>
</tr>
<tr>
<td>testing</td>
<td>testing</td>
</tr>
<tr>
<td>testing</td>
<td> </td>
</tr>
</table>
</body>
Could there be something else on the page that might be conflicting?
Lead to problem in case We have Only TD empty and all other TD is Filled
I'm change the Code to make this in its consideration
<script type="text/javascript">
$(document).ready(function () {
$('tr').each(function () {
var totalTDs = $(this).find('td').length;
var emptyTDS = 0;
$(this).find('td').each(function () {
if ($(this).text().trim() == "") {
emptyTDS += 1;
};
});
if (emptyTDS == totalTDs) {
$(this).remove();
}
});
});
</script>
Try this:
var td = $(this).find('td:empty');
if ( td.length > 0 ) $(this).remove();
http://api.jquery.com/empty-selector/
That said, you really want to do this on the server side. It'll look ugly on the client side because you'll have the empty rows messing things up until the document ready event is fired.