Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I insert a new TR into the MIDDLE of a HTML table using JQuery?

I know how to append a new row to a table using JQuery:

var newRow = $("<tr>..."</tr>");
$("#mytable tbody").append(newRow);

The question is how do I create a new row that precedes some existing row.

like image 417
Howard Pinsley Avatar asked Mar 02 '09 17:03

Howard Pinsley


4 Answers

var newRow = $("<tr>...</tr>");
$("#idOfRowToInsertAfter").after(newRow);

The key is knowing the id of the row you want to insert the new row after, or at least coming up with some selector syntax that will get you that row.

jQuery docs on after()

like image 155
matt b Avatar answered Sep 20 '22 16:09

matt b


where_you_want_it.before(newRow)

or

newRow.insertBefore(where_you_want_it)

-- MarkusQ

like image 31
MarkusQ Avatar answered Sep 17 '22 16:09

MarkusQ


Rather than this:

$("#mytable tbody").append(newRow);

you are going to want to do something like this:

$("#id_of_existing_row").after(newRow);
like image 28
Andrew Hare Avatar answered Sep 16 '22 16:09

Andrew Hare


With:

var newTr = $('<tr>[...]</tr>');

You can…

  1. Insert it after (or before if you so choose) another row for which you know an ID (or whatever other property):

    $('#<id of the tr you want to insert the new row after>').after(newTr)
    
  2. Insert it after a particular row index (indices are 0-based, not 1-based):

    $($('table#<id> tr')[<index>]).after(newTr)
    
  3. …or as you mentioned, the absolute middle is possible:

    var existingTrs = $('table#<id> tr')
    $(existingTrs[parseInt(existingTrs.length / 2)]).after(newTr)
    
like image 25
obeattie Avatar answered Sep 17 '22 16:09

obeattie