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> 
0

1 Answer 1

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

2 Comments

Thank you for your answer, but it doesn't work. Do you know a way using pure javascript?
Huh, it's working on my end. Well, the "possible duplicate" comment on your question has some solutions with pure JS.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.