2

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?

1 Answer 1

4

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') );
Sign up to request clarification or add additional context in comments.

Comments

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.