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

Asked

Viewed 1,085 times

2

I use the code below to insert a row in 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);

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

3 answers

4


Instead of append use the prepend and put a 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>
<table id="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>

  • Can you give an example of where I should include the tbody I usually create the tables without it?

  • Yes @Italorodrigo, updated the answer.

3

I remember I used to 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 looked it up and found that answer who has two more options.

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>

  • Exactly, rs, is that I copied the code of thead! uhauhauahuahu, Malsssss

Browser other questions tagged

You are not signed in. Login or sign up in order to post.