How can I add rows <tr> in to a table a any level(Top/Bottom/In between) using Javascript/jQuery ?
3 Answers
$(html).insertBefore($('table tr').eq(index));
Will insert some html before the tr with index specified.
A small demo
4 Comments
StuperUser
Is the order of the
trs in $('table tr') guaranteed?StuperUser
eq "Reduce[s] the set of matched elements to the one at the specified index.", but can the order of the set of matched elements in the results $('table tr') be the same each time and be from the top of the table each time?Jishnu A P
as far i know the order of the jQuery objects in
$('table tr') will be the same as the order of trs in the table, because jQuery traverses down the table node to make the object $('table tr')clarkk
but how do I put in the table element in this line? $('<tr><td>test</td></tr>').insertBefore(tbl_elm.eq(0));
- to append to the bottom:
you have nothing to do, because you just have to find the parent element and then append it.
- to append to the top:
well, it is more complicated, but I think is possible. One way is following:
find the parent element from the rows and read all rows into an extra variable. Fortunatly the result will be an array of object. Then create a new row element and use the method unshift() to put this at the begin of the array. Clean table's body and then add each element to body again.
1 Comment
Reporter
@StuperUser because I didn't know that method, although this method exists since jquery 1.0.