ether ether - 4 months ago 16
Javascript Question

jQuery: If class exists, remove it, then add it to new element

I'm working on an accordion style video section. I'm currently trying to check if a class exists on click. I want it to only open 1 section at a time, so I need to


  1. Check if the class exists on click

  2. If it does, remove class

  3. Add class to the clicked element



I tried doing this with just
addClass();
and
toggleClass();
but am not 100% sure on what I'm missing.

Add Class

$(".contents-row").click(function(){
$(this).toggleClass("content-open");
});


Toggle Class

$('.contents-row').click(function(){
$(this).toggleClass('content-open');
});


This is the basic HTML set up

<div class="contents-row">
<div class="content-option press">
<div class="class-section-title">test1</div>
</div>
<div class="drop">
test 1
</div>
</div>


A full version of the drop down in on JSFiddle.

Thanks for the help!

Answer

First remove content-open class from all elements having content-open class. Then add the class to clicked element like following.

$('.contents-row').click(function(){
    $('.content-open').removeClass('content-open');
    $(this).addClass('content-open');
});
Comments