Rokki balboa
Rokki balboa

Reputation: 23

Delete empty row in html 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>

Upvotes: 2

Views: 6838

Answers (2)

Web Nexus
Web Nexus

Reputation: 1158

Is 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.com/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>

Upvotes: 3

gaetanoM
gaetanoM

Reputation: 42054

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>

Upvotes: 1

Related Questions