Get all th tags under thead only
Solution 1
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
Solution 2
No Jquery 2018
let headers = document.querySelectorAll("#myTbl > thead > tr > th")
Solution 3
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
Solution 4
Try
var tableHead = $('#MyTbl thead tr th');
DA_Prog
Updated on September 15, 2022Comments
-
DA_Prog over 1 year
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
-
Admin about 11 yearsProbably costed you more time to post the question than try solving your own problem. Good luck coding :)
-
Dipesh Parmar about 11 yearshummm > is the parent child selector...you were using thead > th that will always return null asl long as there is no direct child which is TH.