views:

57

answers:

1

Each element in $(some_selector) has attribute my_attr (which is a number).

I would like insert all these attributes to array.

What would be the easiest way to do this using jQuery ?

+5  A: 

You can use .map() for this:

var arr = $("some_selector").map(function() {
            return $(this).attr("my_attr");
          }).get();

Or as a number, parse along the way:

var arr = $("some_selector").map(function() {
            return parseInt($(this).attr("my_attr"), 10);
          }).get();

Either of these return a JavaScript Array.

Nick Craver
+1 for jQuery's `.map()`.
Rocket
Nick, in the second version: if map's function returns the number itself, why actually get() is needed ?
Misha Moroshko
@Misha - `.get()` is calling `.toArray()` under the covers, it is just getting a clean array with no other jQuery properties left over :)
Nick Craver
OK. Thanks a lot !
Misha Moroshko