Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get parent index with jQuery [duplicate]

<ul class="bullets">
  <li><a href="#">item 1</a></li>
  <li><a href="#">item 2</a></li>
  <li><a href="#">item 3</a></li>
  <li><a href="#">item 4</a></li>
  <li><a href="#">item 5</a></li>
</ul>

When I click on the <a> element, i'd like to get it's parent <li>'s index number.

I'm trying to create a carrousel type function that doesn't need item-n classes on the list items.

$(".bullets li a").click(function(){

   var myIndex = $(this).parent().index(this);
   showPic(myIndex);

});

Thanks for any help.

TD.

like image 664
TD540 Avatar asked Sep 11 '25 06:09

TD540


2 Answers

$(this).parent().index();

short and sweet

Correction : this is not short and sweet

from where this comes it should be like:

$(".bullets li a").click(function(){
    var myIndex = $(this).parent().index();
    console.log(myIndex);
    showPic(myIndex);
});
like image 200
James Avatar answered Sep 12 '25 21:09

James


$(".bullets li a").click(function(){

   var myIndex = $(this).parent().prevAll().length;
   showPic(myIndex);

});

Note: prevAll().length will give you a zero-based index; the first item will be 0 (zero).

like image 36
James Avatar answered Sep 12 '25 20:09

James