I have a simple html table, which containg thead, tbody and tfoot. I want to select using javascript or jquery all th tags only within the thead. So far, I found a way to get either all th in table or the thead itself.
My table:
<table id="MyTbl" class="display">
<thead>
<tr>
<th>
ID
</th>
<th>
Name
</th>
<th>
Desc
</th>
</tr>
</thead>
<tbody id="MyTableBody">
</tbody>
<tfoot>
<tr height="27px">
<th class="TDHMain">
FILTER ID
</th>
<th class="TDHMain">
FILTER NAME
</th>
<th class="TDHMain">
FILTER DESC
</th>
</tr>
</tfoot>
</table>
My javascript:
var table = document.getElementById('MyTbl');
var tableHeader = table.getElementsByTagName('thead');
var headers = tableHeader.getElementsByTagName('th'); //This one doesn't work. No such a method for the thead tag
I also tried the following code:
headers = $('#MyTbl').find('thead > th').get();
But as a result I couldn't really understand how to work with it... It's not an array, there's no foreach function to the headers object I get as a result, and I really couldn't find a way to reach the data.
Is there anyway to get just the th elements within the thead of a table?
Thanks
<th> tag is used to give header in the cell of a table in HTML whereas <thead> tag is used to give the header of a group of a table.
The <thead> tag is used to group header content in an HTML table. The <thead> element is used in conjunction with the <tbody> and <tfoot> elements to specify each part of a table (header, body, footer). Browsers can use these elements to enable scrolling of the table body independently of the header and footer.
<td> is allowed inside a <thead> . Permitted content of a <thead> are zero or more <tr> elements. In a <tr> element you can put a <td> and/or <th> element. It doesn't matter.
Quoting the HTML 4 spec: "The TBODY start tag is always required except when the table contains only one table body and no table head or foot sections. The TBODY end tag may always be safely omitted."
You can push all your text into an array:
var thArray = [];
$('#MyTbl > thead > tr > th').each(function(){
thArray.push($(this).text())
})
Then retrieve it like this:
thArray[0]; // This will give you ID
Demo
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