Add class for the clicked button and remove class from siblings

Viewed 784

I want to add a class to the button that is clicked and remove that class from all of the siblings(button). The below code adds the CSS for the buttons which I click and unable to remove the CSS for the buttons that are already applied.

$("#followingButtonsId").children().addClass('buttonSelected')
            .parent().siblings().find('.buttonSelected').removeClass('buttonSelected');
.buttonSelected { background: #5b2200;}
<div class="row" id="followingButtonsId">
    <button class="buttonSelected">Button1</button>
    <button>Button2</button>
    <button>Button3</button>
</div>

2 Answers

On click I remove the class buttonSelected from all buttons and then add it on the one that is clicked

$('button').click(function(e) {
  $('button').removeClass('buttonSelected');
  $(e.target).addClass('buttonSelected');
});
.buttonSelected {
  background: #5b2200;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row" id="followingButtonsId">
  <button class="buttonSelected">Button1</button>
  <button>Button2</button>
  <button>Button3</button>
</div>

This should work:

$("#followingButtonsId button").on("click", function() {
    $("#followingButtonsId button").removeClass("buttonSelected");
    $(this).addClass("buttonSelected");
});
Related