Home > Back-end >  JavaScript loop over clickable elements on click event, and skip the specific clicked element
JavaScript loop over clickable elements on click event, and skip the specific clicked element

Time:09-27

<div>
 <div class="clickable">1</div>
 <div class="clickable">2</div>
 <div class="clickable">3</div>
 <div class="clickable">4</div>
</div>

Upon clicking one of the 'clickable' elements i want to add a new class to all elements with 'clickable' class except the one that has been clicked.

 $('.clickable').on('click', function (e) {
            $('.clickable').each(function () {
               $(this).addClass('new-class')

            });
})

How, inside the loop, can i skip the specific element that was clicked?

CodePudding user response:

$('.clickable').on('click', function() {
  $(this).removeClass('new-class').siblings().addClass('new-class');
});

CodePudding user response:

This is the simplest to control and read

You do not need the each

$('.clickable').on('click', function(e) {
  $('.clickable').addClass('new-class');
  $(this).removeClass('new-class'); 
})
.new-class {
  color: red
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <div class="clickable">1</div>
  <div class="clickable">2</div>
  <div class="clickable">3</div>
  <div class="clickable">4</div>
</div>

If they are surely all in the same container, you can use siblings. To chain you MUST remove before adding

$('.clickable').on('click', function(e) {
  $(this)
   .removeClass('new-class')  // still necessary for the second click of another element
   .siblings().addClass('new-class');
})
.new-class {
  color: red
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <div class="clickable">1</div>
  <div class="clickable">2</div>
  <div class="clickable">3</div>
  <div class="clickable">4</div>
</div>

CodePudding user response:

There is a not method in jQuery so the simplest thing you can do in my opinion is with the help of not method like below:

$('.clickable').on('click', function (e) {
  $('.clickable').not(this).addClass('new-class');
})
  • Related