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

使用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:

  1. Wrong parameter format for hasClass(): This method expects just the class name without the leading .. So hasClass('selected') is the correct syntax, not hasClass('.selected'). But even if you fix that, it still won't work for your case—here's why:
  2. hasClass() checks the element itself, not its children: The hasClass() method only looks at the classes applied directly to the element you're calling it on. Your #media div doesn't have the selected class—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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:47:48