Reputation: 4008
I've 5 spans, could be more, all share the class .price
.
Reading documentation of Jquery, I find that the best approache is to use map
function. Like this:
var prices = $(".price")
.map(function () {
return this.text;
}).get().join();
I need a list of prices, So afterwards I can do something like (notice the minus 20 part):
$('.price').text(function (index) {
return "S/ " + prices[index]-20;
});
But when I alert prices
I get an empty window.
html:
<span class="price price_50">50</span>
<span class="price price_100">90</span>
<span class="price price_200">120</span>
<span class="price price_300">140</span>
<span class="price price_500">150</span>
Upvotes: 1
Views: 98
Reputation: 24965
Vanilla javascript uses innerText
, which is what text()
in jQuery references.
var prices = $(".price")
.map(function() {
return this.innerText;
}).get().join();
console.log(prices)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<span class="price price_50">1</span>
<span class="price price_100">2</span>
<span class="price price_200">3</span>
<span class="price price_300">4</span>
<span class="price price_500">5</span>
Upvotes: 1
Reputation: 1314
You need some content inside each of your span.
<span class="price price_50">50</span>
<span class="price price_100">100</span>
<span class="price price_200">200</span>
<span class="price price_300">300</span>
<span class="price price_500">500</span>
<p id="list_price"></p>
$( "p" )
.append( $( ".price" ).map(function() {
return $( this ).text();
})
.get()
.join( ", " ) );
Upvotes: 0
Reputation: 115222
Inside map this
refers to DOM and it doesn't have any text
property. So convert it to jQuery object and get text content using text()
method or get textContent
property from the DOM object.
var prices = $(".price")
.map(function() {
return $(this).text();
}).get().join();
console.log(prices)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<span class="price price_50">1</span>
<span class="price price_100">2</span>
<span class="price price_200">3</span>
<span class="price price_300">4</span>
<span class="price price_500">5</span>
Upvotes: 1