47

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?

7 Answers 7

89

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I know .get() returns a basic array, but what is it doing and why does it do that? Can't seem to find an explanation in the jQuery refs (just a mention that that's what it does).
@Peter - It's basically calling .toArray() to get a clean array back, without the extra jQuery properties.
13

Or a little bit shorter than the accepted answer:

$.map($("#foo span a"), $.text)

Comments

6

Try this:

$('#foo span a').map(function() { return $(this).text(); }).get();

2 Comments

You're missing a close paren at the end ( also, this results in a jQuery-wrapped array, not a basic array ( a .get() at the end would give you a basic array) ).
Yep... it was fixed immediately, but you must've loaded it at just the right time :)
2

you can do it like this

var texts = new Array();

$('#foo > span > a').each(function() 
{ 
  texts.push( $( this ).text() ); 
});

Comments

2

Additionally, the function to get the array of values with trimmed spaces:

var array = $('li').map(function(){
               return $.trim($(this).text());
            }).get();

Comments

0

Try this:

var texts = new Array();
//or... var texts = [];

$('#foo a').each(function() {
    texts.push($(this).text());
})

1 Comment

array() is PHP. To create an empty array in JavaScript, the array literal [] is preferred.
-1

use the jquery selector:

$("ul#foo span a")

1 Comment

This is all the a tags, not the contents of all the a tags.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.