Home > Mobile >  Add 0 on empty td
Add 0 on empty td

Time:08-09

I'm having trouble finding a way to add 0 to empty <td>'s

In this case I have a table with some empty td's like this: <td></td>.

And the Java script would find those and add a zero. changing to <td>0</td>.

CodePudding user response:

querySelectorAll and forEach

document.querySelectorAll("#tableId tbody td").forEach(td => {
  if (td.textContent.trim() === "") td.textContent = 0;
});
<table id="tableId">
  <tbody>
    <tr>
      <td>1</td>
      <td>1</td>
      <td>1</td>
      <td>1</td>
      <td>1</td>
    </tr>
    <tr>
      <td>1</td>
      <td>1</td>
      <td>1</td>
      <td>1</td>
      <td>1</td>
    </tr>
    <tr>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
    </tr>
    <tr>
      <td>1</td>
      <td>1</td>
      <td>1</td>
      <td>1</td>
      <td>1</td>
    </tr>
  </tbody>
</table>

CodePudding user response:

Here is a HTML and CSS only solution (no Javascript).

The benefit of not using Javascript:

  1. The Javascript code has to be run after every change to the table. The CSS-only method will always show the 0 in empty cells, and never show the 0 in non-empty cells, no manual updating necessary.
  2. The Javascript code changes empty cells to cells that contain "0", meaning that if you appended content to that cell, the 0 would still be there. With the CSS-only method, the "0" is a pseudo-element, and the td's content is still empty. The user sees a 0, but your code sees an empty box :)

Explanation of the CSS:

A 0 is displayed after any empty td in the table with id tableId.

Technical explanation:

The css selector #tableId tbody td:empty::after selects the after pseudo-element of all empty td elements in tbody elements in the element with id tableId. Then the content attribute of these pseudo-elements is set to 0.

#tableId tbody td:empty::after {
  content: "0";
}
<table id="tableId">
  <tbody>
    <tr>
      <td>1</td>
      <td>1</td>
      <td>1</td>
      <td>1</td>
      <td>1</td>
    </tr>
    <tr>
      <td>1</td>
      <td>1</td>
      <td>1</td>
      <td>1</td>
      <td>1</td>
    </tr>
    <tr>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
    </tr>
    <tr>
      <td>1</td>
      <td>1</td>
      <td>1</td>
      <td>1</td>
      <td>1</td>
    </tr>
  </tbody>
</table>

  • Related