Home > Net >  How can I set src and alt attributes on an image tag using JavaScript
How can I set src and alt attributes on an image tag using JavaScript

Time:02-12

JavaScript is something that I am learning bit by bit, so please excuse my ignorance...!

I have a list of images in a gallery, and I am creating a modal on a click event. I have managed to collect all of the sources for the images into an array and have then used the forEach method to appended an li and img tag into a parent ul, with all of the sources going into the src attribute.

My problem is I also have an array of alt attributes as well that I also need to set into the same list of images.

I don't think I can do both attributes in one forEach loop, and it seems too messy to do a second loop for the alt attributes. There must be a simpler way, it's just beyond my current understanding.

Here is the code I already have below, I was wondering if perhaps I should be looking at a JSON object instead rather than this approach?

 $('.gallery-image img').click(function(){
            $('.modal').addClass('show');
            var images = document.getElementsByClassName('aurora-gallery-image');
            var imageSources = [];
            var imageTitles = [];
            for (var i = 0; i < images.length; i  ) {
                 imageSources.push(images[i].src);
                 imageTitles.push(images[i].alt);
            }
           imageSources.forEach(imageFunction);
            
            function imageFunction(item){
               $('.image-modal ul').append('<li ><img  alt="" src="'   item   '" /><p id="aurora-gallery-image-title">  </p></li>');
            }
           
           
      }); 

CodePudding user response:

forEach() passes the array index as the second argument to the callback function. You can use that to get the corresponding element from the imageTitles array

function imageFunction(item, index){
  $('.image-modal ul').append(`<li ><img  alt="${imageTitles[i]}" src="${item}" /><p id="aurora-gallery-image-title">  </p></li>`);
}

But you don't really need the arrays at all. Just do it in the for loop:

for (let i = 0; i < images.length; i  ) {
  $('.image-modal ul').append(`<li ><img  alt="${images[i].alt}" src="${images[i].src}" /><p id="aurora-gallery-image-title">  </p></li>`);
}
  • Related