Find out how to use jQuery's `each()` function and `clone()` or `html()` function to display multiple cards with different data on the page.
How does the same code in jQuery display multiple cards on the page but with different data on it? I only have one copy of a card container in HTML and I'm trying to populate the DOM with 6 cards displaying different weather data
You can use jQuery's each()
function together with clone()
or jQuery's html()
function to achieve this.
Using each()
:
javascript Copy code
//array of data with each element containing the data of one card
var data = [{}, {}, {}, {}, {}, {}];
$.each(data, function(index, cardData) {
//clone card container
var clonedCard = $('.card-container').clone();
//for each element in cloned card container
clonedCard.find('*').each(function() {
//replace element data with data from array
$(this).text(cardData[this.id]);
});
//append card container to the DOM
$('body').append(clonedCard);
});
Using html()
:
javascript Copy code
//array of HTML strings with each string containing the HTML code of one card
var data = ['<div>data 1</div>', '<div>data 2</div>', '<div>data 3</div>', ...];
$.each(data, function(index, cardHTML) {
//clone card container
var clonedCard = $('.card-container').clone();
//fill the cloned card container with data from the array
clonedCard.html(cardHTML);
//append card container to the DOM
$('body').append(clonedCard);
});