我如何选择所有包含特定属性但不包括所有较深后代的子代? [重复]

问题描述 投票:0回答:2

此问题已经在这里有了答案:

选择包含特定属性(“ attribute_nm”)的所有“子项”,但排除包含相同属性的子项(以此类推)的所有子项。

“实际”情况:

如何调整此查询...

$("#main_span").find("[attribute_nm]");

...仅选择下面指定的项目...

<span id="main_span">

    <span attribute_nm> <!-- Select that PARENT and its contents! -->

        <!-- MORE HTML... -->

        <span attribute_nm> <!-- DO NOT select that CHILD and its contents! -->
        </span>

        <!-- MORE HTML... -->

        <span attribute_nm> <!-- Do not select that child and its contents! -->
        </span>

        <!-- MORE HTML... -->

        <span attribute_nm> <!-- Do not select that child and its contents! -->
        </span>

        <!-- MORE HTML... -->

    </span>

    <span attribute_nm> <!-- Select that PARENT and its contents! -->

        <!-- MORE HTML... -->

        <span attribute_nm> <!-- DO NOT select that CHILD and its contents! -->
        </span>

        <!-- MORE HTML... -->

        <span attribute_nm> <!-- Do not select that child and its contents! -->
        </span>

        <!-- MORE HTML... -->

        <span attribute_nm> <!-- Do not select that child and its contents! -->
        </span>

        <!-- MORE HTML... -->

    </span>

    <!-- MORE HTML... -->

</span>
javascript jquery html dom
2个回答
1
投票
$("#main_span").children("[attribute_nm]");

https://api.jquery.com/children/


0
投票

您可以使用>来指定直接子代。

var elems = $("#main_span").find("> [attribute_nm]")
console.log(elems.length)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span id="main_span">

    <span attribute_nm> <!-- Select that PARENT and its contents! -->

        <!-- MORE HTML... -->

        <span attribute_nm> <!-- DO NOT select that CHILD and its contents! -->
        </span>

        <!-- MORE HTML... -->

        <span attribute_nm> <!-- Do not select that child and its contents! -->
        </span>

        <!-- MORE HTML... -->

        <span attribute_nm> <!-- Do not select that child and its contents! -->
        </span>

        <!-- MORE HTML... -->

    </span>

    <span attribute_nm> <!-- Select that PARENT and its contents! -->

        <!-- MORE HTML... -->

        <span attribute_nm> <!-- DO NOT select that CHILD and its contents! -->
        </span>

        <!-- MORE HTML... -->

        <span attribute_nm> <!-- Do not select that child and its contents! -->
        </span>

        <!-- MORE HTML... -->

        <span attribute_nm> <!-- Do not select that child and its contents! -->
        </span>

        <!-- MORE HTML... -->

    </span>

    <!-- MORE HTML... -->

</span>
© www.soinside.com 2019 - 2024. All rights reserved.