最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Delete empty row in html table - Stack Overflow

programmeradmin1浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 3

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

发布评论

评论列表(0)

  1. 暂无评论