【问题标题】:How to get all elements which possibly have ancestors and all their ancestors are without a specified class?如何获取所有可能有祖先的元素并且它们的所有祖先都没有指定的类?
【发布时间】:2016-02-25 10:05:22
【问题描述】:

我的 HTML 的一部分与下面的相似,我必须只选择没有任何祖先的元素具有指定的类。我从事的项目非常大,我认为我不应该在这里发布所有代码,我认为这超出了 StackOverflow 的目的。

我想要的是按所有祖先过滤元素,而不仅仅是他们的父母。我试过这个:

// This colors two of the <span> elements instead of one. It colors the ".a > .b" <span> and this behavior seems wrong to me.
$(":not(.a) .b:not(.a)").css("color", "red");

// This call only colors the border of the ".b" <span> which, I think, is the correct behavior and should be the behavior of the call above.
$(":not(.a) > .b:not(.a)").css("border-color", "blue");
span {
    border: 0.1rem solid gray;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="a">
  <span class="b">.a > .b</span> <!-- Why does this <span> element become red? -->
  <span class="a b">.a > .a.b</span>
</div>
<div>
  <span class="b">.b</span>
  <span class="a b">.a.b</span>
</div>

我已将上面的代码放在this JSFiddle 中。我已经使用没有 jQuery 的 document.querySelectorAll 函数测试了这两个选择器,并且行为是相同的。

非常感谢! :-)

【问题讨论】:

  • 如果你定义了你想要做什么,而不是解释这个 XY 问题,你的问题会更好。
  • @RoryMcCrossan,我已经更新了这个问题。我希望现在更好。

标签: javascript jquery html jquery-selectors css-selectors


【解决方案1】:

你的意思是选择.b元素

  • 不是.a,并且
  • 没有任何祖先.a

那么这只适用于 jQuery (learn more):

$(".b:not(.a, .a *)")

如果您需要在 CSS 中执行此操作,您可以使用带有上述选择器的 jQuery 添加一个类,或者使用覆盖:

.b {
  /* Style all .b elements */
}

.a .b, .a.b {
  /* Override the previous rule */
}

【讨论】:

    【解决方案2】:
    :not(.a) .b:not(.a)
    

    选择所有具有 b 类但没有 a 类的元素,这些元素具有 任何祖先 没有类 a,例如&lt;body&gt; & &lt;html&gt;

    :not(.a) > .b:not(.a)
    

    选择所有具有类 b、没有类 a、没有 直接父项 的元素类a

    【讨论】:

    • 感谢您的回答!它解释了这种行为。您知道如何更改选择器,以便它选择所有具有类b 但没有类a 的元素,即具有所有祖先 没有类a?有可能吗?
    • @silviubogan 不确定你的意思。看起来你的第二个版本(使用 &gt; 的那个)是你想要的,不是吗?
    • @BoltClock 给了我我正在寻找的答案,我测试了他的选择器并且它有效。不管怎样,谢谢你! :-)
    猜你喜欢
    • 2011-07-23
    • 2019-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-10
    • 2015-10-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多