views:

82

answers:

4

I have two unordered lists, a bit like:

<ul class="list1">
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
    <li class="current">Item 4</li>
    <li>Item 5</li>
</ul>

<ul class="list2">
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
    <li>Item 4</li>
    <li>Item 5</li>
</ul>

And the goal is, with jquery, to identify which li is marked with the 'current' class and then add a class to the second list to the corresponding li. I just can't think of how to do this.

Thanks.

+6  A: 
$('ul.list2 li:nth-child(' + $('ul.list1 li.current').index() + ')').addClass('current');

Or you could make it a little less icky:

$('ul.list2 li').eq($('ul.list1 li.current').index()).addClass('current');

The second one, I like better, now that I get to see them both :-) The tricks here are:

  1. the "eq" filter lets you pick an element from a jQuery list based on an index;
  2. the "index" function lets you find the index of an element relative to its siblings in the DOM
Pointy
Fantastic, thanks!
Meep3D
A: 
$('li.current + li').addClass('yourClass')

edit: misunderstanding of the question

var index = $.inArray($('li.current')[0],$('li.current').parent().children());
$('ul:eq(1) li:eq('+index+')').addClass('selected');
markcial
Is this even a valid jQuery selector? And what should the `+`-sign mean in the selector. And how/why should this work at all?
jitter
@jitter: http://api.jquery.com/next-adjacent-Selector/ It is valid but not selecting the right elements.
Felix Kling
+1  A: 

// Find the current item in the first list, remember its text var textToMatch = $('ul.list1 li.current').text(); // Loop through each li in the second list $('ul.list2 li').each(function(index, domElement){ var curr = $(domElement); // if the text matchs the first then add our class if(textToMatch == curr.text()){ curr.addClass('NEWCLASS'); } });

EDIT1:This is answering the wrong question, the question has since been clarified I will leave this here as it still seems nice :)

EDIT2: as Per Flex, this is a nicer way to achive the same thing, again not what the question was after.

$('.list2 li:contains("' + // Find an li in list2 which contains
    $('.list1 li.current').text() + '")')  // the same text as the as the current li in list1
    .addClass("NEWCLASS"); // and add our new class to it
David Waters
I assumed we where looking for elements of the second list with the same text. Other answers assume you mean at element of the same index in the second list.
David Waters
Sorry for being unclear - it's the same index (not necessarily text)
Meep3D
This can be done easier with `:contains`: `$('.list2 li:contains("' + $('li.current').text() + '")').addClass("whatever")`
Felix Kling
+1  A: 

Just simply use this:

var initialIndex = $('.list1 .current').index();
$('.list2 li').eq(initialIndex).addClass('current');
XGreen