Using Javascript to display an array of images in a table

I've been attempting to generate a JavaScript table with rows of 10 using an array of images, but unfortunately, I have not been successful. The issue is that while the table itself appears to be functioning correctly, each cell only displays [object HTMLImageElement] instead of the actual image.

Below is the code that I have attempted:


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>');

Answer №1

Examining the following two lines of code:

myArray[i] = new Image();

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

Therefore, myArray represents an image, but in the second line you are attempting to treat it as a string -

"<td>" + myArray[j] + "<td>"
- this is a string concatenation method, not suitable for objects. (in this scenario, myArray[i] gets implicitly converted to a string like "htmlImageElement" or something similar)

The solution is to showcase an <img> tag with the src attribute containing what's in myArray[i], like so:

document.writeln('<td ><img src="' + myArray[j].src + '" /></td>');

Answer №2

Here are a couple of ways you can achieve this:

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

Alternatively, you can also use:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I'm curious, are there any html rendering engines that can display text-based content using curl-php?

When utilizing PHP cURL to interact with webpages, I often find myself needing to use regular expressions if the page contains AJAX and JavaScript elements. Does anyone have any recommendations for rendering HTML pages and extracting the text-based render ...

Finding the center of a Three.js Scene

I'm trying to find the center of a Scene that I've loaded using ColladaLoader in Three.js. Once I have the center, I want to set it as the target for the Camera. ...

The slideUp function is not functioning as expected

I am trying to implement a slideUp effect on my webpage. Here is the code within my <body> tag: <script> $('#slide_up').click(function(){ $('p.text_study').slideUp('slow', function() { $ ...

What is causing all these network responses to flood my system?

As I send this request Axios.get('./phone.json').then(({data}) => { this.setState({ phone: data }) }) I receive these responses: https://i.sstatic.net/yYttx.jpg However, when executing the same code on a Mac, I do ...

Pulling and showcasing an object in Angular using a remote AJAX call

I am attempting to display an object retrieved remotely through AJAX. The current error I am facing is: ReferenceError: $stateParams is not defined Below is the snippet from services.js: .factory('Games', function() { var games = $.ajax({ ...

Tips for recognizing a faulty CSS line in a WordPress site

Recently, I encountered an issue on my website, yildirimakademi, when using woocommerce to add a product to the shopping cart. While the shopping cart logo appears correctly on the right side of the navbar, I noticed that the image becomes distorted when ...

In CAKEPHP, emphasize a row in a Product table to indicate a comparison condition, without the need for hovering

I've been experimenting with different approaches to make this comparison work. Despite trying various methods, only the "gumboots" string check seems to do the trick. This string represents a product name in the table and proves that PHP is not neede ...

What is the best way to extend the width of an element within a Bootstrap column beyond the column itself?

Apologies for any language errors, but I have a query regarding Bootstrap. I am currently working on making a website responsive and I have a row with 4 columns set up like this: The "seeMore" div is initially hidden and on clicking the boxToggle element ...

Exploring JSON Data with NativeScript

As a newcomer to NativeScript and JSON, I am currently facing challenges in accessing data from my JSON file. My main goal right now is to simply log some of the data for debugging purposes. Below is the code snippet from my view-model: var config = requ ...

After diligently following every step on OneCheckout and getting no response when placing an order, I decided to upgrade my Magento version from 1.6.1.0 to 1.8

After upgrading the Magento version from 1.6.1.0 to 1.8.0, everything seems to be working smoothly. However, customers are facing an issue during checkout where they can't actually place their order. Despite following all the steps correctly, when t ...

Conceal a request URL within JavaScript through the use of Laravel/Ajax

I have an idea that I'm not sure is great or even feasible, but I really need to make it work. I am attempting to obfuscate a URL that needs to be used in a Javascript function as a parameter. This is what I currently have: <script> myFunction ...

Verify that each element in the array has been assigned a value

Here is the array I am working with: $my_array = array ( 'city' => $this->input->post('city'), 'country' => $this->input->post('country'), & ...

Navigating through the array generated by a MongoDB aggregation request

Good day everyone, I'm currently facing challenges with aggregation queries in MongoDB 3.4. The task at hand requires me to push the results of my aggregation query into an empty array named categories. I've managed to achieve this successfully ...

Is there a way I can retrieve a cookie stored in an Express middleware even if the req.cookies object is returning empty?

I am currently working on validating a cookie using the cookie-parser module to verify if the user is authenticated to access restricted routes within my application. My technology stack includes NodeJS and Express for the server, and Sveltekit for the fro ...

How to implement horizontal scrolling in an Ionic/AngularJS app

Struggling to implement a scroll navigation with ionic, but encountering issues with navigation and styling. Seeking guidance on how to achieve the desired outcome: Desired navigation look: https://i.sstatic.net/vQ2CS.png Current implementation showcases ...

What is the fastest and most efficient method to confirm that all rows in a 2D array are of equal length?

Imagine you have a 2D array like this: const matrixRegular = [ ['a', 'b', 'c'], ['e', 'f', 'g'], ]; Now, let's think about how we can check if every row in this matrix has the same ...

A guide on retrieving data with JSONP, Ajax, and jquery

I am having trouble retrieving data from an API using JSONP. I enter an ISBN number into an input box and attempt to fetch the data, but I keep encountering an error message stating "Cannot read property 'title' of undefined". Can anyone assist m ...

Steps to create a Runtime array and assign it a name from a predefined list

There's a list called list_1 = ["File_A","File_B","File_C","File_D"] I'm looking to execute a loop and create four arrays: File_A = np.array(0) File_B = np.array(0) File_C = np.array(0) File_D = np.arr ...

Issues with using hooks in a remote module in Webpack 5 module federation

I am attempting to create a dynamic system at runtime using Module Federation, a feature in webpack 5. Everything seems to be working well, but I encounter a multitude of 'invalid rule of hooks' errors when I add hooks to the 'producer' ...

The content of the served HTML Table remains static and requires a server restart for any updates to

Having been encountering this issue for quite some time, I have searched extensively for a solution but to no avail. Therefore, I am taking matters into my own hands and posing the question myself. The dilemma is as follows: https://i.stack.imgur.com/UZrQ ...