views:

71

answers:

3

Hi

I have a list like this one:

<ul>

  <li>
    <a href="..."> ... </a>
    <a href="..."> ... </a>
  </li>

  <li>
    <a href="..."> ... </a>
    <a href="..."> ... </a>
  </li>

  <li>
    <a href="..."> ... </a>
    <a href="..."> ... </a>
  </li>

  ...

</ul>

and the jQuery:

$("li").each(function(){
     // do stuff
});

How can I get the current list number (like 1, 2 or 3) inside that jquery function (where do stuff is)?

+2  A: 

jQuery passes it as an argument:

$('li').each(i, li) {
  // i is the counter (starts at zero)
});

(hold on while I make sure that's the right order; i always get confused b/c "$.map()" is different!)

yup that's it, index then element.

Pointy
+2  A: 

The callback function passed to each has two arguments, the first being the index you're looking for:

$('li').each(function(index, value) {
  // index is what you're looking for
});

Have a look at the documentation for each:

the callback is passed an array index and a corresponding array value each time.

Note that the index will be zero-based, so if you want your "1, 2, 3..." (from your question), you'll need to make the appropriate accommodations.

Rob Hruska
that works, thank you :)
Alex
@Alex - Once you have been given an answer, can you please accept one that works for you just to help future jQuery-ers and to reward those who took the time to help you. Thanks!
JasCav
+3  A: 

Per the jQuery documentation, you can include a callback within the function (as below):

$('li').each(function(index, value) { 
  alert('li #' + index); 
});
JasCav