如何获得嵌套元素?

时间:2017-03-21 10:55:28

标签: jquery

我有一些DOM结构:

<div class="model-A">
    <div class="some1">
        <div class="sub1"></div>
        <div class="model-B">
            <div class="some2">
                <div class="sub2"></div>
            </div>
            <div class="model-C">
                <div class="some3">
                    <div class="sub3"></div>
                    <div class="model-B">
                        <div class="some4"></div>
                        <div class="sub4"></div>
                    </div>
                </div>
            </div>
            <div class="some2">
                <div class="sub2"></div>
            </div>
        </div>
    </div>
</div>

如何获得具有&#39;模型-B&#39;的div的所有元素?上课,但不是其他模特 - *&#39;孩子的?例如,结果必须是包含元素:

从第一个&#39;模型-B&#39;

<div class="some2">
   <div class="sub2"></div>
</div>
<div class="some2">
   <div class="sub2"></div>
</div>

从第二个&#39;模型-B&#39;

<div class="some4"></div>
<div class="sub4"></div>

1 个答案:

答案 0 :(得分:1)

您可以使用:has选择器执行此操作,如下所示:

$('.model-B>div').not(':has([class^=model])')

演示:

&#13;
&#13;
$('.model-B>div').not(':has([class^=model])').each(function () {
    console.log(this.outerHTML);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="model-A">
    <div class="some1">
        <div class="sub1"></div>
        <div class="model-B">
            <div class="some2">
                <div class="sub2"></div>
            </div>
            <div class="model-C">
                <div class="some3">
                    <div class="sub3"></div>
                    <div class="model-B">
                        <div class="some4"></div>
                        <div class="sub4"></div>
                    </div>
                </div>
            </div>
            <div class="some2">
                <div class="sub2"></div>
            </div>
        </div>
    </div>
</div>
&#13;
&#13;
&#13;