0

I need a javascript to show me the nth-child number when I click a li. For example if I click "apple" console.log show me "2". I want to turn nth-child number into a variable.

<!DOCTYPE html>
<html>
    <head>
        <style type="text/css">
            li:nth-child(1) b {color: #eeaa33;}
            li:nth-child(2) b {color: #0000ff;}
            li:nth-child(3) b {color: #ff3300;}
        </style>
    </head>
    <body>
        <ul class="menu">
            <li><b>apple</b></li>
            <li><b>watermelon</b></li>
            <li><b>blueberry</b></li>   
        </ul>
        <script>
    //I need a javascript to show me the nth-child number when I click a li. 
        //For example if I click "apple" console.log show me "2".
        // I want to turn nth-child number into a variable.
        </script>
    </body>
</html>
josele
  • 1

1 Answers1

0

If you can use jQuery, .prevAll() would help. Assign a click handler to "li", call .prevAll() on the clicked element, and take the length of the resulting set to get the number of siblings before the clicked element. Add 1 so that the first li has n=1.

$("li").click(function(){  
    var n = $(this).prevAll().length + 1;  
    console.log(n);  
});
  • Thank you for your answer, but it doesn't work. Do you know a way using pure javascript? – josele Jun 04 '15 at 18:41
  • Huh, it's working on my end. Well, the "possible duplicate" comment on your question has some solutions with pure JS. –  Jun 04 '15 at 18:46