views:

166

answers:

4

I'm using jQuery and wanting to target the nth <li> in a list after clicking the nth link.

<ul id="targetedArea">
  <li></li>
  <li></li>
  <li></li>
  <li></li>
</ul>
<div id="clickedItems">
  <a></a>
  <a></a>
  <a></a>
  <a></a>
</div>

I can target them individually, but I know there must be a faster way by passing which <a> element I clicked on.

$("#clickedItem a:eq(2)").click(function() {
  $("#targetedArea:eq(2)").addClass('active');
  return false;
});

Cheers,
Steve

+3  A: 

how about something like this:

$('#clickedItems a').click(function() {
// figure out what position this element is in
   var n = $('#clickedItems a').index($(this) );
// update the targetedArea
   $('#targetedArea li:eq('+n+')').html('updated!');
   return false;
});

assuming a 1:1 relationship between your <a> and <li> elements it will update the appropriate <li>

Owen
+1  A: 

I know this is not directly answering your question, but maybe you're making it more difficult than it is.

Give each of the A and LI elements an ID, and make the IDs so you can infer them from each other. As soon as an A is clicked, you immediately know the LI's ID and can refer to it directly.

As a side effect, this is more efficient than any clever jQuery that might do the same thing.

Tomalak
A: 

i dont know if jquery has something like this in mootools

$$('a.clickedItems').addEvent('click', function(e){
  e.preventDefault();
  $('targetedArea').getChildren()[this.getAllPrevious().length].addClass('selected');
});
ken
A: 
$('#clickedItems a').click(function() {
    // you probably want to turn off the currently active one
    $('#targetedArea li.active').removeClass("active");

    // count the links previous to this one and make the corresponding li active
    $('#targetedArea li:eq(' + $(this).prevAll('a').length + ')').addClass("active");

    // prevent the browser from going to the link
    return false;
});
nickf