【问题标题】:Filter parent div with only one type of child过滤只有一种子类型的父 div
【发布时间】:2018-04-08 18:50:43
【问题描述】:

我需要搜索具有“test”类的 div,该 div 在隐藏的子节点或子节点中只有按钮类型。这是我必须过滤的 HTML。

<div class="test">
  <div>
    <button> <span>Button 1</span></button>
    </div>
</div>
<div class="test">
  <div>
    <button> <span>Button 2</span></button>
    <div>Div 1</div>
    <div>Div 2</div>
    <div>Div 3</div>
  </div>
</div>

基于this jQuery 选择器我一直在测试这个fiddle 但它返回我这个错误:

我一直期待返回的 div 是第一个 div。 那么我怎样才能达到呢?

【问题讨论】:

  • 欢迎来到 Stack Overflow!您问题的全部内容必须在您的问题中in,而不仅仅是链接。链接腐烂,使问题及其答案对未来的人们毫无用处,人们不应该离开现场来帮助你。将minimal reproducible example 放入 问题中,最好使用 Stack Snippets(&lt;&gt; 工具栏按钮)使其可运行。更多:How do I ask a good question?

标签: javascript jquery html jquery-selectors


【解决方案1】:

这个应该可以解决问题。

var TestDivs = $(document).find(".test div button");
alert(TestDivs[0].innerHTML);

【讨论】:

    【解决方案2】:

    您可以比较子 div 元素和其中包含按钮元素的子 div 元素的长度:

    var notButtonDivs = $('.test').filter(function(){
       return $(this).find('div').length == $(this).find('div:has(button)').length
    })
    

    Working Demo

    【讨论】:

      猜你喜欢
      • 2021-11-14
      • 1970-01-01
      • 1970-01-01
      • 2019-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-28
      • 1970-01-01
      相关资源
      最近更新 更多