简体   繁体   中英

Show/hide table row if a child DIV is empty

I have a table with multiple entries. After each entry table row is an edit table row, with a column spanned cell, inside of which is a DIV which HTML is dynamically loaded into. The problem is that having all these empty table rows causes a lot of extra whitespace to appear on the page when it's rendered.

I understand I can't dynamically load HTML directly into the cell, so I have a DIV in it which I load the content into.

I want to hide any table row while the child DIV in it is empty, and show that table row once information has been dynamically loaded into the child DIV. This dynamically loaded information can also removed so I need it to be hidden again once it's empty again.

<table width="100%">
  <tbody>
    <tr>
      <td>A</td>
      <td>B</td>
      <td>C</td>
    </tr>
    <tr style="display: none;">
      <td colspan="3"><div></div></td>
    </tr>
  </tbody>
</table>



$("tr").each(function() {
    if (this.children().filter(":empty").length) {
        this.hide();
    } else {
        this.show();
    }
});
  • The div isn't a child, it's a grandchild, thus children() won't find the div s. Use the context or find instead.

  • You are operating hide and show on the DOM element, not the jQuery element. You need to wrap it in jQuery first.

Therefore, run this code everytime you load something :

//find empty divs and hide it's tr
$("div:empty").closest('tr').hide();

//find non-empty divs and show it's tr
$("div:not(:empty)").closest('tr').show();

And look ma! No loops! No each ! :D

You should use $(this) instead of this .

Reason being: $(this) is a JQuery object, which allows you to call JQuery methods like .children() and .filter(":empty") on it, whereas this is only a Javascript object...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM