user4571629
user4571629

Reputation: 450

for each table push to array

I'm a beginner with code, I'm trying to run on this table and get the text from each .winner class and push it to an Array,

so instead of getting:
["aa","aa","dd"]

I'm getting
["aaaadd","aaaadd","aaaadd"]

$(document).ready(function(){

    var arr = [];
    var winner = $('.winner').text() ;

     for ( i = 0; i < $('table').length ; i++ ) {           
        arr.push(winner);
     }

     console.log(arr);      

});

HTML:

    <table>      
        <tr>
            <td>#</td>
            <td class="winner">aa</td>
            <td>bb</td>
            <td>cc</td>
            <td>dd</td>
        </tr>
   </table>

   <table>      
        <tr>
            <td>#</td>
            <td class="winner">aa</td>
            <td>bb</td>
            <td>cc</td>
            <td>dd</td>
        </tr>
   </table>

   <table>      
        <tr>
            <td>#</td>
            <td class="winner">dd</td>
            <td>cc</td>
            <td>bb</td>
            <td>aa</td>
        </tr>
   </table>

I guess something is wrong with my for loop

Upvotes: 1

Views: 3152

Answers (3)

Oleksandr T.
Oleksandr T.

Reputation: 77482

var arr = [];

$('table .winner').each(function () {
   arr.push($(this).text());  
})

Example

or version without class .winner

$('table').each(function () {
   arr.push($(this).find('tr').eq(0).find('td').eq(1).text());
}); 

Example

$('table .winner') - returns 3 td's with class .winner

$(this).text() - get text from current element.

In your example $('.winner').text() returns text "aaaadd", then you get $('table').length (will be 3) and three times push the same text to arr

Upvotes: 1

rubikonx9
rubikonx9

Reputation: 1413

With this:

var winner = $('.winner').text();

You are getting a combined texts from all the td elements marked as winner (see docs here).

Then, for each table, to push this value to the array:

 for ( i = 0; i < $('table').length ; i++ ) {           
    arr.push(winner);
 }

This is actually not necessary. What you want is probably:

var winners = $('.winner');

for (var i = 0; i < winners.length(); ++i) {
    arr.push(winners.eq(i).text());
}

Upvotes: 0

The sentence

var winner = $('.winner')

will give you an array of objects, so you need to loop each of them and call text() method for each one.

Upvotes: 0

Related Questions