Estoy mostrando una tabla. Algunas celdas de esta tabla están llenas de contenido. Pero hay algunas celdas que están vacías. Lo que quiero es que todas las celdas vacías tengan un color de fondo diferente. ¿Cómo puedo hacer eso? ¿Cómo puedo verificar si un td está vacío?
Puedes usar :empty :
Manifestación:
//You can loop and remove the space charcater from cells document.querySelectorAll('table tr > td').forEach(c => c.textContent = c.textContent.trim()); table, th, td { border: 1px solid black; } table tr > td:empty { background-color: yellow; } <table> <tr> <th>Month</th> <th>Savings</th> </tr> <tr> <td>January</td> <td>$100</td> </tr> <tr> <td>February</td> <td></td> </tr> <tr> <td>March</td> <td>$90</td> </tr> <tr> <td>May</td> <td> </td> </tr> </table>Puede usar js/jquery para verificar si una celda está vacía o no. En base a eso, puede agregar una clase y darle un background-color a la misma.
O si desea un enfoque solo CSS, puede usar :empty . Pero el problema con :empty es que no considerará un td como vacío si solo hay unos pocos espacios en él. Verifique el fragmento a continuación.
$(document).ready(function () { $("table td").each(function (index, eachCell) { if ($(eachCell).html().trim().length === 0) { $(eachCell).addClass("empty-cell"); } }); }); .empty-cell { background-color: red; } td { border: 1px solid #ddd; padding: 5px; } td:empty { background-color: yellow; } <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table> <tbody> <tr> <td>1</td> <td>2</td> <td>3</td> </tr> <tr> <td>1</td> <td></td> <td>3</td> </tr> <tr> <td>1</td> <td>2</td> <td> </td> </tr> </tbody> </table>