... ...
  • ...

    Get current number <li>

    I have a list like this:

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

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

    How can I get the current list number (e.g. 1, 2 or 3) inside this jquery function (where there are things)?

    +4
    source share
    3 answers

    The callback function passed to each has two arguments, the first of which is the index you are looking for:

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

    See the documentation for each :

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

    Please note that the index will be based on a zero value, so if you need your "1, 2, 3 ..." (from your question), you will need to make the corresponding numbers.

    +4
    source

    In the jQuery documentation, you can enable the callback inside the function (as shown below):

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

    jQuery passes it as an argument:

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

    (hold on until I'm sure the correct order, I always confuse b / c "$ .map ()" is different!)

    yup to it, index then item.

    +2
    source

    All Articles