Meep3D
Meep3D

Reputation: 3756

Matching classes with jquery

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.

Upvotes: 1

Views: 264

Answers (4)

David Waters
David Waters

Reputation: 12028

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

Upvotes: 1

Ali Habibzadeh
Ali Habibzadeh

Reputation: 11548

Just simply use this:

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

Upvotes: 1

markcial
markcial

Reputation: 9323

$('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');

Upvotes: -1

Pointy
Pointy

Reputation: 413702

$('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

Upvotes: 7

Related Questions