Add a line before another line that has an ID

3

I need to add a line 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>
    
asked by anonymous 20.05.2015 / 22:18

2 answers

1

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>
    
20.05.2015 / 22:21
0

JavaScript has its own methods for tables that make this easy. You can join a new line simply by

var tr = table.insertRow(idIndex);

In your case you can do this:

var idIndex = document.getElementById('id_2').rowIndex;
var table = document.querySelector('table');
var tr = table.insertRow(idIndex);
tr.innerHTML = '<td>Teste intermédio...</td>';

example: link

Read about this ( MDN in English ):

20.05.2015 / 22:36