2

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 ?

1 Answer 1

5

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.

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

2 Comments

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

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.