Search code examples
jqueryclassname

jQuery: show child elements with class/es that match their parent class/es


I have lists of child elements that need to be filtered based on the matching of any of their classes to those of their parent.

The parent and children elements can in theory have any number of classes.

Essentially, if a child does not have a class that the parent also has, it needs to be hidden.

The classes in each case are going to be unknown, so I can't target any specific class names.

An example of my markup:

<ul id="mylist" class="class1 class2">
    <li class="class1">This should be visible (class1)</li>
    <li class="class2">This should be visible (class2)</li>
    <li class="class1 class2">This should be visible (class1 class2)</li>
    <li class="class3 class2 class1">This should be visible (class3 class2 class1)</li>
    <li class="class2 class3">This should be visible (class2 class3)</li>
    <li class="class3 class4">This should be hidden (class3 class4)</li>
    <li class="class3">This should be hidden (class3)</li>
    <li class="class4">This should be hidden (class4)</li>
</ul>

So far, I have got to this:

$('#mylist li').each(
function(i) {
    var classes = this.className.split(/\s+/);
    for (var i=0,len=classes.length; i<len; i++){
        if (!$('#mylist').hasClass(classes[i])){
            $(this).hide();
        }
    }
});

Something is not quite right in the logic. I have correct results for eg:

<li class="class1">This is visible</li>
<li class="class2">This is visible</li>
<li class="class1 class2">This is visible</li>

But not for eg:

<li class="class3 class2">This should be visible</li>

Here is a fiddle: http://jsfiddle.net/455qdrn8/


Solution

  • I think what you should do is to show elements which has a common class with the parent so

    var $lis = $('#mylist li'),
        classes = $.map($('#mylist').attr('class').split(/\s+/), function (value) {
            return '.' + value
        });
    
    $lis.hide().filter(classes.join()).show();
    

    Demo: Fiddle