0

How can I add rows <tr> in to a table a any level(Top/Bottom/In between) using Javascript/jQuery ?

1

3 Answers 3

1
$(html).insertBefore($('table tr').eq(index));

Will insert some html before the tr with index specified.

A small demo

Sign up to request clarification or add additional context in comments.

4 Comments

Is the order of the trs in $('table tr') guaranteed?
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?
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')
but how do I put in the table element in this line? $('<tr><td>test</td></tr>').insertBefore(tbl_elm.eq(0));
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

@StuperUser because I didn't know that method, although this method exists since jquery 1.0.
0

http://api.jquery.com/prepend/

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.