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 hidden. Therefore, I wanted to create this script to remove the empty rows and get rid of the space between the other items that are still displayed. I cannot seem to get what I currently have to run and I am unsure as to why. Here is the code:
<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>
Any guidance would be greatly appreciated. Thanks!
The jQuery remove() method is used to remove a row from HTML table. jQuery remove() Method: This method removes the selected elements alongwith text and child nodes. This method also removes data and events of the selected elements.
Accepted Answerhtml = Regex. Replace(html, @"( |\t|\r?\ n)\1+", "$1");
The jQuery function removes all the rows except the first one using the remove() method.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With