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>
.
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>
.
The benefit of not using Javascript:
td
's content is still empty. The user sees a 0, but your code sees an empty box :)A 0 is displayed after any empty td
in the table with id tableId
.
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>
Use querySelectorAll
and forEach
I also suggest to trim the contents
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>