views:

56

answers:

3

I have a UL with 9 anchor tags, each with the class 'highlight'.

Here is a bit of Javascript with jQuery:

  var titles = $('a.highlight');
  jQuery.each(titles, alert(titles.length));

What I expect this bit of code to do: Alert 9 times, the number 9.

What this bit of code actually does: Alerts 1 time the number 9.

What am I missing?

A: 

I'm a novice myself, but shouldn't it be titles.each(), not jQuery.each()?

Larry Lustig
You can use either way, jQuery.each is just a generic iterator.http://docs.jquery.com/Utilities/jQuery.eachEither way I get the same result though.
Tim76
My bad. I thought you were trying to call $(...).each().
Larry Lustig
+3  A: 

jQuery.each calls a function you pass it for each item it finds in the given collection. You are passing an expression that is evaluated immediately. You need to wrap the expression in an anonymous function:

jQuery.each(titles, function() {
    alert(titles.length)
});
Roatin Marth
A: 

You're looking for:

jQuery.each( titles, function( index, title ) {
  console.log( 'the title at index ', index, ' is ', title );
} );

See the documentation for the each function.

thenduks