0

I'm trying to get all the text of a particular class into an array.

The below works theoretically, but it puts them into an object, not an array, and .map apparently is widely unsupported in most versions of IE :(

var valuesArr = $('.'+sort_column);
var valuesArr =  valuesArr.map(function(){return $(this).text().trim();});

Is there any way to get all the values into a plain and simple array that I'm just missing?

Thanks!

1

3 Answers 3

1

Simple iteration:

var array = [];

$(".elements").each(function() {
    array.push($.trim($(this).text()));
});

console.log(array);

Or with jQuery map method:

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

console.log(array);​

DEMO: http://jsfiddle.net/f6cmR/

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

7 Comments

any particular advantage to one or the other?
.map() returns a jQuery object not an array.
@thomas Implicitly the first iteration underlies of JQuery map method. The second can be considered as one line solution only. And yes, map returns object of { 0: value, 1: value, ... }, which most browsers interpret as array (see log in demo). Both methods work fine in all browsers.
You'll want .get() after the .map() call to get an array.
@ThiefMaster Hm... I was thinking about that. From JQuery specification, map(): Translate all items in an array or object to new array of items. I do not see any problems in calling the resulting array "a pure array" somehow. Or what is the reason for using get()?
|
0

Use $.map like

var valuesArr = $('.'+sort_column);
var valuesArr =  $.map(valuesArr,function(){
                      return $(this).text().trim();
                     }).get();

$.map return an jQuery object.

jQuery obects are array-like, but they are not arrays! The reason of calling .get() at the end of the .map() call is to turn that jQuery object into a true array. The elements of that array are the values returned by the callback.

1 Comment

$.map iterates over a set of elements, I dont think it's an issue with IE. Can you be more specific of what IE problem you are talking about?
0

You can use $.makeArray() to convert jQuery object to an array and then map text from elements:

var valuesArr = $.makeArray($('.elements'))
    .map(function() {
        return $(this).text().trim();
    });

1 Comment

Or just use .get() on the jQuery object.

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.