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

如何选择内部不含<ul>的<li>元素?CSS选择器失效求助

Fixing the .level1:not(:has(ul)) CSS Selector Issue

Hey there! I see you're trying to target <li class="level1"> elements that don’t contain a nested <ul>, but your selector isn’t working. Let’s break this down and get it sorted out.

1. The Likely Culprit: Browser Support for :has()

Your selector .level1:not(:has(ul)) is actually syntactically correct for what you want to do. The problem is probably browser compatibility.

The :has() pseudo-class is part of CSS Selectors Level 4, and while modern browsers support it now, there are a few caveats:

  • Chrome, Edge, and Opera have supported it since version 105+
  • Firefox requires version 121+ (earlier versions needed manually enabling the layout.css.has-selector.enabled flag in about:config)
  • Safari supports it from version 15.4+

If you’re testing on an older browser or haven’t enabled the flag in Firefox, that’s why your selector isn’t taking effect.

2. Verify Your Selector (and Make It More Precise)

Just to be thorough, you can make your selector more specific to target direct child <ul> elements (which matches your HTML structure) using the child combinator:

.level1:not(:has(> ul)) {
  background: red;
}

This does the same thing as your original selector but explicitly checks for a direct child <ul>, which can avoid accidental matches if there are nested lists deeper down. But again, this only works if your browser supports :has().

3. Fallback Solution for Older Browsers

If you need to support browsers that don’t have :has() support, use a quick JavaScript workaround to add a custom class to the elements you want to target:

First, add this JavaScript (place it at the end of your <body> or wrap it in a DOMContentLoaded listener):

// Wait for the DOM to fully load
document.addEventListener('DOMContentLoaded', () => {
  // Grab all .level1 list items
  document.querySelectorAll('.level1').forEach(li => {
    // Check if the li doesn't contain any ul elements
    if (!li.querySelector('ul')) {
      // Add a custom class to mark it
      li.classList.add('no-submenu');
    }
  });
});

Then use this CSS to style those elements:

.level1.no-submenu {
  background: red;
}

Testing Your HTML Structure

Just to confirm, your HTML structure is perfectly valid for this use case:

<ul>
  <li class="level1">Link1</li>
  <li class="level1">Link2
    <ul>
      <li>Link2</li>
    </ul>
  </li>
</ul>

With the working selector or the JS fallback, "Link1" should get the red background as expected.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:30:42