skip to Main Content

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:

image of result of code snippet above

How can I get only one object per article instead of all objects left in the iteration?

2

Answers


  1. 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 the article you just created:

    for (let place of list_of_places) {
      const $article = $('<article />').appendTo('.places');
      $article.append(`<div class="title_box"><h2>${place.name}</h2><div class="price_by_night">${place.price_by_night}</div></div>`);
    }
    

    Alternatively you can use map() instead of your for loop to create an array of HTML strings which you append to the DOM as a whole:

    const html = list_of_places.map(place => `<article><div class="title_box"><h2>${place.name}</h2><div class="price_by_night">${place.price_by_night}</div></div></article>`);
    $('.places').append(html);
    
    Login or Signup to reply.
  2. Try

    $(".places article").eq(-1).append(`<div class="title_box">...
    

    based on this answer to How do I select a single element in jQuery? in conjunction looking up eq in jQuery docs.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search