0

I'm trying to create a javascript table with rows of 10 from an array of images but with no luck. The table works but each cell just has [object HTMLImageElement] instead of the image.

The code I tried is below.

for(var i=0; i<myArray.length; i++){
    myArray[i] = new Image();
    myArray[i].src = i + '.gif'; 
}

document.writeln('<table border = 1 >');
for(var j=0; j<myArray.length; j++){
    if(j%10==0 && j!==0){
    document.writeln('</tr><tr>');
    }
    document.writeln('<td >' + myArray[j] + '</td>');
}
document.writeln('</tr></table>');

2 Answers 2

2

Look at those two lines from your code:

myArray[i] = new Image();

document.writeln('<td >' + myArray[j] + '</td>'); // wrong - myArray has to be a string

So, myArray is an image, but in the second line you're trying to make it a string - "<td>" + myArray[j] + "<td>" - this is a way to concatenate strings, not objects. (in this case, myArray[i] is implicitly converted to a string - "htmlImageElement" or whatever)

What you need is to display an <img> tag with the src attribute set to the one in myArray[i], i.e.:

document.writeln('<td ><img src="' + myArray[j].src + '" /></td>');
Sign up to request clarification or add additional context in comments.

Comments

0

One way to do this is this:

$(document.createElement('table'));
var result = "";
for (let i = 0; i < myArray.length; i++){
    result+= '<tr><td><img src="' + myArray[i] + '" alt=""/></td></tr>'
}
$('#table').append(result);

Or this:

$(document.createElement('table'));
var result = "";
myArray.map(function(item){
    result+= '<tr><td><img src="' + item + '" alt=""/></td></tr>'
})
$('#table').append(result);

3 Comments

Ok, thanks, I get the string vs object explanation (I think) so have amended that line. What I get now is a table of broken image icons instead of my images so I must be close but have missed something along the way. Any suggestions greatly appreciated.
Of course I could always just include the .src as stated above and it works perfectly. Now resolved, Many thanks.
Good to know! Can you mark my answer as accepted please? Also, I've tried my solution and I didn't get any broken images, did you still use myArray[i] = new Image()? As this is not necessary, assuming inside myArray are a bunch of image urls.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.