jonmrich
jonmrich

Reputation: 4323

Hide all instances of a class except for the one clicked

My HTML sets up like this.

<div id="A" class="square channels blue">A</div>
<div id="B" class="square channels blue">B</div>
<div id="C" class="square channels blue">C</div>

What I want to do is get the id for the class that was selected...like this:

$('.channels').click(function() {
alert(this.id ) //This gets me the right `id`
});

Now what I want to do is hide all the other instances of "channels" classes, but show (i.e., not hide) the one that was selected. In other words, hide all the instances of the class "channels" except for the one that was clicked on.

This doesn't work obviously, but not exactly sure how to do this:

$('.channels').click(function() {
    $('.channels').hide();
   $(this.id).show();
    });

Upvotes: 2

Views: 1093

Answers (4)

gaetanoM
gaetanoM

Reputation: 42054

You can use the .not selector:

$('.channels').on('click', function(e) {
    $('.channels').not(this).hide();
});

The example:

$('.channels').on('click', function(e) {
  $('.channels').not(this).hide();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<div id="A" class="square channels blue">A</div>
<div id="B" class="square channels blue">B</div>
<div id="C" class="square channels blue">C</div>

Upvotes: 6

Banzay
Banzay

Reputation: 9470

Even this solution will work

$('.channels').click(function() {
   $('.channels').hide();
   $(this).show();
});

Upvotes: 1

Anil M
Anil M

Reputation: 100

You can do this

$('.channels').click(function() {
    $('.channels').hide();
   $("#"+$(this).id).show();
    });

Without #, it will not use id.

Upvotes: 1

Michael Lorton
Michael Lorton

Reputation: 44386

I think this

$("#" + this.id).show();

will work.

Upvotes: 1

Related Questions