Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get the index of dynamically created element (list item)?

Tags:

jquery

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

like image 530
Krish Avatar asked Oct 21 '22 05:10

Krish


2 Answers

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
});
like image 171
Rajaprabhu Aravindasamy Avatar answered Oct 24 '22 10:10

Rajaprabhu Aravindasamy


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

like image 26
Anoop Joshi P Avatar answered Oct 24 '22 12:10

Anoop Joshi P