tags:

views:

66

answers:

8
+3  Q: 

JQuery - Set TBODY

Hello,

I have a table defined as follows:

<table id="myTable" cellpadding="0" cellspacing="0">
  <thead><tr>
    <th>Date</th>
    <th>First Name</th>
    <th>Last Name</th>
  </tr></thead>

  <tbody>
    <!-- rows will go here -->
  </tbody>
</table> 

I am trying to dynamically populate 'myTable' at runtime via JavaScript. To accomodate for this, I am using JQuery. I want to write some HTML into the tbody element within 'myTable'. However, I am having problems understanding how to do this with the selectors. I know that I can get 'myTable' using:

$("#myTable")

I know that I can set the HTML of myTable by using the following:

$("#myTable").html(someHtmlString);

However, that sets the HTML of the entire table. In reality, I just want to set the HTML within the TBODY of 'myTable'. How do I do this with JQuery?

Thank you!

A: 

Try:

$("#myTable tbody")
ungarida
+2  A: 

Find the tbody element and use append, if you want to add rows, or html, if you want to replace all rows.

$('#myTable tbody').append(someRowHtml);

$('#myTable tbody').html(someRowHtml);

Note that if you have more than one tbody element you'll also need to use the :first selector (or nth-child -- don't forget that, that although it's zero-based, you have a thead element) to get the correct one.

$('#myTable tbody:first').append(...);
tvanfosson
There's no need to use a function to find the tbody.
Gert G
@Gert G - I realized that right after I wrote it. If you did already have a reference to the table, though, it would be the way to go.
tvanfosson
+1  A: 
$("#myTable tbody").html(someHtmlString);
Reigel
+8  A: 

You would use:

$("#myTable > tbody");

which selects tbody elements that are the direct descendant of #myTable.

Alternatively, you could use:

$('tbody', '#myTable');

which finds all tbody elements within the context of #myTable.

In jQuery, there are often several ways to accomplish what you need.

Another way, would be to do:

$('#myTable').children('tbody');

which is effectively the same as my first solution above.

jQuery has great docs:

Selectors: http://api.jquery.com/category/selectors/

Traversing: http://api.jquery.com/category/traversing/

patrick dw
A: 

give your tbody a id and then do the same with it as you have done with your table

< tbody id='myTbody' >

sushil bharwani
A: 

Try to use $("#myTable > tbody").html("");

Develman
A: 

You can do like:

$("#myTable tbody").html(html_here);
Sarfraz
A: 
$('#myTable tbody').append('<tr><td>foo</td><td>bar</td></tr>');
Richard Rail