Reputation: 4008
From backend I'm sending a list of prices.
Like: [70, 90, 100, 140, 200]
I also have <span>
elements with specific clases, inside a div:
<span class="price_50_units"></span>
<span class="price_100_units"></span>
<span class="price_200_units"></span>
<span class="price_300_units"></span>
<span class="price_500_units"></span>
I need to append these elements to it's specific span. The first element of the list will always correspond to the span with class="price_50_units"
:
<span class="price_50_units">70</span> #should be the result for the first span.
The second element will always corresponde to the span with class="price_100_units"
and so on.
<span class="price_100_units">90</span> #should be the result for the second span.
Right now I can put span elements with the values of the list inside a div with this code:
req.done(function (response) {
$('#prices').empty();
var prices = response.prices;
var list = '';
for (var j = 0; j < prices.length; j++) {
list += "<span>" + prices[j] + "</span></br>";
}
$('#prices').html(list);
});
This code will create new span elements, with the values from the list.
But how to target span elements already present in html?
I was thinking on something like this, but is not working:
$('p').children('span .price_50_units').text(prices[1]);
Upvotes: 0
Views: 763
Reputation: 1206
If your spans are not always created in order, then maybe:
// Your data
var respData = [70, 90, 100, 140, 200];
// Loop through
$.each(respData, function(index, value ) {
// Check if element exists. PS change selector if needed
if($('span.price_' + value + '_units').length) {
// add the value to the span
$('span.price_' + value + '_units').text(value);
}
});
Upvotes: 1
Reputation: 24965
If the index of the response and the index of the span is a direct correlation, then you can put a common class on the spans, and just set their texts based on the index.
var responseData = [70, 90, 100, 140, 200];
$('.price').text(function(index){
return responseData[index];
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="price price_50_units"></span>
<span class="price price_100_units"></span>
<span class="price price_200_units"></span>
<span class="price price_300_units"></span>
<span class="price price_500_units"></span>
Upvotes: 1