Reputation: 283
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
Upvotes: 6
Views: 20315
Reputation: 8253
More easy way to handle this question
<table id="table1">
<thead>
<tr>
<th style='width: 80px'>Mon</th>
<th style='width: 80px'>Tue</th>
<th style='width: 80px'>Wed</th>
<th style='width: 80px'>Thr</th>
<th style='width: 80px'>Fri</th>
<th style='width: 80px'>Sat</th>
<th style='width: 80px'>Sun</th>
</tr>
</thead>
<tfoot>
<tr>
<td></td>
</tr>
</tfoot>
<tbody>
</tbody>
</table>
<script>
$(document).ready(function () {
test($('#table1'));
});
function test(table) {
$.each($(table).find("th"), function (key, val2) {
alert(val2.innerHTML);
alert($(val2).html());
});
}
</script>
Upvotes: 0
Reputation: 476
With jQuery normal CSS selector such as $('#MyTbl thead th')
works. But you can also use scoped selector. To use scoped selector, you mention the scope as second argument as
$('th','thead').css('color','red');
Here second argument thead
provides the scope.
See this fiddle for example
Upvotes: 2
Reputation: 6202
No Jquery 2018
let headers = document.querySelectorAll("#myTbl > thead > tr > th")
Upvotes: 4
Reputation: 14827
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
Upvotes: 10
Reputation: 283
Oh ! I missed the "tr".
I solved it the following way:
headers = $('#MyTbl').find('thead > tr > th').get();
Upvotes: 0
Reputation:
You can do it like this;
$('#MyTbl thead').find('th');
OR
$('#MyTbl thead th').each(function() {
// Your code per th here
});
Upvotes: 2