I have html blocks and there would be many this kind of html block with different html values and image sources.
<div data-id="a1">
<div >
<div ><strong>Alexander</strong></div>
<div >21 August 2022</div>
<div >Comportable table</div>
</div>
<img src="girl1.jpg" >
</div>
I want to extract all html values as array and I will console.log all values, sources with Jquery.
img_array =$(this).closest('.customers__content').find('.infoblock__user-name, .infoblock__date, .infoblock__text, img').map(function() {return
let name = $(".infoblock__user-name").html();
let date = $(".infoblock__date").html();
let text = $(".infoblock__text").html();
$("img").attr("src")
}).get();
img_array.forEach(function(name, date, text, src) {
console.log(name, date, text, src);
//$(".listblock").append(<img src="${src}">);
});
I want to get all class values as i got for source of image (for (infoblock__user-name, infoblock__date, infoblock__text, )) using one foreACH. PLEASE HOW CAN i do that?
CodePudding user response:
Your syntax to implement map()
isn't correct. You need to return an object, and the properties of that object need to be key/value pairs.
You also need to retrieve the values from the DOM relative to the current .customers__photo
element in the DOM, not by selecting all instances of that class.
Try this:
const data = $('.customers__photo').map((i, el) => ({
name: $(el).find('.infoblock__user-name').text(),
date: $(el).find('.infoblock__date').text(),
text: $(el).find('.infoblock__text').text(),
src: $(el).find('.reviews__photo').prop('src'),
})).get();
console.log(data);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<div data-id="a1">
<div >
<div ><strong>Alexander</strong></div>
<div >21 August 2022</div>
<div >Comportable table</div>
</div>
<img src="girl1.jpg" >
</div>
<div data-id="a1">
<div >
<div ><strong>John</strong></div>
<div >22 August 2022</div>
<div >Expandable table</div>
</div>
<img src="girl2.jpg" >
</div>
<div data-id="a1">
<div >
<div ><strong>Edward</strong></div>
<div >23 August 2022</div>
<div >Collapsable table</div>
</div>
<img src="girl3.jpg" >
</div>