Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to addClass to its equal index .....(JQUERY)

<ul>
   <li>Index 0</li>
   <li>Index 1</li>
   <li>Index 2</li>
</ul>
<div>
     <a>Index 0</a>
     <a>Index 1 (If i click this this this i want to addClass to it to LI with the same index of this )</a>
     <a>Index 2</a>
</div>
like image 817
user555600 Avatar asked Jan 25 '11 09:01

user555600


2 Answers

You can invoke jQuerys .index()help method for that purpose. It returns the index relative the the siblings of the current node. To find the li node with the according index, use .eq()help

$('a').click(function() {
   $('ul li').eq($(this).index()).addClass('your_new_class');
});

Demo: http://www.jsfiddle.net/2rFn3/

Referring to your comment

$('a').click(function() {
   $('ul li').eq($(this).index()).addClass('your_new_class').siblings().removeClass('your_new_class');
});

Demo: http://www.jsfiddle.net/2rFn3/1/

like image 194
jAndy Avatar answered Oct 14 '22 05:10

jAndy


$("a").click(function() {
   //Remove classes from other li (per comment)
    $("ul li").removeClass("class");

   //Now update the clicked item
   var length = $(this).prevAll().length;
   $("ul li:eq(" + length + ")").addClass("class");
});
like image 40
Steve Avatar answered Oct 14 '22 07:10

Steve