How to insert row at the top of a table using JS?

2

I use the following code to insert a row into a table:

var linha = "<tr>";
linha += '<td class="cnes">' + cnes + '</td>';
linha += '<td class="cbo">' + cbo + '</td>';
linha += '<td class="profissional">' + profissional + '</td>';
linha += '<td class="procedimento">' + procedimento + '</td>';
linha += '<td class="idade">' + idade + '</td>';
linha += '<td class="quant">' + quant + '</td>';
linha += '<td><button class="btn btn-danger" style="text-align:center;" onclick="remove(this)">Excluir</button></td>'
linha += '</tr>';

$("#tabelaProducao").append(linha);

Being that it inserts at the end of it and I need it to be inserted in the second line (the first is the column header). How do I?

    
asked by anonymous 17.07.2017 / 20:09

3 answers

4

Instead of append use prepend and put tbody to separate body header:

...
$("#tabelaProducao tbody").prepend(linha);

Example

var linha = "<tr>";
linha += '<td class="cnes"> Item' + 3 + '</td>';
linha += '<td class="cbo"> Item' + 4 + '</td>';
linha += '</tr>';

$("#tabelaProducao tbody").prepend(linha);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><tableid="tabelaProducao">
  <thead>
    <tr>
      <th>Titulo 1</th>
      <th>Titulo 2</th>
    </tr>

  </thead>
  <tbody>
    <tr>
      <td>Item 1</td>
      <td>Item 2</td>
    </tr>  
  </tbody>
</table>
    
17.07.2017 / 20:14
3

I remember that I used insertBefore .

var linha = "<tr>";
linha += '<td class="cnes">' + cnes + '</td>';
linha += '<td class="cbo">' + cbo + '</td>';
linha += '<td class="profissional">' + profissional + '</td>';
linha += '<td class="procedimento">' + procedimento + '</td>';
linha += '<td class="idade">' + idade + '</td>';
linha += '<td class="quant">' + quant + '</td>';
linha += '<td><button class="btn btn-danger" style="text-align:center;" onclick="remove(this)">Excluir</button></td>'
linha += '</tr>';

$("#tabelaProducao").insertBefore(linha);

I've researched and found this answer that has two more options.

    
17.07.2017 / 20:14
3

$("table > tbody").prepend("<tr><td>Linha Nova 1</td><td>Linha Nova 2</td><td>Linha Nova 3</td>   </tr>")
<script src="https://code.jquery.com/jquery-3.2.1.js"></script>
<table>
  <thead>
    <tr>
      <th>Coluna 1</th>
      <th>Coluna 2</th>
      <th>Coluna 3</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Linha 1</td>
      <td>Linha 2</td>
      <td>Linha 3</td>
    </tr>
  </tbody>
    
17.07.2017 / 20:20