Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

93
Vistas
How to give an empty td a class?

I am displaying a table. Some cells of this table are filled with content. But there are some cells that are empty. What i want is that all empty cells have a different background color. How can i do that? How can i check if a td is empty?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You can use :empty selector:

Demo:

//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>&nbsp; </td>
  </tr>
</table>

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can use js/jquery to check if a cell is empty or not. Based on that you can add a class and give a background-color to the same.

Or if you want a css only approach, you can use :empty selector. But the problem with :empty is that it will not consider a td an empty one if there is just a few space in it. Check the below snippet.

$(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>

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda