Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get array of text values using selector instead of iterating?

Tags:

jquery

I have some HTML like:

<ul id='foo'>
    <span><a>hello 1</a></span>
    <span><a>hello 2</a></span>
    <span><a>hello 3</a></span>
</ul>

I want to get an array of all the text values of the elements like:

var texts = [ 'hello 1', 'hello 2', 'hello 3' ];

I'm trying to iterate over each one, is there some way in jQuery to just grab all of them using a selector?

like image 559
user246114 Avatar asked Aug 16 '10 18:08

user246114


4 Answers

You can do it using .map() like this:

var myArray = $("#foo span a").map(function() {
                 return $(this).text();
              }).get();

You can test it out here.

like image 200
Nick Craver Avatar answered Nov 09 '22 05:11

Nick Craver


Or a little bit shorter than the accepted answer:

$.map($("#foo span a"), $.text)
like image 34
George Herolyants Avatar answered Nov 09 '22 05:11

George Herolyants


Try this:

$('#foo span a').map(function() { return $(this).text(); }).get();
like image 6
jmar777 Avatar answered Nov 09 '22 05:11

jmar777


you can do it like this

var texts = new Array();

$('#foo > span > a').each(function() 
{ 
  texts.push( $( this ).text() ); 
});
like image 2
ovais.tariq Avatar answered Nov 09 '22 06:11

ovais.tariq