如何使用JQuery隐藏父元素下除指定元素外的所有元素?
解决仅保留指定data-index元素的问题
你的选择器逻辑本身是正确的,代码无效大概率是执行时机不对——DOM还没加载完成就运行了jQuery代码,导致选择器找不到目标元素。以下是几种可行的解决方式:
方式一:用DOM就绪回调包裹代码
确保代码在页面DOM完全加载后再执行:$(document).ready(function() { $('.fieldset-wrapper div:not([data-index="one"]):not([data-index="three"])').hide(); });也可以用更简洁的简写形式:
$(function() { $('.fieldset-wrapper div:not([data-index="one"]):not([data-index="three"])').hide(); });方式二:调整script标签位置
把你的jQuery代码脚本标签移到HTML结构的末尾(</body>标签之前),此时DOM已经加载完成,无需就绪回调:<div class="fieldset-wrapper"> <div data-index="one">one</div> <div data-index="two">two</div> <div data-index="three">three</div> <div data-index="four">four</div> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> <script> $('.fieldset-wrapper div:not([data-index="one"]):not([data-index="three"])').hide(); </script>方式三:简化选择器写法
用not()方法替代链式:not选择器,逻辑更清晰:$(function() { $('.fieldset-wrapper div').not('[data-index="one"], [data-index="three"]').hide(); });
如果你的需求是移除而非隐藏不符合条件的元素,只需把代码中的hide()替换成remove()即可。
内容的提问来源于stack exchange,提问作者Aniruddha Ray
相关产品推荐
相关产品推荐

