tags:

views:

82

answers:

3

hi,

how can i select the nth child in a set of <div>'s when the nth child in a set of <li>'s is clicked?

HTML below

<ul>
 <li><a href="#">link</a></li>
 <li><a href="#">link</a></li>
 ......
 <li><a href="#">link</a></li>
</ul>

<div class="info">
...
</div>
<div class="info">
...
</div>
......
<div class="info">
...
</div>

for example, when the <a> in the 2nd <li> is clicked, the 2nd <div class="info"> should get selected.

thanks

A: 

This should give you a rough idea (untested)

$('ul li').click(function() {
  var i = $(this).index();
  $('.info:eq('+i+')').addClass('selected');
  return false;
});​

I've created a quick demo to show this working: http://jsfiddle.net/Jbgkm/

Ben Rowe
+1  A: 

This works:

$("li a").click(function(){ 
    $(".info").eq($("li a").index(this)).hide();
});​

(sample http://jsfiddle.net/KGQDz/11/)

Mark E
+1 Beat me to it... uses the best of both other answers. Nice.
harpo
+1  A: 

The solution is simple, tested with your code. Will hide the clicked element. Here you have the working example with more elements http://jsfiddle.net/v2vqm/

$("ul li a").each(function(index){
   $(this).click(function(){
     $('.info').eq(index).hide();
   });
});

Explanation, you're iterating through all the existant li a elements available when the script is loaded. And with that iteration you pass the respective index, which we later use to select the correct .info element via the eq(index) method.

Please note that hide() is just for the demonstration.

Related Docs:

http://api.jquery.com/each/

http://api.jquery.com/eq/

kuroir