Search code examples
jqueryjquery-selectorspattern-matchingsizzle

Using jQuery's Sizzle Engine to find a class (advanced)


What I am attempting to do is see if a jQuery object (or even DOM element for that matter) contains a particular class using the same selectors as the Sizzle engine.

jQuery publicly exposes Sizzle with the following:

jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;
jQuery.expr[":"] = jQuery.expr.filters;
jQuery.unique = Sizzle.uniqueSort;

I can successfully use the find method to determine that a particular DOM element has a class matching my selector but I cannot seem to find a way to get access to the name of the selector that matched.

EXAMPLE (NOT WORKING AS INTENDED)

$.fn.extend({
    getMatchingClass: function(selector) {
        return this.each(function() {
            var match = jQuery.find.matches('*[class'+selector+']', [this]);
                    // I would like to return the matching class's FULL NAME,
                    // i.e. lightbox_RESTOFCLASS
            alert(match[0]);
        });
    }
});

var class = $('#lightbox').getMatchingClass('^="lightbox_"');

Is it possible to use Sizzle to return the class name which matched my selector?


Solution

  • I've come up with a non-sizzle solution using a subset of selectors (^=, $=, *=, and =) which is fully working. A Sizzle solution would have been nice, however. This should at least demonstrate what the intended functionality of the plugin should do.

    $.fn.getMatchingClass = function(selector) {
        var regex, class, tmp, $this;
        tmp = $(this)[0].className;
        class = selector;
        class = class.replace(/(\^|\*|\$)?=/i, '');
        class = class.replace(/\"/g, '');
        if (selector.indexOf('$=') != -1) {
            regex = new RegExp('[\\s]+' + class + '$', 'i');
        } else if (selector.indexOf('^=') != -1) {
            regex = new RegExp('^' + class + '[\\s]+', 'i');
        } else if (selector.indexOf('*=') != -1) {
            regex = new RegExp('[a-zA-z0-9_\\-]*' + class + '[a-zA-z0-9_\\-]*', 'gi');
        } else if (selector.indexOf('=') != -1) {
            regex = new RegExp('^' + class + '$', 'i');
        } else return false;
        return tmp.match(regex);
    }
    
    var class = $('#myID').getMatchingClass('*="lightbox"');
    var class2 = $('#myID').getMatchingClass('^=lightbox');
    var class3 = $('#myID').getMatchingClass('="lightbox"');
    var class4 = $('#myID').getMatchingClass('$=lightbox');
    alert(class);
    alert(class2);
    alert(class3);
    alert(class4);