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

800
Visualizações
jQuery dataTables row.add with different classes on outer td based on content

I want to add entries to a jQuery Datatable with row.add and while adding (or afterwards if not possible while adding) change the class of the outer <td> based on the content. Values > 5 should get the class color-green, values below 5 color-red

var mTableROH   = $('.mm-table.ROH').DataTable(
    {
        dom: 'Bfrtip',
        "stateSave": true,

    }
);

for(let i = 0; i < 10; i++)
{
  mTableROH.row.add(
          [
             (Math.random() * 10).toFixed(2),
             (Math.random() * 10).toFixed(2),
             (Math.random() * 10).toFixed(2),
             (Math.random() * 10).toFixed(2),
             (Math.random() * 10).toFixed(2),
             (Math.random() * 10).toFixed(2),
             (Math.random() * 10).toFixed(2),
             (Math.random() * 10).toFixed(2),
          ]
  );
 
}
 mTableROH.columns.adjust().draw();

    
.color-red{
  color: red;
}

color-green{
  color: green;
}
<link rel="stylesheet" href="https://cdn.datatables.net/1.11.5/css/jquery.dataTables.min.css">

                            <table id="mm-table-roh" class="table table-striped table-bordered mm-table ROH">
                                <thead>                             
                                    <tr>
                                        <th>Value 1</th>
                                        <th>Value 2</th>
                                        <th>Value 3</th>
                                        <th>Value 4</th>
                                        <th>Value 5</th>
                                        <th>Value 6</th>
                                        <th>Value 7</th>
                                        <th>Value 8</th>
        
                                    </tr>
                                </thead>
                                <tbody>
                                
                                </tbody>

                            </table>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>

How to add those classes while adding new rows like this?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

So after reading your comment I did more research and I think this is better since I believe you are concerned about performance:

var mTableROH = $('.mm-table.ROH').DataTable({
    dom: 'Bfrtip',
    "stateSave": true,
    "createdRow": function(row, data, dataIndex) { // add a callback function
        const length = row.children.length;
        for (let i = 0; i < length; i++) {
            row.children[i].className = data[i] > 5 ? "color-green" : "color-red";
        }
    }
});

// Below remains the same as my previous answer
for (let i = 0; i < 10; i++) {
    let randomNumbers = [];
    for (let j = 0; j < 8; j++) {
        randomNumbers.push((Math.random() * 10).toFixed(2));
    }
    mTableROH.row.add(randomNumbers)
}
mTableROH.columns.adjust().draw();

Basically we can just add a createdRow (https://datatables.net/reference/option/createdRow) property inside the object argument of .DataTable() that is executed when a TR element is created (and all TD child elements have been inserted)

Also another change is this time it's replacing all the classes of the td elements instead of adding a class, if you just wanna add the class you can replace

row.children[i].className = data[i] > 5 ? "color-green" : "color-red";

with

row.children[i].classList.add(data[i] > 5 ? "color-green" : "color-red");
about 4 years ago · Juan Pablo Isaza Relatório

0

While I'm at this let me also help you simplify your for loop so that you don't have to repeat (Math.random() * 10).toFixed(2) 8 times

for (let i = 0; i < 10; i++) {
    let randomNumbers = [];
    for (let j = 0; j < 8; j++) {
        randomNumbers.push((Math.random() * 10).toFixed(2));
    }
    mTableROH.row.add(randomNumbers)
}
mTableROH.columns.adjust().draw();

Right after the above code, you can write this, this adds the class after the adding of the table cells:

$(".mm-table.ROH tbody td").each(function() {
     const value = parseFloat($(this).text());
     $(this).addClass(value > 5 ? "color-green" : "color-red");
});

What it does is using the jQuery selector we can retrieve all the td elements inside the tbody of the element with class .mm-table.ROH, and using the .each() function, we pass in a function that gets executed for each td element. So we retrieve the value from the .text() property of $(this) (which refers to the current td element), and then add the corresponding class based on if the value is more than 5 or not.

about 4 years ago · Juan Pablo Isaza Relatório

0

So, here is an approach on how to tackle your problem. Get all your cells with document.querySelectorAll and then you should do a forEach method in order to get the innerHTML of every cell. Thus this will allow you to get the string and from there on you can do a parseFloat() method to get the real numeric value of the cell. At last, you can do a conditional statement which checks if the value is below or more than 5. If it is likewise, you assign the class with classList.add() inside every cell you need. Cheers

var mTableROH = $('.mm-table.ROH').DataTable({
  dom: 'Bfrtip',
  "stateSave": true,
   "createdRow": function(row, data, dataIndex) { // add a callback function
    const length = row.children.length;
    for (let i = 0; i < length; i++) {
         (data[i] > 5) ? row.children[i].classList.add("color-green") : row.children[i].classList.add("color-red");
    }
}
});

for (let i = 0; i < 10; i++) {
  mTableROH.row.add(
      [
        (Math.random() * 10).toFixed(2),
        (Math.random() * 10).toFixed(2),
        (Math.random() * 10).toFixed(2),
        (Math.random() * 10).toFixed(2),
        (Math.random() * 10).toFixed(2),
        (Math.random() * 10).toFixed(2),
        (Math.random() * 10).toFixed(2),
        (Math.random() * 10).toFixed(2),
      ]).draw()
    .nodes()
    .to$()
    .addClass('row');
}

mTableROH.columns.adjust().draw();
.color-red {
  color: red;
}

.color-green {
  color: green;
}
<link rel="stylesheet" href="https://cdn.datatables.net/1.11.5/css/jquery.dataTables.min.css">

<table id="mm-table-roh" class="table table-striped table-bordered mm-table ROH">
  <thead>
    <tr>
      <th>Value 1</th>
      <th>Value 2</th>
      <th>Value 3</th>
      <th>Value 4</th>
      <th>Value 5</th>
      <th>Value 6</th>
      <th>Value 7</th>
      <th>Value 8</th>

    </tr>
  </thead>
  <tbody>

  </tbody>

</table>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>

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