如何在多个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:
- The selector inside
find()was off:ul.sub-tab > li.super-activewould look for aul.sub-tabinside your targetul.sub-tab, which isn't what you want. You need to check for direct childlis of the currentul.sub-tab. - A jQuery object always evaluates to
truein anifstatement, 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

