i want to iterate a response and create an article section with each object
I have the following piece of code that makes the request:
$.ajax({
type: "POST",
url: "http://0.0.0.0:5001/api/v1/places_search/",
data: JSON.stringify({}),
dataType: 'json',
contentType: "application/json",
success: function (list_of_places) {
for (let place of list_of_places) {
$(".places").append("<article></article>");
// title box
$(".places article").append(`<div class="title_box">
<h2>${place['name']}</h2>
<div class="price_by_night">${place['price_by_night']}</div>
</div>`);
}
}
});
here’s a snippet of the html to edit:
<section class="places">
<!-- <h1>Places</h1> -->
</section>
here’s a screenshot of the result of the snippet:
How can I get only one object per article instead of all objects left in the iteration?
2
Answers
The issue is because within your
for
loop,$(".places article")
is selecting all elements matching that selector in the DOM, so you repeatedly append the new items to each one.To fix this you can
append()
the content to thearticle
you just created:Alternatively you can use
map()
instead of yourfor
loop to create an array of HTML strings which you append to the DOM as a whole:Try
based on this answer to How do I select a single element in jQuery? in conjunction looking up eq in jQuery docs.