jQuery .text() multiple elements same class

14,950

Solution 1

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>

Solution 2

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.

Solution 3

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);
});
Share:
14,950
Myles
Author by

Myles

front end web developer for boohoo.com

Updated on July 07, 2022

Comments

  • Myles
    Myles almost 2 years

    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!