JQuery hides multiple divs of the same identifier when clicking on it

I want to hide everything divwith a similar one id, if not click on any of these divs. In my code, it only works for the first div, as I use index[0]to get the identifier. I want to generalize it to work for all id.

Here is the code:

$(window).click(function(e) {
  if (e.target.id != $('[id^=div_]')[0].id) {
    $('[id^=div_]').hide();
  }
});
div {
  height: 150px;
  width: 150px;
  display: inline-block;
  background: green;
  margin: 10px;
  color: #fff;
  text-align: center;
  line-height: 150px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="div_1">One</div>
<div id="div_2">Two</div>
<div id="div_3">Three</div>
<div id="div_4">Four</div>
Run code

Fiddle

+4
source share
2 answers

A simple solution here is to use a common class for all elements. Then you can use is()to determine if e.targetone of these elements was and hide / show them as needed. Try the following:

$(window).click(function(e) {
  if (!$(e.target).is('.div')) {
    $('.div').hide();
  }
});
div {
  height: 150px;
  width: 150px;
  display: inline-block;
  background: green;
  margin: 10px;
  color: #fff;
  text-align: center;
  line-height: 150px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="div_1" class="div">One</div>
<div id="div_2" class="div">Two</div>
<div id="div_3" class="div">Three</div>
<div id="div_4" class="div">Four</div>
Run code

- HTML,

id , , div_. , divs, - :

$(window).click(function(e) {
  if (e.target.id.indexOf('div_') != 0) {
    $('[id^=div_]').hide();
  }
});
div {
  height: 150px;
  width: 150px;
  display: inline-block;
  background: green;
  margin: 10px;
  color: #fff;
  text-align: center;
  line-height: 150px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="div_1" class="div">One</div>
<div id="div_2" class="div">Two</div>
<div id="div_3" class="div">Three</div>
<div id="div_4" class="div">Four</div>
+3

,

if(e.target.id=="" || $('[id^=div_]').filter('#'+e.target.id).length==0){
     $('[id^=div_]').hide();
  }

filter div div whoes id div

$(window).click(function(e) {
  if(e.target.id=="" || $('[id^=div_]').filter('#'+e.target.id).length==0){
     $('[id^=div_]').hide();
  }

});
div {
  height: 150px;
  width: 150px;
  display: inline-block;
  background: green;
  margin: 10px;
  color: #fff;
  text-align: center;
  line-height: 150px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="div_1">One</div>
<div id="div_2">Two</div>
<div id="div_3">Three</div>
<div id="div_4">Four</div>
-1

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


All Articles