jQuery filtering selector to remove nested elements matching pattern

前端 未结 6 720
再見小時候
再見小時候 2020-12-17 01:58

Given this sample markup (assuming a random number of elements between .outer and .inner:

相关标签:
6条回答
  • 2020-12-17 02:31

    You could use some css magic:

    $('.outer>.inner')
    

    Shold give you only first level of .inner elements. :)

    0 讨论(0)
  • 2020-12-17 02:35
    $('.outer').children('.inner');
    

    That would select any inner that sits immediately below an outer. I'm not really clear on which div you're trying to select for. Is it a, b, c, or d? Having something called outer nested within something called inner doesn't make a whole lot of sense. Maybe if you could provide a more specific example?

    0 讨论(0)
  • 2020-12-17 02:36

    I wonder why not to select .inner at first, and then get closest .outer ?

    $inner = $('.inner');
    $outer = $inner.closest('.outer');
    

    in case some inner blocks could be not within outer blocks at all, use this first line instead

    $inner = $('.outer .inner');

    0 讨论(0)
  • 2020-12-17 02:41

    Here's another option. Suppose you have the .outer o, this will select all inners under it:

    o.find('.inner').not(o.find('.outer .inner'))
    

    It should work identically to gnarf's answer, but a bit simpler.

    First, it finds all inners under this outer.
    Next, remove all inners that are descendants of other outers

    Interactive working example: http://jsfiddle.net/Zb9gF/

    Selector performance seems to be much better using this method as opposed to the .filter() as well: http://jsperf.com/selector-test-find-not

    0 讨论(0)
  • 2020-12-17 02:42

    If assume correctly you want to select all .inner that is beneath an .outer, except if there is an .outer inbetween, perhaps following will work (untested):

    $('.outer:not(.inner):has(:not(.outer) .inner:not(.outer), > .inner:not(.outer))');
    

    updated after test on OP example HTML at http://jsfiddle.net/cEwBT/1/

    0 讨论(0)
  • 2020-12-17 02:48

    If the .inner are always direct children of .outers - children() is probably your best bet (jasongetsdown's answer)

    If you need something that looks even deeper, you could do something like this:

    var $outer = $('.outer').first(); // grab the first .outer
    $outer.find('.inner').filter(function() {
        // only if the closest parent .outer is the same as the .outer we are looking in
        return $(this).closest('.outer').get(0) == $outer.get(0);
    }).css('border','1px solid #000');
    

    jsfiddle demo

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