anil naraindas
anil naraindas

Reputation: 15

Iterate through JSON and get image for each data key

I have this table

<table id="player_info">
<tr>
<th>Position</th>
<th>Club</th>
<th>Points</th>
<th>Matches Played</th>
<th>Wins</th>
<th>Draws</th>
<th>Losses</th>
<th>Goals For</th>
<th>Goals Against</th>
<th>Goal Difference</th>
<th>Form</th>
</tr>
</table>

And I have this function which iterates through JSON keys and creates a new table cell with each key. I would like to have the logo of each club appear next to its name in the table cell. The logo URL is stored in the JSON.

My current code

data.api.standings[0].forEach(elements => {

        var tr = document.createElement('tr');

        var img = new Image();

        img.src = elements.logo;

        tr.innerHTML = '<td>' + elements.rank + '</td>' + 
                       '<td>' + elements.teamName +  img + '</td>' + 
                       '<td>' + elements.points + '</td>' + 
                       '<td>' + elements.all.matchsPlayed + '</td>' + 
                       '<td>' + elements.all.win + '</td>' + 
                       '<td>' + elements.all.draw + '</td>' + 
                    '<td>' + elements.all.lose + '</td>' + 
                    '<td>' + elements.all.goalsFor + '</td>' + 
                    '<td>' + elements.all.goalsAgainst + '</td>' + 
                    '<td>' + elements.goalsDiff + '</td>' + 
                    '<td>' + elements.forme + '</td>';

        table.appendChild(tr);

    });

However I am getting the team name and [object HTMLImageElement] and no image.

Upvotes: 0

Views: 331

Answers (1)

Gene Sy
Gene Sy

Reputation: 1685

In your case you can do this instead

var img = '<img src="' + elements.logo + '" />'

instead of making an img element

Upvotes: 1

Related Questions