How can I delete rows that are blank. I only managed remove a row using deleteRow()
method, but I need to remove only empty ones.
<table border="1">
<tr>
<td></td>
</tr>
<tr>
<td>testing</td>
</tr>
<tr>
<td></td>
</tr>
</table>
How can I delete rows that are blank. I only managed remove a row using deleteRow()
method, but I need to remove only empty ones.
<table border="1">
<tr>
<td></td>
</tr>
<tr>
<td>testing</td>
</tr>
<tr>
<td></td>
</tr>
</table>
Share
Improve this question
edited Jan 25, 2019 at 18:25
Brian Tompsett - 汤莱恩
5,89372 gold badges61 silver badges133 bronze badges
asked Jan 25, 2019 at 17:58
Rokki balboaRokki balboa
231 silver badge6 bronze badges
2
- foreach($('table tr'), function(){ if($this.find('td').val()==''){ // your code here }}) – s_p Commented Jan 25, 2019 at 18:03
-
Show us your code and we will try to help you. One possible idea might be to check for
$('tr').text()==''
. – Carsten Massmann Commented Jan 25, 2019 at 18:04
2 Answers
Reset to default 3Is this the sort of thing you are looking for?
What we are doing is getting all of the td
checking if they are empty and then removing them if they do not have any text inside.
$("td").each(function() {
if (this.innerText === '') {
this.closest('tr').remove();
}
});
td {
height: 20px;
}
<script src="https://cdnjs.cloudflare./ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table border="1">
<tr>
<td></td>
</tr>
<tr>
<td>123</td>
</tr>
<tr>
<td></td>
</tr>
<tr>
<td>456</td>
</tr>
</table>
Instead of deleteRow() you can use removeChild():
document.querySelectorAll('table tr').forEach(function(e, i) {
if (e.textContent.trim().length == 0) { // if row is empty
e.parentNode.removeChild(e);
}
})
// in jQuery:
//$('table tr').filter((i, e) => e.textContent.trim().length == 0).remove();
<table border="1">
<tr>
<td></td>
</tr>
<tr>
<td>testing</td>
</tr>
<tr>
<td></td>
</tr>
</table>