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

如何在多个ul集合中找到含指定li的ul并为其添加类

Hey there! Let's get this sorted out for you. You're trying to find the ul.sub-tab that has a direct child li.super-active, then add a class to that specific ul—right?

What went wrong with your original code

Your initial approach had two key issues:

  1. The selector inside find() was off: ul.sub-tab > li.super-active would look for a ul.sub-tab inside your target ul.sub-tab, which isn't what you want. You need to check for direct child lis of the current ul.sub-tab.
  2. A jQuery object always evaluates to true in an if statement, even if it doesn't match any elements. So your condition would always run, regardless of whether the target li exists.

Simple, working solutions

Here are two clean ways to achieve what you need:

1. Use the :has() selector

This lets you directly target the ul.sub-tab that contains a direct child li.super-active:

// Add your desired class to the matching ul
$('ul.sub-tab:has(> li.super-active)').addClass('highlighted-tab-group');

The > ensures we only look at direct children of the ul.sub-tab, so you won't accidentally match nested uls further down the tree.

2. Use the .has() method

This works exactly like the selector above, but uses jQuery's method syntax instead:

$('ul.sub-tab').has('> li.super-active').addClass('highlighted-tab-group');

Bonus: Explicit check with .filter()

If you prefer a more explicit approach (maybe for readability), you can use .filter() to narrow down the uls:

const targetUls = $('ul.sub-tab').filter(function() {
  // Check if this ul has a direct child li with the super-active class
  return $(this).children('li.super-active').length > 0;
});

targetUls.addClass('highlighted-tab-group');

All these methods will correctly find the exact ul.sub-tab you're targeting and apply your class to it.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:05:33