JQuery - remove a class from all divs except the ones I clicked on

I have some code working that turns the "active" class on and off when you click on a div wrapper div.

However, I would like one of these divs to have an active class at a time. Right now I can click them all and everyone will have an active class. I'm not sure how to remove a class from all other divs except the ones I just clicked on.

I tried to use .parent (), but it didn't seem to work / I don't think I used it correctly.

HTML

<div class="variation_form_section"> <div class="select"> <div class="swatch-wrapper"></div> <div class="swatch-wrapper"></div> <div class="swatch-wrapper"></div> </div> </div> 

Js

 <script> $(document).ready(function(){ $(".variation_form_section .select div").each(function() { $(this).click(function() { if($(this).hasClass( "active" )){ $(this).removeClass( "active" ); }else{ $(this).addClass( "active" ); } }); }); }); </script> 
+5
source share
5 answers

Just remove the active class from them, and then add the active class to the clicked element.

 $(document).ready(function(){ $(".variation_form_section .select div").click(function() { $('.variation_form_section .select div').removeClass('active'); $(this).addClass('active'); }); }); 

Demo: http://jsfiddle.net/conm54k2/

+14
source

You can use not as follows:

 $(".variation_form_section .select div").click(function() { $(".variation_form_section .select div").not($(this)).removeClass('active'); }); 
+14
source

If you want to switch if the div is already active, you just need to check it before clearing all assets. After that, add only the active state if the selected div was not originally active.

http://jsfiddle.net/wilchow/6208d114/

 $(document).ready(function(){ $(".variation_form_section .select div").click(function() { var isActive = ($(this).hasClass('active')) ? true : false; // checks if it is already active console.log("isActive: "+isActive); $('.variation_form_section .select div').removeClass('active'); if(!isActive) $(this).addClass('active'); // set active only if it was not active }); }); 
+4
source

You can try using .siblings () http://api.jquery.com/siblings/

 $(document).on('ready', function(){ $(".variation_form_section .select div").on('click', function() { $(this).addClass('active').siblings().removeClass('active'); }); }); 

demo: http://jsfiddle.net/conm54k2/4/

+2
source
 <script> $(document).ready(function(){ $(".swatch-wrapper").on('click',function() { $(".swatch-wrapper").removeClass('active'); $(this).addClass('active'); }); }); </script> 
0
source

Source: https://habr.com/ru/post/1207440/


All Articles