We have the following situation:
<ul>
<li>Button 1</li>
<li class="active">Button 2</li>
<li>Button 3</li>
<li>Button 4</li>
</ul>
now the following code that handles it:
$('.tab-menu li').on('click', function() {
$($($(this).closest('.tab-menu')).find('li')).removeClass('active');
$(this).addClass('active');
});
it works, but is there a jQuery function that selects all 'parallel' elements ? I want this part
$($($(this).closest('.tab-menu')).find('li')).removeClass('active');
make shorter. I know 'toggleClass', but this works only on the clicked element. Is there any shorter method to select all parallel elements? (In this siutation all 'li' that belongs to the specific 'ul');
We have the following situation:
<ul>
<li>Button 1</li>
<li class="active">Button 2</li>
<li>Button 3</li>
<li>Button 4</li>
</ul>
now the following code that handles it:
$('.tab-menu li').on('click', function() {
$($($(this).closest('.tab-menu')).find('li')).removeClass('active');
$(this).addClass('active');
});
it works, but is there a jQuery function that selects all 'parallel' elements ? I want this part
$($($(this).closest('.tab-menu')).find('li')).removeClass('active');
make shorter. I know 'toggleClass', but this works only on the clicked element. Is there any shorter method to select all parallel elements? (In this siutation all 'li' that belongs to the specific 'ul');
Share Improve this question edited Sep 9, 2013 at 13:07 Oskar Szura asked Sep 9, 2013 at 12:57 Oskar SzuraOskar Szura 2,5695 gold badges34 silver badges43 bronze badges 10-
1
Isn't that entire first part redundant?
$($(this).closest('.tab-menu')).find('li'))
is alreadythis
– tymeJV Commented Sep 9, 2013 at 12:59 -
1
no it will be a list of all the
li
's under.tab-menu
not just the one currently being iterated over – DGS Commented Sep 9, 2013 at 13:00 - @DGS But he iterates over all of them. It's nonsensical code. – Reinstate Monica Cellio Commented Sep 9, 2013 at 13:01
-
1
You don't need to keep recasting things to jquery objects (the
$($($(
). Nearly all jquery functions return jquery objects. The only one that I know of which does not isget
which is explicitly for getting the dom element out of the jquery object. – MushinNoShin Commented Sep 9, 2013 at 13:01 -
1
@OskarSzura Should the code above really say
each
?? – Reinstate Monica Cellio Commented Sep 9, 2013 at 13:04
1 Answer
Reset to default 8Try this, using .siblings()
$(this).addClass('active').siblings().removeClass('active');
DEMO with onclick