【问题标题】:Select only parent nodes that match the selector仅选择与选择器匹配的父节点
【发布时间】:2019-04-18 22:41:33
【问题描述】:

我正在尝试获取包含.export 类的所有父节点,任何具有.export 类的父节点的子节点都应从选择中跳过。

节点可以出现在树中的任何位置,但需要任何没有具有相同类的父节点的节点。

具有以下 HTML 结构:

<div class="export"> <!-- Select this one -->
    <div class="export"> <!-- SKIP this one -->
        <!-- Content -->
    </div>
</div>
<div class="export"> <!-- Select this one -->
    <!-- Some more content -->
</div>

【问题讨论】:

    标签: javascript jquery html dom jquery-selectors


    【解决方案1】:

    您可以使用 jQuery .not() 方法获取它们,例如:

    console.log($(".export").not(".export .export").length);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="export">
      <!-- Select this one -->
      <div class="export">
        <!-- SKIP this one -->
        <!-- Content -->
      </div>
    </div>
    <div class="export">
      <!-- Select this one -->
      <!-- Some more content -->
    </div>

    【讨论】:

      【解决方案2】:

      您可以使用:not() 查询选择器跳过与选择器中的查询匹配的查询。

      $('.export:not(.export >)')
      

      【讨论】:

      • jQuery 充满了惊喜。这似乎没有记录在案,但它确实有效。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-23
      • 1970-01-01
      • 2017-04-14
      • 1970-01-01
      • 2015-10-10
      • 2011-05-23
      相关资源
      最近更新 更多