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?
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.
Or a little bit shorter than the accepted answer:
$.map($("#foo span a"), $.text)
Try this:
$('#foo span a').map(function() { return $(this).text(); }).get();
you can do it like this
var texts = new Array();
$('#foo > span > a').each(function()
{
texts.push( $( this ).text() );
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With