views:

24

answers:

2

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  A: 

Use $.map like so:

var links = $('a').map(function() { return this.href }).get()
meder
+1 - You'll need a `.get()` on the end, but this is the correct approach.
Nick Craver
Ah thanks, I just quickly did `[0]` and assumed it was an array when it was in fact a jquery constructed array-like object.
meder
+1  A: 
var links = $("a").map(function(){return $(this).attr("href")}).get();
nicholasklick