Reputation: 812
I'm attempting to use .text() on multiple (unknown number of) elements on a page.
Consider:
<ul>
<li class="myClass">element1</li>
<li class="myClass">element2</li>
<li class="myClass">element3</li>
</ul>
$('.myClass').text();
Will return the first element's text "element1".
I came across the following while looking around:
$('.myClass').each(function(index, obj)
{
// do something
});
However, this simply query returns each full elements like:
<li class="myClass">element1</li>
<li class="myClass">element2</li>
<li class="myClass">element3</li>
I need to return all element's text such as:
"element1" "element2" "element3"
Thanks!
Upvotes: 6
Views: 17977
Reputation: 337637
You can use map()
to retrieve a specific property of a group of elements and place them in an array:
var textValues = $('.myClass').map(function() {
return $(this).text();
}).get();
From there you can work with the array to create the string as you need, for example, using join()
:
console.log(textValues.join(', ')); // = 'element1, element2, element3'
var textValues = $('.myClass').map(function() {
return $(this).text();
}).get();
console.log(textValues.join(', ')); // = 'element1, element2, element3'
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li class="myClass">element1</li>
<li class="myClass">element2</li>
<li class="myClass">element3</li>
</ul>
March 2020 Update
The map()
call can now be made even simpler by using ES6's arrow functions.
var textValues = $('.myClass').map((i, el) => el.innerText.trim()).get();
Note, however, that this will not work in IE. You will need to use the method in the first example if you require legacy browser support.
Upvotes: 21
Reputation: 23811
Simply concat the text inside .each
. Here is a DEMO
Here is modified jQuery:
$(function() {
var names = '';
$('.myClass').each(function(index, obj) {
names += $(this).text() +',';
});
alert(names);
});
Upvotes: 1
Reputation: 746
var x =[];
$('.myClass').each(function(index, obj)
{
x.push($(this).text());
});
console.log(x);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li class="myClass">element1</li>
<li class="myClass">element2</li>
<li class="myClass">element3</li>
</ul>
Upvotes: 16
Reputation: 18825
Make use of $(this)..!
var string = null;
$('.myClass').each(function(index, obj){
// do something
string += $(this).text();
});
Upvotes: 0