Alex Szymanowski Alex Szymanowski - 5 months ago 16
jQuery Question

checkbox Filter divs displayed by class with multiple classes

I have this http://jsfiddle.net/RyZy8/221/

The JS

$('input[type="checkbox"]').click(function() {
if ($('input[type="checkbox"]:checked').length > 0) {
$('#main-div > div > div > div').hide();
$('input[type="checkbox"]:checked').each(function() {
$('#main-div > div > div > div[class=' + this.id + ']').show();
});
} else {
$('#main-div > div > div > div').show();

}
});


The HTML:

<input type="checkbox" id="one">
<input type="checkbox" id="two">
<input type="checkbox" id="three">

<div id="main-div">
<div>
<div>
<div class="one two other classes">
Content
</div>
</div>
</div>
</div>

<div id="main-div">
<div>
<div>
<div class="one three other classes">
Content
</div>
</div>
</div>
</div>

<div id="main-div">
<div>
<div>
<div class="two three other classes">
Content
</div>
</div>
</div>
</div>


The check boxes will filter fine if a single class is used but not when multiple classes are present.

How would I change the following to allow for multiple classes

$('#main-div > div > div > div[class=' + this.id + ']').show();

Answer

You probably don't want to use an attribute selector here since it'll be looking for exact text. You'll want to use the class selector instead, which will just look for the presence of the class, regardless of other classes present.

$('#main-div > div > div > div.' + this.id).show();

I'd also advise against using nested direct child selectors like you're doing (div > div > div). This is quite brittle and will break the moment you change your HTML hierarchy, which will be painful for you when refactoring.

Something like this may be better:

$('#main-div .' + this.id).show();

Having said that, you also never want to re-use ids on a page. According to Mozilla Developer Network, an id 'must be unique in a document'. If you ever wanted to use getElementById, it would only return the first item it finds, rather than an array of items. main-div should probably be a class in this case.