how to insert a tr in position 0 in a table with jquery?

1

I have a table similar to this one:

$("#nuevo").click(function(){
tr="<tr><td>Nuevo</td><td>1</td></tr>";
  $("#tabla").append(tr);
});
table tr td{
border:1px solid #000
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="tabla" style="border:1px solid #000">
<tr>
<td>Nombre
</td>
<td>Nro
</td>
</tr>
</table>

<button id="nuevo">nuevo</button>

In which rows are added at the bottom of the table.

My question is:

  

How do I insert that new row at the top of the table?

    
asked by Shassain 04.10.2018 в 09:03
source

2 answers

5

Instead of using append() or prepend() you should use the action after() . The first two options you need to put them in a parent element to work, but with the third you can add them after the element you want.

var num = 1;
$("#nuevo").click(function(){
  tr="<tr><td>Nuevo</td><td>"+num+"</td></tr>";
  num++;
  $("#tabla tr:first").after(tr);
});
table tr td{
border:1px solid #000
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="tabla" style="border:1px solid #000">
  <tr>
    <td>Nombre
    </td>
    <td>Nro
    </td>
  </tr>
</table>

<button id="nuevo">nuevo</button>
    
answered by 04.10.2018 / 09:20
source
3

It is important to use the .on () plugin associated with the DOM, since it allows the dynamically generated elements to receive that function for the indicated event, that is, all the elements with a new ID will generate that action when clicking, although the # again be dynamically loaded.

$(document).on("click","#nuevo",function(){
  $("#selector-de-la-tabla").prepend("<tr>Contenido del TR</>");
});

<button id="nuevo">nuevo</button>
    
answered by 04.10.2018 в 09:30