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>
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>
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>
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>';