如何判断设置<li>为display:none后<ul>元素是否为空?
判断隐藏后的
- 是否"为空"的解决方案
注意:
display: none;仅会让- 视觉隐藏,元素仍存在于DOM结构中,所以直接通过
ul.children.length判断的结果依然是不为空。 若需求是判断视觉上无可见
- ,可采用两种方案:
- 检查
- 的计算样式,统计可见元素数量:
const targetUl = document.querySelector('ul'); const visibleItems = Array.from(targetUl.children).filter(item => { const style = window.getComputedStyle(item); return style.display !== 'none'; }); const isVisuallyEmpty = visibleItems.length === 0; - 给隐藏的
- 添加专属类名,通过类名筛选可见元素:
.visually-hidden { display: none; }const targetUl = document.querySelector('ul'); const visibleItems = targetUl.querySelectorAll('li:not(.visually-hidden)'); const isVisuallyEmpty = visibleItems.length === 0;
若需要让
- 在DOM层面为空,则不能仅用
- 元素:
const targetUl = document.querySelector('ul'); // 移除所有隐藏的li Array.from(targetUl.children).forEach(item => { const style = window.getComputedStyle(item); if (style.display === 'none') { item.remove(); } }); // 此时可判断DOM是否为空 const isDomEmpty = targetUl.children.length === 0;
display: none,需直接移除内容的提问来源于stack exchange,提问作者Hamude Salman
- 元素:
相关产品推荐
相关产品推荐

