Call items inside $ (this)?

Possible duplicate:
How to find an element inside an element

Im starts a loop to go through each row of the table. I want to access the elements inside each row of the table. How to do it?

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>

The code does not 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();

});
+3
source share
6 answers

You can use the method children:

$("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();

});
+8
source

The second parameter to the jQuery function is the context:

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

This will find all descendants td.athat fall into this.

+6
source

"" (.. jQuery), cells.

var trs = document.getElementsByTagName('tr'), l = trs.length, i, tds;
for( i=0; i<l; i++) {
    tds = trs[i].cells;
    // do stuff with tds
]
+3

$(this) , . . :

$this vs $(this) 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();

});
+3
source
$("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();

});
+1
source
$("tr").each(function() {
    var $this = $(this),
        aText = $this.find('.a').text(),
        bText = $this.find('.b').text(),
        cText = $this.find('.c').text();
});
0
source

All Articles