Mr Jonny Wood
Mr Jonny Wood

Reputation: 3854

jquery .removeClass() if NOT .next()

How would I go about remove the class from all elements except the next one?

For example:

<ul>
  <li class="current"><a href="#">Trigger</a></li>
  <li class="next"><a href="#">Trigger</a></li>
  <li class="next"><a href="#">Trigger</a></li>
  <li class="next"><a href="#">Trigger</a></li>
</ul>

Clicking on Trigger link a removes all the "next" classes from the li elements except the one directly below

I'm not worried about the whole set of code to achieve this. I've written everything that I need apart from this one thing of removing the class except on the next li?!

UPDATE: SOLVED

Seems I overlooked a simple solution which works well:

$(this).parent().siblings().not().next().removeClass('next');

Upvotes: 0

Views: 3323

Answers (5)

addisu
addisu

Reputation: 634

You can get the nextAll for the next li element , and your li is a parent of the links

$("a").click( function() {
   $(this).parent().next().nextAll().removeClass();  
});​

http://jsfiddle.net/L7KaS/

Upvotes: 0

Rob W
Rob W

Reputation: 348992

Use the .nextAll method to get all consecutive siblings after the current element. Then, reduce the set using .slice(1).

$('li a').click(function() {
    $(this).parent().nextAll().slice(1).removeClass('next');
});

The previous method only removes next from later items. If you want to affect all siblings, the following can be used:

$('li a').click(function() {
    var $parent = $(this).parent();
    $parent.siblings().not($parent.next()).removeClass('next');
});

Another option: Remove the next class from all elements, then add it to the next element.

Upvotes: 3

Richard Neil Ilagan
Richard Neil Ilagan

Reputation: 14747

You can try this:

var $ul = $('ul').on('click', 'a', function () {

    // get the next element
    var n = $(this).next('a');

    // get everything else except this
    $ul.find('a').not(this).removeClass('next');

});

Upvotes: 0

Tatu Ulmanen
Tatu Ulmanen

Reputation: 124768

Something like this:

$('a').click(function() {
    $(this).parent().nextAll('.next').not($(this).next()).removeClass('next');

});

Upvotes: 0

Mr Jonny Wood
Mr Jonny Wood

Reputation: 3854

Just realised it's very simple!

$(this).parent().siblings().not().next().removeClass('next');

Upvotes: 0

Related Questions