Home > Enterprise >  how can I create an html article for each element in a javascript array
how can I create an html article for each element in a javascript array

Time:11-03

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 >
                 <h2>${place['name']}</h2>
                 <div >${place['price_by_night']}</div>
                 </div>`);
            }

        }

    });

here's a snippet of the html to edit:

<section >
            <!-- <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?

CodePudding user response:

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 ><h2>${place.name}</h2><div >${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 ><h2>${place.name}</h2><div >${place.price_by_night}</div></div></article>`);
$('.places').append(html);

CodePudding user response:

Try

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

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

CodePudding user response:

Don't append each time inside for loop. Create markup inside loop and append once.

Example:

success: function(list_of_places) {
    var htm = '',
    for (let place of list_of_places) {
      html  = "<article>";
      html  = `<div >
                 <h2>${place['name']}</h2></div>`
                 <//More string goes here
      html  = "</article>";


    }
    $(".places").append(html)
}
  • Related