Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

92
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda