Reputation: 7728
What is the jQuery syntax for adding rows in between existing HTML table rows?
<Table id="TEST"> <tr>1</tr> <tr>2</tr> </table>
I want to add
<tr>xx</tr>
in between 1 and 2
eg:
<tr>1</tr> **<tr>xx</tr>** <tr>2</tr>
and please note here there is no id for rows.
Correcting the final look
before
<table id=Test><tr> <td>1 </td> </tr><tr> <td>2 </td> </tr></table>
after
<table id=Test><tr> <td>1 </td> </tr> <tr> <td>xx </td> </tr> <tr> <td>2 </td></tr></table>
Upvotes: 4
Views: 8024
Reputation: 166021
Assuming you are looking for a way to insert the new row after the first existing row (and you're not looking for a way to insert it in a place described by the contents of existing rows) you can use after
to insert the content, and eq
to reduce the set of matched elements to the one at the required index:
$("#TEST tr").eq(0).after("<tr><td>x</td></tr>");
Note that I've added in a td
element, since it's invalid to have text nodes as children of tr
elements.
It's also worth noting the wide variety of ways to select the "first" element with jQuery. In the 5 answers to this question we see 3 different methods, and there are even more than that. Using .eq(0)
is the most efficient.
Upvotes: 0
Reputation: 4103
The answer to your question (taking it literally) is:
$("table#test tr:contains('1'").after('<tr>xx</tr>');
This means: add "xx" after the <tr>
that contains "1" in the table with id "test".
I guess that's not exactly what you need, can you tell us what do you exactly want to do?
There are various ways to add content to elements. I suggest to have a look at the jQuery Doc, especially at the DOM Insertion, Around, the DOM Insertion, Inside and the DOM Insertion, Outside.
Upvotes: 0
Reputation: 123397
especially for the sake of consistency amongs browser you should wrap all your tr
inside a tbody
element. then you can after()/insertAfter()
the new row (after the first one) or before()/insertBefore()
the row (before the latest one).
http://api.jquery.com/after/
http://api.jquery.com/before/
http://api.jquery.com/insertAfter/
http://api.jquery.com/insertBefore/
example of
insertAfter: $('<tr>xx</tr>').insertAfter($('tr:first'));
after: $('tr:first').after('<tr>xx</tr>');
Upvotes: 0
Reputation: 102438
Something like this:
$('#TEST > tbody > tr').eq(0).after('<tr>xx</tr>');
Upvotes: 5
Reputation: 6239
$('#test tr').first().append('<tr>xx</tr>');
You can replace first()
with eq(n)
(in which n
is a number from 0
to n-1
rows of the table) and add the row after any existing row.
Upvotes: 0
Reputation: 35213
$('#TEST tr:gt(0)').after('<tr>xx</tr>');
gt
stands for greater than. Note that index of the rows starts at 0, not 1.
Upvotes: 0