2

I have a list

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

I need a jquery to add a class to one of active class siblings (prev or next sibling). This is a part of a navigation and active class it's the active page. Can anyone help please?

Thank you!!

UPDATE: I found another way to add style to the next element from a list, with css: CSS next element Here's a demo: http://jsfiddle.net/S52YH/2/ Thank you for your effort!!

Community
  • 1
  • 1
Cristina Cristea
  • 566
  • 1
  • 3
  • 11

4 Answers4

7

Add class to previous li

$('li.active').prev().addClass("someclass");

Add class to next li

$('li.active').next().addClass("someclass");
Venkata Krishna
  • 14,926
  • 5
  • 42
  • 56
  • this could help me but the class "someclass" is not moving. Here is my example http://jsfiddle.net/S52YH/1/ the active class is moving from a li to another when clicked. – Cristina Cristea Nov 21 '13 at 08:44
  • thank you but I found another way to do it: UPDATE: I found another way to add style to the next element from a list, with css: CSS next element Here's a demo: http://jsfiddle.net/S52YH/2/ Thank you for your effort!! – Cristina Cristea Nov 21 '13 at 09:25
2

You should use li elements for menu items. So there should be only one active classed element. If so,

var $activeElement = $(".active");

$( ".active" ).next().addClass( "active" );
$activeElement.removeClass("active");

See Fiddle

zkanoca
  • 9,664
  • 9
  • 50
  • 94
1

Try this demo fiddle

//  this will apply active class to all li
$('ul li').addClass('active');
//  this will apply particular index of child
$('ul li:nth-child(2)').addClass('active');
stanze
  • 2,456
  • 10
  • 13
0
$('.active').prev().addClass('foo');

or

$('.active').next().addClass('foo');
j08691
  • 204,283
  • 31
  • 260
  • 272