Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery siblings how to remove class?

I have the following jQuery:

<script type="text/javascript">
$('.showFood').on('click', function () {
    $(this).addClass('selected').siblings().removeClass('selected');
    $('.targetFood').hide();
    $('#food' + $(this).data('target')).show(function() {
        $('#food' + $(this).data('target')).toggle("slide");
    });
});
$('.showFood').first().click();
</script>

The following HTML:

<ul class="menus-nav">
<li><a href="#menu1" class="showFood" data-target="1">Menu 1</a></li>
<li><a href="#menu2" class="showFood" data-target="2">Menu 2</a></li>
<li><a href="#menu3" class="showFood" data-target="3">Menu 3</a></li>
</ul>
<div id="food1" class="targetFood">
<p>Items from menu 1</p>
</div>

<div id="food2" class="targetFood">
<p>Items from menu 2</p>
</div>

<div id="food3" class="targetFood">
<p>Items from menu 3</p>
</div>

Everything works fine except when you navigate through the menus it won't remove the selected class and once you click all menus they all have the class selected.

I don't have a great experience in javascript or jquery, any chance some of you guys could give me some help please?

Note: the html has been reduced for demo purpose.

Fiddle

like image 855
lesandru Avatar asked Oct 01 '13 10:10

lesandru


People also ask

Can you remove a class with jQuery?

Similarly, you can remove the classes from the elements using the jQuery removeClass() method. The removeClass() method can remove a single class, multiple classes, or all classes at once from the selected elements.

What is the use of siblings in jQuery?

Definition and Usage The siblings() method returns all sibling elements of the selected element. Sibling elements are elements that share the same parent. The DOM tree: This method traverse forward and backwards along siblings of DOM elements.

What is remove class?

A Remove class in education is or was a group of students at an English public school, typically a year group: for example the year group between the fourth form and the fifth form.


1 Answers

This line of code might be your problem:

$(this).addClass('selected').siblings().removeClass('selected');

You probably want to delete the classes first, then add it to the selected element:

$('.selected').removeClass('selected'); // remove all current selections
$(this).addClass('selected')            // select this element
like image 136
naloxx Avatar answered Nov 15 '22 20:11

naloxx