JQuery - 如何选择包含特定属性的所有子项,但排除所有深层后代?



选择包含特定属性("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]");

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

可以使用>指定直接子级。

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>

最新更新