javascript - show nth-child number when click - turn nth-child number into a variable -
this question has answer here:
i need javascript show me nth-child number when click li. example if click "apple" console.log show me "2". want turn nth-child number 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 javascript show me nth-child number when click li. //for example if click "apple" console.log show me "2". // want turn nth-child number variable. </script> </body> </html>
if can use jquery, .prevall() help. assign click handler "li", call .prevall() on clicked element, , take length of resulting set number of siblings before clicked element. add 1 first li has n=1.
$("li").click(function(){ var n = $(this).prevall().length + 1; console.log(n); });
Comments
Post a Comment