How to get index of list of Items when li button is clicked using jquery

Is there any way I can get the index of list items when I click the li element using JavaScript / jQuery?

 <ul> <li>item1</li> <li>item2</li> <li>item3</li> </ul> 
+4
source share
2 answers
 $('ul li').click(function(){ alert($(this).index()); }); 
+12
source

Use the onClick event to call the getIndex function (no jQuery, just vanilla javascript):

 onClick = "getIndex(this);" function getIndex(node) { var childs = node.parentNode.childNodes; for (i = 0; i < childs.length; i++) { if (node == childs[i]) break; } return i; } 

The index starts at 0! To get started with 1: return i+1

+8
source

All Articles