Select element unless it has an ancestor of a given class using just a selector

后端 未结 5 905
孤街浪徒
孤街浪徒 2021-01-03 23:11

Suppose I have the following HTML:

  • One
  • Two
相关标签:
5条回答
  • 2021-01-03 23:23

    You can do it like this

    $("li").not('.foo li')
    

    http://jsfiddle.net/y7s54/

    or

    $("li:not(.foo li)")
    

    http://jsfiddle.net/QpCYY/

    Select all li's that don't have an ancestor with class foo

    0 讨论(0)
  • 2021-01-03 23:32

    I think this solution looks a little nicer, but there's a bit of controversy on the API comments about speed differences.

    $("li").not(".foo li")
    

    fiddle

    0 讨论(0)
  • 2021-01-03 23:34

    How about this:

    $("li:not(.foo > li)")
    

    The comments in the docs are quite useful if this doesn't work:

    http://api.jquery.com/not-selector/

    0 讨论(0)
  • 2021-01-03 23:44

    Try li:not(.foo > ul > li); that selects all lis minus those with a parent .foo two levels up.

    0 讨论(0)
  • 2021-01-03 23:49

    You can do it using context along with selector as under,

    $('li', $('div:not(.foo)'))
    

    LIve Demo

    $('li', $('div:not(.foo)')).each(function(){
        alert($(this).text());
    });​
    
    0 讨论(0)
提交回复
热议问题