此问题已经在这里有了答案:
选择包含特定属性(“ 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>
$("#main_span").children("[attribute_nm]");
您可以使用>来指定直接子代。
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>