3
I need to add a row at a specific table position, using Javascript.
Example:
<table>
<tr><td>Teste</td></tr>
<!-- Inserir linha aqui! -->
<tr id="id_2">
<td>Teste 2</td>
</tr>
</table>
3
I need to add a row at a specific table position, using Javascript.
Example:
<table>
<tr><td>Teste</td></tr>
<!-- Inserir linha aqui! -->
<tr id="id_2">
<td>Teste 2</td>
</tr>
</table>
1
Using jQuery, you can use insertBefore
, thus:
$("<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>
0
Javascript has its own methods for tables that make it easier. You can add a new line simply with
var tr = table.insertRow(idIndex);
In your case you can do so:
var idIndex = document.getElementById('id_2').rowIndex;
var table = document.querySelector('table');
var tr = table.insertRow(idIndex);
tr.innerHTML = '<td>Teste intermédio...</td>';
Browser other questions tagged javascript html
You are not signed in. Login or sign up in order to post.
How exactly would this be? It wouldn’t be much easier to add it by html even?
– Raul Correia