【问题标题】:How to select the closest descendant using jquery or selector?如何使用 jquery 或选择器选择最近的后代?
【发布时间】:2021-08-03 23:00:16
【问题描述】:

我想获取与 class="foo" 匹配的节点的后代。
问题是:我不知道这个后代会有多深。
我知道我可以使用 >
或者如果我知道它有多深,我可以使用多个 > > > >
我可以只使用 class="foo" 但我会得到与 class="foo" 匹配的目标的后代。

是 div.class="foo":first-child 解决方案吗?

div id="im_here"
  div id="child"
    ......
         div class="foo"              <= I want this
           ......
                div class="foo"       <= not that
                ......
                      div class="foo" <= not that
                      ......

【问题讨论】:

  • 我认为单靠 CSS 不会做到这一点。你可能需要 JavaScript
  • 在jquery中你可以使用$(".foo:first")

标签: jquery jquery-selectors


【解决方案1】:

您可以将jQuery's :first selector.find() 结合使用:

$('#im_here').find('.foo:first')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-02
    • 2013-06-30
    • 2017-09-17
    • 1970-01-01
    • 1970-01-01
    • 2010-09-08
    • 1970-01-01
    相关资源
    最近更新 更多