Home > Mobile >  get image src values for a bunch of images
get image src values for a bunch of images

Time:04-23

I have a div with a bunch of <img> elements within it. I want to be able to store the <src> values in jQuery and then inject these src values elsewhere in the DOM.

So basically, I want to get the img src values from the below:

<div >
<img src="example.jpg">
<img src="chicken.jpg">
<img src="hope.jpg">
</div>

And then inject them in the location below within the 'markup' template as below:

<div >
<div style="background-image: example.jpg"></div>
<div style="background-image: chicken.jpg"></div>
<div style="background-image: hope.jpg"></div>
</div>

The number of imgs in the "newHomeHeroCarouselFetchedIMGs" div is not known, could be 1, could be 10.... For each img that appears in the "newHomeHeroCarouselFetchedIMGs" div - I need another <div style="background-image: IMGSRC.jpg"></div> added in the "targetLocation" div.

I guess I need to create an array and pass the img src values into that, then based on the number of items in the array loop through it to output the markup and inject the img src to the background-image style attribute - I just am not sure how to achieve it!

CodePudding user response:

Would this work for you?

$('newHomeHeroCarouselFetchedIMGs > img').each(function() {
    let src = $(this).attr('src');
    $('div.targetLocation').append( $(`<div style="background-image: ${src}" />`) );
});
  • Related