简体   繁体   中英

How to append tr to top of table

how can i append a new tr to the top of the table instead of under other tr.

Example:

<table width='100%'>
<tr><td>something</td><td>else here</td></tr>
<tr><td>something2</td><td>else here2</td></tr>
</table>

After a click event in jQuery, how can i place <tr><td>something3</td><td>else here3</td></tr> at the top of the table so it now looks like

<table width='100%'>
<tr><td>something3</td><td>else here3</td></tr>
<tr><td>something</td><td>else here</td></tr>
<tr><td>something2</td><td>else here2</td></tr>
</table>

Any help on this would be greatly appreciated.

$('table').prepend('<tr><td>something3</td><td>else here3</td></tr>');

or...

$('<tr><td>something3</td><td>else here3</td></tr>').prependTo('table');

More info on 'prepend': http://docs.jquery.com/Manipulation/prepend

More info on 'prependTo': http://docs.jquery.com/Manipulation/prependTo

This JS is IE specific at the moment, but it shouldn't be too hard to make it multi-browser compatible.

<html>
<body>
<script language="JavaScript">
function function1() {
   var myRow = document.all.myTable.insertRow(0);
   var myCell = myRow.insertCell();
   myCell.innerText = "The added cell"; 
} 
</script>
<table id="myTable" border="1" cellspacing="5" cellpadding="5">
   <tr>
       <td width="100">3</td>
       <td width="100">4</td>
   </tr>
   <tr>
       <td>1</td>
       <td>2</td>
   </tr>
</table>
<button onclick="function1();">Add a cell</button>
</body>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM