views:

57

answers:

1

I am trying to loop through all of the links on a page and add them to an array using jquery but I can't seem to get it quite right.

What I have is:

$(document).ready(function() {

var links = new Array();
var link;

for (link in $("a"))
{
links.push(link);
}

alert(links);

});

What I get is an array of numbers (I think one for each link on the page), and properties, events, etc. like 'selector', 'context', ... 'onmouseover' and so on.

What am I missing?

+3  A: 

When you do $('a') you already have a jQuery object, which is an array-like object.

If you want an actual Array of elements, you can convert it to an Array with $.makeArray().

var array = $.makeArray( $('a') );

EDIT: If you're curious about why you were getting those unexpected results in the for/in, fire up the developer tools in your favorite browser, and log a jQuery object to the console. You'll see all those (prototyped) properties you were getting.

console.log( $('a') );
patrick dw
+1 Short and sweet.
Gert G