最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - hide div if it doesn't have a certain class - Stack Overflow

programmeradmin5浏览0评论

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
Add a ment  | 

3 Answers 3

Reset to default 4

To 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();
发布评论

评论列表(0)

  1. 暂无评论