<ul class="siteName"></ul>
In the above un order list i am appending the <li></li>
for some n(10) item.
on click on the the <li>
how to get the index of get the index of the li
?
Try to use element.index()
to get its index in relative to its siblings,
$('.siteName').on('click','.siteName > li',function(){
console.log($(this).index()); //index of the clicked li, index starts from 0
});
If you don't want to exclude the nested li element's click then use,
$('.siteName').on('click','li',function(){
console.log($(this).index()); //index of the clicked li, index starts from 0
});
From your comments, it is clear that your li
has child tags inside it, so the click event will generate it for them too. So you should write the code as,
$('.siteName').on('click', 'li', function(e){
alert($(this).closest("li").index());
});
Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With