Jquery Remove Class Multiple Elements
Asked Answered
R

2

8

I am setting a class to multiple elements via a Button click via the code below:

$('button.but1').on('click', function() {
    $(".div1,.div2,.div3").addClass("focus");
    $(".div1,.div2,.div3").css("z-index", "99");
    $(".div1,.div2,.div3").css("opacity", "1");
});
$('button.but2').on('click', function() {
    $(".div4,.div5,.div6").addClass("focus");
    $(".div4,.div5,.div6").css("z-index", "99");
    $(".div4,.div5,.div6").css("opacity", "1");
});

HTML:

<div class="div1"></div>
<div class="div2"></div>
<div class="div3"></div>
<div class="div4"></div>
<div class="div5"></div>
<div class="div6"></div>
<button type="button" class="but1" href="#">But1</button>
<button type="button" class="but2" href="#">But2</button>

The issue I am having is that I only want the div selected to be "focus"(the class), all the other div, not from the same group need to have the "focus" class removed. Not sure which we to go?

Revolution answered 15/4, 2015 at 16:2 Comment(0)
I
18

You can remove the already added class before adding the class to set of elements.like this:

 $(".focus").removeClass("focus");
 $(".div4,.div5,.div6").addClass("focus");

Complete Code:

$('button.but1').on('click', function() {
  $(".focus").removeClass("focus");
  $(".div1,.div2,.div3").addClass("focus");
  $(".div1,.div2,.div3").css("z-index", "99");
  $(".div1,.div2,.div3").css("opacity", "1");
});

$('button.but2').on('click', function() {
  $(".focus").removeClass("focus");
  $(".div4,.div5,.div6").addClass("focus");
  $(".div4,.div5,.div6").css("z-index", "99");
  $(".div4,.div5,.div6").css("opacity", "1");
});
Iveson answered 15/4, 2015 at 16:5 Comment(0)
U
2

Just remove the class from all the 'other' divs first:

$('button.but1').on('click', function() {
    $(".div4,.div5,.div6").removeClass("focus");
    $(".div1,.div2,.div3").addClass("focus");
    $(".div1,.div2,.div3").css("z-index", "99");
    $(".div1,.div2,.div3").css("opacity", "1");
});
$('button.but2').on('click', function() {
    $(".div1,.div2,.div3").removeClass("focus");
    $(".div4,.div5,.div6").addClass("focus");
    $(".div4,.div5,.div6").css("z-index", "99");
    $(".div4,.div5,.div6").css("opacity", "1");
});
Urena answered 15/4, 2015 at 16:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.