3

Possible Duplicate:
How to find an element within an element

Im running a loop to go through each table row. I want to access the elements inside each table row. How do I do this?

Table:

<table>
<tr> <td class="a">x</td> <td class="b">x</td> <td class="c">x</td> </tr>
<tr> <td class="a">x</td> <td class="b">x</td> <td class="c">x</td> </tr>
<tr> <td class="a">x</td> <td class="b">x</td> <td class="c">x</td> </tr>
<tr> <td class="a">x</td> <td class="b">x</td> <td class="c">x</td> </tr>
</table>

Code doesnt work:

$("tr").each(function(index) {

    // get class a text
    $(this + " td.a").text();

    // get class b text
    $(this + " td.b").text();

    // get class c text
    $(this + " td.c").text();

});
Community
  • 1
  • 1
supercoolville
  • 8,636
  • 20
  • 52
  • 69

6 Answers6

8

You can use children method:

$("tr").each(function(index) {

    // get class a text
    var text1 = $(this).children("td.a").text();

    // get class b text
    var text2 = $(this).children("td.b").text();

    // get class c text
    var text2 = $(this).children("td.c").text();

});
VisioN
  • 143,310
  • 32
  • 282
  • 281
6

The second parameter of the jQuery function is context:

$("td.a", this).text();

This will find all td.a descendants that fall within this.

Sampson
  • 265,109
  • 74
  • 539
  • 565
3

If you were accessing it "normally" (ie. not with jQuery), you can just get the cells property.

var trs = document.getElementsByTagName('tr'), l = trs.length, i, tds;
for( i=0; i<l; i++) {
    tds = trs[i].cells;
    // do stuff with tds
]
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
3

If you need to call $(this) multiple times, you should assign it to a local variable to increase performance. See this post for more information:

$this vs $(this) in jQuery

Finally, you can use .find() for what you are trying to achieve:

$("tr").each(function(index) {

    var $this = $(this);

    // get class a text
    $this.find("td.a").text();

    // get class b text
    $this.find("td.b").text();

    // get class c text
    $this.find("td.c").text();

});
Community
  • 1
  • 1
Curtis
  • 101,612
  • 66
  • 270
  • 352
1
$("tr").each(function(index) {

    // get class a text
    $("td.a", this).text();

    // get class b text
    $("td.b", this).text();

    // get class c text
    $("td.c", this).text();

});
The System Restart
  • 2,873
  • 19
  • 28
0
$("tr").each(function() {
    var $this = $(this),
        aText = $this.find('.a').text(),
        bText = $this.find('.b').text(),
        cText = $this.find('.c').text();
});
jmar777
  • 38,796
  • 11
  • 66
  • 64