Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery - Set TBODY

Tags:

jquery

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!

like image 854
Villager Avatar asked May 31 '10 13:05

Villager


2 Answers

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/

like image 64
user113716 Avatar answered Oct 30 '22 05:10

user113716


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(...);
like image 27
tvanfosson Avatar answered Oct 30 '22 05:10

tvanfosson