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!
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/
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(...);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With