jqueryjquery-selectorscustom-selectors

Custom selector for data in jQuery don't work


I have elements in the DOM that have set data('disabled', true) and I want to create custom selector that will select those elements. I try this:

jQuery.extend(jQuery.expr[':'], { 
    disabled: function(a,i,m) {
        return $(a).data('disabled') === true;
    }
});

and this:

jQuery.expr[':'].disabled = function(a,i,m) {
    return $(a).data('disabled') === true;
};

I also try !!$(a).data('disabled');

but it don't work, $('.parent :disabled') return nothing, even when I have elements that are inside .parent that have data('disabled'). Anybody know why.


Solution

  • It looks like it is because jQuery already has a selector named :disabled, if you rename it it works fine

    jQuery(function($){
        jQuery.extend(jQuery.expr[':'], { 
            disabled1: function(a,i,m) {
                console.log('x',arguments)
                return $(a).data('disabled') === true;
            }
        });
    
        $('.parent :disabled1').hide()
    })
    

    Demo: Fiddle