Reputation: 575
I have some HTML that I don't have control off. The basic layout is as follows...
<div class="container">
<div class="img-field">
<img src="/path/to/img.jpg" />
</div>
<div class="img-field">
<img src="/path/to/img.jpg" />
</div>
</div>
There's about 8 ".img-field" div's all containing images. I am looking to loop through and grab the src for all the images, add them to an array and then move them to be in list tags so it can work with a plugin I'm using. I can grab the source for 1 img no problem but I'm struggling to grab all 8 src's. Any advice on the best way to achieve this?
Upvotes: 0
Views: 855
Reputation: 144729
var arr = $('.img-field img').map(function(){
return this.src;
}).get();
Upvotes: 3
Reputation: 76597
You can simply create an array and loop through all of the specific <img>
tags using the jQuery .each()
function:
//Your array to store your values
var yourImageSources = new Array();
//Iterates through each of the image fields
$('.img-field').each(function()
{
//Selects the img element within the current image field and pushes it onto
//the array.
yourImagesSources.push($('img',this).attr('src'));
});
Upvotes: 2
Reputation: 34426
Do this -
$('.img-field').each(function() {
var thisSRC = $(this).find('img').attr('src'); // thisSRC is the current image source
// do something with thisSRC
});
EDIT: And I just saw Rion's answer which does all that you need it to do.
Upvotes: 0
Reputation: 12619
You can select the img src attribute by $(".img-field").find("img").attr("src")
and then you can loop over them using the jquery .each()
function
Upvotes: 0