What JQuery selector excludes items with a parent that matches a given selector?

前端 未结 7 791
Happy的楠姐
Happy的楠姐 2020-12-02 16:39

I have

var $set = $(\'.foo,.bar\').filter(
    function() {return $(this).parents(\'.baz\').length < 1;});

as a way to select all the el

相关标签:
7条回答
  • 2020-12-02 17:16

    The truth of the matter is that jQuery simply does not have a particularly elegant way to do what you want. While chaos' answer does work, you have to wonder whether the complicated selector (that would be about as slow as a selector can be in a complicated webpage) is worth it over the more verbose but faster filter function you have. This is not really that big of a deal, I am just personally weary of particularly long, convoluted selectors when I can avoid it.

    A different option is to create your own selector, since jQuery is awesome:

    jQuery.expr[':'].parents = function(a,i,m){
        return jQuery(a).parents(m[3]).length < 1;
    };
    
    $('.foo,.bar').filter(':parents(.baz)');
    

    The expr map is part of the Sizzle selector engine and documentation can be found here: Sizzle Custom Pseudo-Selectors

    0 讨论(0)
提交回复
热议问题