Reputation: 18745
I have a simple page with buttons. After clicking on the button, the text appears right under this button using toggle
.
This work's correct but it does not "untoggle" another sections/buttons. So what I want is on click not just toggle the section under the button but also untoggle another toggled section.
I've added a loop over all sections which is executed right after click and it should "hide" all sections and then do what it has to do - show this
section.
ncaught TypeError: acc.removeClass is not a function
$(document).ready(function(){
var accs = $('.accordion');
$('.accordion').on('click',function(){
$.each(accs,function(acc){
acc.removeClass('active'); # NOT WORKING
acc.nextElementSibling.classList.remove('show'); # NOT WORKING
});
this.classList.toggle('active'); # WORKING
this.nextElementSibling.classList.toggle("show"); # WORKING
})
});
Do you know where is the problem?
Upvotes: 1
Views: 1699
Reputation: 2799
The issue is that acc
is the index of the element within the each function. You need to use $(this).eq(acc)
or accs.eq(acc).
$(document).ready(function(){
var accs = $('.accordion');
$('.accordion').on('click',function(){
$.each(accs,function(index){
accs.eq(index).removeClass("active");
accs.eq(index).classList.remove("show"); //you don't need next because this each function will remove the class 'active' and 'show' from every accs element regardless
});
$(this).toggleClass('active');
$(this).next().toggleClass("show");
})
});
Right now you're treating an integer (index) as an object. That will not work.
Upvotes: 0
Reputation: 133433
removeClass()
is not a native DOM element method, thus you are getting the error. Convert the DOM element into jQuery object then you can use the methods.
Since you already have jQuery object directly use it like
accs.removeClass('active'); //remove class from element
accs.next().removeClass('show'); //Remove class from sibling
instead of
$.each(accs,function(acc){
acc.removeClass('active'); # NOT WORKING
acc.nextElementSibling.classList.remove('show'); # NOT WORKING
});
Upvotes: 3
Reputation: 8496
I hope below code will work
$(document).ready(function(){
var accs = $('.accordion');
$('.accordion').on('click',function(){
accs.each(function(index){
$(this).removeClass('active');
$(this).next().removeClass("show");
});
$(this).toggleClass('active');
$(this).next().toggleClass("show");
})
});
Upvotes: 2