使用jQuery判断子元素含selected类时返回true,为何代码始终返回false?
Hey there! Let's figure out why your code is returning false and get it fixed right away.
Why $("#media").hasClass('.selected') doesn't work
You've got two key issues here:
- Wrong parameter format for
hasClass(): This method expects just the class name without the leading.. SohasClass('selected')is the correct syntax, nothasClass('.selected'). But even if you fix that, it still won't work for your case—here's why: hasClass()checks the element itself, not its children: ThehasClass()method only looks at the classes applied directly to the element you're calling it on. Your#mediadiv doesn't have theselectedclass—those are on its child<img>elements. That's why it's always returning false.
Fixes to check if children have the selected class
Here are a few solid ways to achieve your goal:
1. Use find() with length
Search for elements with the selected class inside #media, then check if any exist by looking at the result length:
// Full version if ($("#media").find('.selected').length > 0) { return true; } else { return false; } // Shortened, cleaner version return $("#media").find('.selected').length > 0;
2. Use jQuery's has() method
The has() method filters parent elements that contain a specific child. We can check if the filtered result exists:
return $("#media").has('.selected').length > 0;
3. Use the :has() selector directly
You can also bake the check right into your initial selector:
return $("#media:has(.selected)").length > 0;
Bonus: More targeted check
Since your selected images are inside #table-pane (a direct child of #media), you could make the query even more precise:
return $("#table-pane .selected").length > 0;
内容的提问来源于stack exchange,提问作者Yavuz Selim Özmen
相关产品推荐
相关产品推荐

