JQuery targeting elements with index ()

So, I have two unordered lists with the same number of elements in them. Therefore, let items in unordered list # 2 be hidden. The only way to do this is if you click on the items in unordered list # 1.

therefore basically

<ul class="list1"> <li>item 1</li> <li>item 2</li> <li>item 3</li> <li>item 4</li> </ul> <ul class="list2"> <li class="hide">item 1</li> <li class="hide">item 2</li> <li class="hide">item 3</li> <li class="hide">item 4</li> </ul> 

Now the way I'm trying to do this is to use the index() method, but I'm not sure how to properly approach this code.

This is how I thought about it.

 $('.list1').on('click', 'li', function() { $('.list2 li').index($(this).index()).toggleClass('active'); }); 

so when you click on a line item in .list1 , regardless of the index of that line item, this is the index I want to target in .list2

The problem I am facing is that when I register the console, I get weird indexes. The first position will be displayed as 2, not 0, and the index for the second position will be -1.

what am I doing wrong? I'm sure.

Thanks in advance guys!

+5
source share
2 answers

JQuery .index() returns the index of the selected item. You need to use :eq() selector or .eq() method for selecting an element with index.

 $('.list1').on('click', 'li', function() { $('.list2 li').eq($(this).index()).toggleClass('active'); }); 
 .hide { display: none; } .active { display: block; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul class="list1"> <li>item 1</li> <li>item 2</li> <li>item 3</li> <li>item 4</li> </ul> <ul class="list2"> <li class="hide">item 1</li> <li class="hide">item 2</li> <li class="hide">item 3</li> <li class="hide">item 4</li> </ul> 
+5
source

try this, it will work for you well

 <html> <head></head> <title></title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <style type="text/css"> /* in here we get the ul which the class name is list2 and get the li elements inside it and hide those first*/ ul.list2 li{ display: none; } </style> <body> <ul class="list1"> <li>item 1</li> <li>item 2</li> <li>item 3</li> <li>item 4</li> </ul> <ul class="list2"> <li>item 1</li> <li>item 2</li> <li>item 3</li> <li>item 4</li> </ul> </body> <script type="text/javascript"> $(document).ready(function(){ $("ul.list1 li").click(function(){ var theindex = $(this).index();//in here you get the index number of clicked li element inside list1 class $("ul.list2 li").eq(theindex).slideToggle(500);//then in here, you show the same index li element in list2 , which we are hidden. }); }); </script> </html> 
+3
source

All Articles