To easily solve this issue, you can assign a common class to all the elements and then use the is()
method to check if the e.target
belongs to any of those elements. You can then show or hide them accordingly. Give this a try:
$(window).click(function(e) {
if (!$(e.target).is('.common-class')) {
$('.common-class').hide();
}
});
.common-class {
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="element_1" class="common-class">One</div>
<div id="element_2" class="common-class">Two</div>
<div id="element_3" class="common-class">Three</div>
<div id="element_4" class="common-class">Four</div>
If modifying HTML by adding classes is not an option for you
In that scenario, you can inspect the clicked element's id
to determine if it starts with element_
. If it doesn't match, you can hide all the elements with IDs starting with that prefix. Here is how you can do it:
$(window).click(function(e) {
if (e.target.id.indexOf('element_') != 0) {
$('[id^=element_]').hide();
}
});
.common-class {
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="element_1" class="common-class">One</div>
<div id="element_2" class="common-class">Two</div>
<div id="element_3" class="common-class">Three</div>
<div id="element_4" class="common-class">Four</div>