DEV Community

vive
vive

Posted on

Easy Ways to Render a List of Images: HTML vs. JavaScript

Hi there 👋

In this guide, I'll show you two approaches to rendering a list of images - one using only HTML and the other using JavaScript. While the HTML-only method works, using JavaScript makes the process much easier!

Let's start with the HTML-only approach.

Imagine you want to display a few images on your website in a list, one by one. Your HTML structure could look as follows:

/* HTML code */
<div class="img-container">
  <img src="link-to-the-image"/>
  <img src="link-to-the-image"/>
  <img src="link-to-the-image"/>
  <img src="link-to-the-image"/>
</div>
Enter fullscreen mode Exit fullscreen mode

Every time you want to add a new image to the list, you need to manually insert a new <img> element with all the attributes.

How can JS make our life easier? Let's see!
With JavaScript we can create an array with the image links and dynamically generate elements.
Here's the updated HTML:

/* HTML code */
<div class="img-container"></div>
Enter fullscreen mode Exit fullscreen mode

And here's the JavaScript code to dynamically render the images:

// JavaScript code
const picturesLinksArray = [
"https://cdn.pixabay.com/photo/2020/10/29/03/22/dog-5695088_1280.png",
"https://cdn.pixabay.com/photo/2022/02/20/09/43/animal-7024108_1280.png",
"https://cdn.pixabay.com/photo/2022/02/20/09/36/animal-7024080_1280.png",
"https://cdn.pixabay.com/photo/2022/02/20/09/34/animal-7024072_1280.png"
];

// Get the container element from the HTML
const imgContainer = document.querySelector(".img-container");

// Create and append img elements for each image in the array
picturesLinksArray.forEach((link) => {
  const image = document.createElement("img");
  image.src = link;
  imgContainer.appendChild(image);
})
Enter fullscreen mode Exit fullscreen mode

With this approach, next time you want to add a new image, you only need to update the array with the new image link. The JavaScript code remains unchanged, making the process much simpler and more efficient.

Conclusion

Using HTML alone to manage a list of images can quickly become cumbersome, especially as the list grows. JavaScript offers a more dynamic and scalable solution.
This not only saves time but also keeps your code cleaner and more maintainable.

Top comments (2)

Collapse
 
moopet profile image
Ben Sinclair

With the javascript method, you'll need to extend the array to be an array of objects rather than simple strings, so you can include alt text. On the other hand, you can automate things like srcset variants if they have predictably-formatted names.

Collapse
 
vivecodes profile image
vive

Sure, you are absolutely right. It's just a simplified example of the difference between using and not using JS.