Skip to content Skip to sidebar Skip to footer

How To Use JQuery To Filter Divs Based On Certain Classes

I am trying to create a filter system for a list of divs that contain a series of classes based on their content. So if I pick an option in 1 select, then the visible options will

Solution 1:

Here's a solution for you:

// you can target all of the select fields by just using
// jQuery(#selectContainer select) so that you don't have to write
// a separate onChange function for each individual select field
jQuery('#selectContainer select').on('change', function() {

    // define each of the select fields (color, shape, style)
    var color = '.' + jQuery('#select-1').val();
    var shape = '.' + jQuery('#select-2').val();
    var style = '.' + jQuery('#select-3').val();

    // To check whether an element has multiple classes, you 
    // shouldn't have white space between the class names.
    // e.g. classes will output like this: .class1.class2.class3
    var selectedClasses = (color + shape + style);

    // Hide all divs (will only stay hidden for a few milliseconds)
    jQuery('div.object').hide();

    // Show only the elements that have all three classes
    jQuery(selectedClasses).show();  

});

And here is the corresponding Pen: https://codepen.io/VisualHarmony/pen/GBqQYp


Solution 2:

So I figured it out with the help of a friend. The correct jQuery should be:

jQuery('#selectContainer select').on('change', function() {
var color = jQuery('#select-1').val();
var shape = jQuery('#select-2').val();
var style = jQuery('#select-3').val();

  jQuery('div.object').hide();

  jQuery('div.object').each(function() {
    if(jQuery(this).hasClass(color) && jQuery(this).hasClass(shape) && jQuery(this).hasClass(style)) {
    jQuery(this).show();
    }
  });

});

and that gets the result I was looking for. Here's the jsfiddle. Hope this helps someone else!


Post a Comment for "How To Use JQuery To Filter Divs Based On Certain Classes"