选择元素,除非它具有仅使用选择器的给定类的祖先 [英] Select element unless it has an ancestor of a given class using just a selector

查看:84
本文介绍了选择元素,除非它具有仅使用选择器的给定类的祖先的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我具有以下HTML:

Suppose I have the following HTML:

<div class="foo">
  <ul>
    <li>One</li>
    <li>Two</li>
  </ul>
</div> <!-- not originally here -->
<div class="bar">
  <ul>
    <li>Three</li>
    <li>Four</li>
  </ul>
</div>

我想选择所有不是类foo的元素的不是后代的li元素.我知道我可以使用精美的过滤器来完成此操作功能,但我想知道是否可以仅使用选择器就能做到这一点.首先,我尝试过:

I want to select all li elements that are not descendants of an element with class foo. I know I can do it with a fancy filter function, but I'm wondering whether I can do it with just a selector. First I tried:

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

不幸的是,这不起作用,因为li other 个祖先,但没有样式(在本例中为ul).以下似乎有效;

Unfortunately this doesn't work since the li has other ancestors without the style (the ul in this case). The following seems to work;

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

换句话说,选择所有不具有祖先的所有li元素,这些祖先要么具有类foo,要么具有其自身的祖先,而其祖先具有类foo.也许这是使用选择器的最佳/唯一方法,但是对于:not选择器的重复,我并不感到兴奋.还有更好的主意吗?

In other words, select all li elements that have no ancestor that either has class foo or has an ancestor of its own with class foo. Perhaps this is the best/only way to do it with a selector, but I'm not thrilled about the repetition of the :not selector. Any better ideas out there?

小提琴

推荐答案

您可以这样做

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

http://jsfiddle.net/y7s54/

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

http://jsfiddle.net/QpCYY/

选择所有不具有foo类祖先的li'

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

这篇关于选择元素,除非它具有仅使用选择器的给定类的祖先的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆