8

In jQuery, it is easy to select elements as array.

$("a"); // return as elements array of anchors

But is it possible to select matched elements' attributes as array?

Currently I need to do something like...

links = [ ];

$("a").each(function() {

href = $(this).attr("href");
links.push(href); 

});

Are there any better method to fill the variable links with href of the all matched anchors?

2 Answers 2

19

Use $.map like so:

var links = $('a').map(function() { return this.href }).get()
Sign up to request clarification or add additional context in comments.

4 Comments

+1 - You'll need a .get() on the end, but this is the correct approach.
Ah thanks, I just quickly did [0] and assumed it was an array when it was in fact a jquery constructed array-like object.
This seems a bit verbose for a library whose purpose seems to be masking these kind of gymnastics from the programmer. Why doesn't this simply return an array: var links = $('a').attr('href'); Wouldn't that be cleaner and more readable? (consider this my suggestion for the next iteration of jQuery...)
What about "data" attributes ?
5
var links = $("a").map(function(){return $(this).attr("href")}).get();

1 Comment

This approach works great for custom defined data attributes like data-id, data-name etc.

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.