You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何判断设置<li>为display:none后<ul>元素是否为空?

判断隐藏
  • 后的
      是否"为空"的解决方案
    • 注意:display: none;仅会让

    • 视觉隐藏,元素仍存在于DOM结构中,所以直接通过ul.children.length判断的结果依然是不为空。

    • 若需求是判断视觉上无可见

    • ,可采用两种方案:

      1. 检查
      2. 的计算样式,统计可见元素数量:
        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;
        
      3. 给隐藏的
      4. 添加专属类名,通过类名筛选可见元素:
        .visually-hidden { display: none; }
        
        const targetUl = document.querySelector('ul');
        const visibleItems = targetUl.querySelectorAll('li:not(.visually-hidden)');
        const isVisuallyEmpty = visibleItems.length === 0;
        
    • 若需要让

        在DOM层面为空,则不能仅用display: none,需直接移除
      • 元素:

        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;
        

      内容的提问来源于stack exchange,提问作者Hamude Salman

    相关产品推荐
    方舟 Agent Plan

    超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

    最近更新时间:2026.08.07 09:05:34