Home > other >  Remove table row that have empty cells c#
Remove table row that have empty cells c#

Time:10-06

I have a table created from a WYSIWYG editor and save as a string in C#. When I submit a form, I will map the values to the table cells. However, there are some empty rows that don't have any data. How can I remove these rows, for example the 3 4 row, before returning the html string with either regex or HtmlAgilityPack? Thanks

The table in the string looks like this:

<table>
  <thead>
    <tr>
      <th></th>
      <th>Name</th>
      <th>Age</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1</td>
      <td>John</td>
      <td>18</td>
    </tr>
    <tr>
      <td>2</td>
      <td>Arthur</td>
      <td>20</td>
    </tr>
    <tr>
      <td>3</td>
      <td></td>
      <td></td>
    </tr>
    <tr>
      <td>4</td>
      <td></td>
      <td></td>
    </tr>
  </tbody>
</table>

Preview: enter image description here

CodePudding user response:

It's better to manage the empty elements on the frontend than the backend because you don't need to submit them and process them on the backend if you can simply filter them out (or even better validate them before submitting) on the frontend.

Proof-of-concept with JS:

const cells = document.querySelectorAll('td');
const emptyCells = Array.from(cells).filter(cell => cell.innerHTML === '');
emptyCells.forEach(cell => cell.parentNode.remove());
<table>
  <thead>
    <tr>
      <th></th>
      <th>Name</th>
      <th>Age</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1</td>
      <td>John</td>
      <td>18</td>
    </tr>
    <tr>
      <td>2</td>
      <td>Arthur</td>
      <td>20</td>
    </tr>
    <tr>
      <td>3</td>
      <td></td>
      <td></td>
    </tr>
    <tr>
      <td>4</td>
      <td></td>
      <td></td>
    </tr>
  </tbody>
</table>

  • Related