Search code examples
jqueryjquery-selectorstraversal

Selecting an element with multiple classes in jQuery


I want to select an element which has a few classes

Something like this HTML:

<div class="myclass fclass sclass tclass"></div>
<div class="myclass tclass"></div>
<div class="myclass sclass tclass"></div>
<div class="myclass fclass tclass"></div>
<div class="myclass fclass sclass tclass"></div>

I only want to select the element with the myclass tclass classes.

I don't really want to do it in a way where I have to know every class, like this:

$(".myclass.tclass").not(".fclass, .sclass")

Solution

  • May not work great as a callback with a named function (if you need it done with different class types), but the demo shows it works:

    $('.myclass.tclass').filter(match_exact_class);
    
    function match_exact_class() {
        return $(this).attr('class').split(/\s+/).length == 2;
    }
    

    http://jsfiddle.net/userdude/9bc4qjn4/1

    As a single call:

    $('.myclass.tclass').filter(function match_exact_class() {
        return $(this).attr('class').split(/\s+/).length == 2;
    });
    
    $('.myclass.tclass.sclass').filter(function match_exact_class() {
        return $(this).attr('class').split(/\s+/).length == 3;
    });
    
    $('.myclass.tclass.tclass.sclass').filter(function match_exact_class() {
        return $(this).attr('class').split(/\s+/).length == 4;
    });
    

    I suspect you could roll a simple plugin or custom selector and then split on the selector, something like:

    var selector = '.myclass.tclass.tclass.sclass',
        sel_match = selector.split('.').length;
    
    $(selector).filter(function match_exact_class() {
        return $(this).attr('class').split(/\s+/).length == sel_match;
    });
    

    Simple custom selector:

    jQuery.extend(jQuery.expr[':'], {
        matcls: function(elem, i, match){
            return elem.className.split(/\s+/).length == match[3].split(/\s+/).length;
        }
    });
    
    console.log($('div:matcls("myclass tclass")'));
    

    http://jsfiddle.net/userdude/9bc4qjn4/4