user4609276
user4609276

Reputation:

jQuery targeting elements with index()

So I have two unordered lists, with the same amount of items in them. So let's assume items in unordered list #2 are all hidden. The only way to make them appear is if you click on the items in unordered list #1.

so 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 accomplish this is using the index() method, but I'm not sure how to properly approach this code.

This is how I thought of it.

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

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

the problem I'm having is that when I console log it, I'm getting weird index numbers. The first line item would show up as 2 rather than 0, and the index for the 2nd line item would be -1.

what am I doing wrong? a lot I'm sure.

thanks in advance guys!

Upvotes: 5

Views: 101

Answers (2)

caldera.sac
caldera.sac

Reputation: 5088

try this, this will work for you fine

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

Upvotes: 3

Mohammad
Mohammad

Reputation: 21489

Jquery .index() return index of selected element. You need to use :eq() selector or .eq() method to selecting 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>

Upvotes: 4

Related Questions