javascript – add a line<tr> before another line that has an ID

Question:

I need to add a row at a specific position in a table using Javascript .

Example:

<table>
  <tr><td>Teste</td></tr>
  <!-- Inserir linha aqui! -->
  <tr id="id_2">
   <td>Teste 2</td>
  </tr>
</table>

Answer:

Using jQuery, you can use insertBefore , like this:

$("<tr><td>Outro teste</td></tr>").insertBefore("#id_2");

Or with pure Javascript, without jQuery:

var tr = document.createElement("tr"); // cria o elemento tr
var td = document.createElement("td"); // cria o element td
var textnode = document.createTextNode("Outro teste"); 
td.appendChild(textnode); // adiciona o texto na td criada
tr.appendChild(td); // adiciona a td na tr

var tr_id2 = document.getElementById("id_2"); // pega a tr pelo id
// adiciona o elemento criado, a partir do nó pai (no caso <table>)
tr_id2.parentNode.insertBefore(tr, tr_id2); 
<table>
  <tr><td>Teste</td></tr>
  <!-- Inserir linha aqui! -->
  <tr id="id_2">
   <td>Teste 2</td>
  </tr>
</table>
Scroll to Top