How do I select all <th> elements of class “sortasc” within a table with a specific id?
-
01-07-2019 - |
Question
Let's say I have the following HTML:
<table id="foo">
<th class="sortasc">Header</th>
</table>
<table id="bar">
<th class="sortasc">Header</th>
</table>
I know that I can do the following to get all of the th elements that have class="sortasc"
$$('th.sortasc').each()
However that gives me the th elements from both table foo and table bar.
How can I tell it to give me just the th elements from table foo?
Solution
table#foo th.sortasc
OTHER TIPS
This is how you'd do it with straight-up JS:
var table = document.getElementById('tableId');
var headers = table.getElementsByTagName('th');
var headersIWant = [];
for (var i = 0; i < headers.length; i++) {
if ((' ' + headers[i].className + ' ').indexOf(' sortasc ') >= 0) {
headersIWant.push(headers[i]);
}
}
return headersIWant;
The CSS selector would be something like '#foo th.sortasc'. In jQuery that would be $('#foo th.sortasc').
With a nested table, like:
<table id="foo">
<th class="sortasc">Header</th>
<tr><td>
<table id="nestedFoo">
<th class="sortasc">Nested Header</th>
</table>
</td></tr>
</table>
$('table#foo th.sortasc') will give you all the th's because you're using a descendant selector. If you only want foo's th's, then you should use the child selector - $('table#foo > th.sortasc').
Note that the child selector is not supported in CSS for IE6, though JQuery will still correctly do it from JavaScript.