admin管理员组

文章数量:1277303

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?

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?

Share Improve this question edited Dec 29, 2011 at 16:42 Rob W 349k87 gold badges807 silver badges682 bronze badges asked Sep 19, 2008 at 12:52 Mark BiekMark Biek 151k54 gold badges159 silver badges201 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 8

table#foo th.sortasc

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.

本文标签: