tags:

views:

32

answers:

5

Hi,

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?

Thanks

A: 

use the jquery selector:

$("ul#foo span a")
codersarepeople
This is all the `a` tags, not the contents of all the `a` tags.
Peter Ajtai
+1  A: 

Try this:

$('#foo span a').map(function() { return $(this).text(); }).get();
jmar777
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) ).
Peter Ajtai
Yep... it was fixed immediately, but you must've loaded it at just the right time :)
jmar777
A: 

Try this:

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

$('#foo a').each(function() {
    texts.push($(this).text());
})
treeface
`array()` is PHP. To create an empty array in JavaScript, the array literal `[]` is preferred.
Ryan Tenney
Sorry about that...edited it to be JS.
treeface
+5  A: 

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.

Nick Craver
+1 cause I forgot .get() on mine (now added).
jmar777
@Nick - 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 Ajtai
@Peter - It's basically calling `.toArray()` to get a clean array back, without the extra jQuery properties.
Nick Craver
A: 

you can do it like this

var texts = new Array();

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