How to target objects of the same class that were not clicked using jQuery?

I have 3 divs of the same class, but with a unique identifier, and when I click on one cell, I would like to hide the other 2.

This is not a problem, and I could achieve this with a few if / elses or case case, perhaps, but I was wondering if there is a more general / efficient way to hide all elements of the same class that are not the one that was clicked?

<div id="boxes"> <div id="box1" class="box">Box 1</div> <div id="box2" class="box">Box 2</div> <div id="box3" class="box">Box 3</div> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function () { $('.box').click(function() { $(this).html('hi'); if ($(this).attr('id') == 'box1') { $('#box2').hide('slow'); $('#box3').hide('slow'); } .......... more if }); }); </script> 
+4
source share
5 answers

You can use the .not filter function to refer to "others". That way, the code will work even if the boxes are not necessarily siblings in the DOM tree, or if there are additional siblings that are not boxes.

 var $boxes = $('.box'); $boxes.click(function() { $(this).html('hi'); $boxes.not(this).hide('slow'); }); 

Note that I am caching the result of $('.box') for performance - no doubt it will not be noticeable, but there is no reason not to.

+5
source

You want to hide the siblings of a clicked div:

 $('.box').click(function() { $(this).siblings().hide("slow"); }); 
+4
source
 $('.box').click(function() { var bTrigger = $(this); $('.box').each(function() { if($(this) != bTrigger) $(this).hide('slow'); }); }); 
+1
source

if you want to hide all .box except click:

 $('.box').click(function() { $('.box').not(this).hide('slow'); }); 
+1
source

Try the following:

 $(document).ready(function () { $(".box").bind("click", function(){ $(".box").hide("slow"); $(this).show(); }); } 
0
source

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


All Articles