I need to hide a class if it doesn't have the class active
.
$(document).ready(function() {
if (!$('.active').hasClass('active')) {
$(this).hide();
};
});
<script src=".1.1/jquery.min.js"></script>
<div class="subheader active">
<p>Hello</p>
</div>
<div class="subheader">
<p>Goodbye</p>
</div>
<div class="subheader">
<p>Hello Again</p>
</div>
I need to hide a class if it doesn't have the class active
.
$(document).ready(function() {
if (!$('.active').hasClass('active')) {
$(this).hide();
};
});
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="subheader active">
<p>Hello</p>
</div>
<div class="subheader">
<p>Goodbye</p>
</div>
<div class="subheader">
<p>Hello Again</p>
</div>
Share
Improve this question
asked Jul 5, 2015 at 21:04
Mr.SmithyyyMr.Smithyyy
1,33913 gold badges55 silver badges104 bronze badges
0
3 Answers
Reset to default 4To hide the subheader
that doesn't have the class active
, use
$('.subheader:not(.active)').hide();
A better solution would be, I think, to use pure CSS for this:
.subheader {
display: none;
}
.subheader.active {
display: block;
}
As demonstrated in this snippet, that only uses jQuery to toggle the class, and uses CSS to decide what happens with it visually.
$('.subheader').on('click', function(){
$('.subheader').toggleClass('active');
});
.subheader {
display: none;
}
.subheader.active {
display: block;
}
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="subheader active">
<p>Hello, click to toggle</p>
</div>
<div class="subheader">
<p>Goodbye</p>
</div>
<div class="subheader">
<p>Hello Again</p>
</div>
$(function() {
$('.subheader:not(.active)').hide();
});
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="subheader active">
<p>Hello</p>
</div>
<div class="subheader">
<p>Goodbye</p>
</div>
<div class="subheader">
<p>Hello Again</p>
</div>
Or, with css:
.subheader{ display: none; }
.subheader.active{ display: block; }
<div class="subheader active">
<p>Hello</p>
</div>
<div class="subheader">
<p>Goodbye</p>
</div>
<div class="subheader">
<p>Hello Again</p>
</div>
Use below code to hide divs with subheader class:
$('.subheader:not(.active)').hide();