views:

518

answers:

4

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?

+6  A: 

table#foo th.sortasc

Fuzzy76
Crud. I figured it was easy but I didn't think it was that easy.
Mark Biek
A: 

The CSS selector would be something like '#foo th.sortasc'. In jQuery that would be $('#foo th.sortasc').

pjesi
+1  A: 

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;
levik
A: 

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.

Mark Brackett
Also note that if your th elements are within a thead or tbody or tfoot, this will fail. You'll want $$('table#foo > th.sortasc, table#foo > thead th.sortasc, table#foo > tbody th.sortasc, table#foo > tfoot th.sortasc'), which is a bit unweildy...
eyelidlessness