I have an html code:
<div >
<div >
<img data-id="1" src="girl1.jpg" >
</div>
<div >
<img data-id="2" src="girl2.jpg" >
</div>
<div >
<img data-id="3" src="girl3.jpg" >
</div>
</div>
<div >
<div >
<img data-id="4" src="girl4.jpg" >
</div>
<div >
<img data-id="5" src="girl5.jpg" >
</div>
<div >
<img data-id="6" src="girl6.jpg" >
</div>
</div>
<div ></div>
So I want to get list of img sources only of this element's closest parent image children and append them to listblock-otziv:
data_otziv = $(this).closest('.customers-otziv__content .items').map((i, el) => ({
src: $(el).find('.reviews-photo').prop('src'),
})).get();
$.map( data_otziv, function( item, i ) {
$(".listblock-otziv").append(`
<div data-id="${i}">
<img src="${item.src}">
</div>`
);
})
But I am getting only one images's src value)! Please help!
CodePudding user response:
Your first issue is that .closest('.customers-otziv__content .items')
is the same as .closest('.customers-otziv__content").find(".items')
which you don't want. Change to
...closest('.customers-otziv__content.items')...
Secondly: $(el).find('.reviews__photo').prop('src')
will always give you the first src=
because prop returns a string not an array (.text() works differently here). You need to .map to get them all out.
Easiest is to map the .reviews__photo
elements directly:
$(this).closest('.customers-otziv__content.items').find(".reviews__photo").map((i, el) => ({
src: $(el).prop('src')
})).get();
Thirdly, if you doing that then there appears to be no need for the interim array data_otziv
as i
will be the same i
and item
will be the same as el
. Switching between jquery .map((i, el)
and array .map((item,i)
.