Myles Myles - 7 days ago 5
jQuery Question

jQuery .text() multiple elements same class

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!

Answer

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>