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

JavaScript点击按钮查找含指定字符串的最近父类元素问题

Fixing the Closest Parent Element Selection Issue

Let's break down what's wrong with your current code and fix it to get the desired behavior.

What's Wrong with the Original Code?

Your selector syntax is incorrect. You tried combining a CSS attribute selector with jQuery's :contains() filter in an invalid way:

$(this).closest('div[class*=:contains(feature)]')

The [class*=...] attribute selector expects a string value to match within the class attribute, but you incorrectly nested the :contains() filter inside it. jQuery can't parse this invalid selector, so it fails to find the target parent element.

Solutions Based on Your Exact Need

You mentioned you want to find the closest parent element containing a specified string—let's cover two common scenarios here:

Scenario 1: Target Parent with a Class Containing "feature"

If your goal is to find the nearest parent <div> that has "feature" in its class attribute (like your outermost <div class="feature I am the best">), use a valid attribute contains selector or a direct class selector (more efficient):

Option 1: Attribute Contains Selector
$('.clickme').on('mouseup', function(event) {
  // Matches any div with "feature" anywhere in its class attribute
  var description = $(this).closest('div[class*="feature"]').attr('class');
  console.log("Description " + description);
});
Option 2: Direct Class Selector (Recommended)

If you specifically want the parent with the feature class (not just any class containing "feature"), this is more precise and faster:

$('.clickme').on('mouseup', function(event) {
  // Matches the nearest parent div with the "feature" class
  var description = $(this).closest('.feature').attr('class');
  console.log("Description " + description);
});

Scenario 2: Target Parent with Text Containing a Specific String

If you need to find the nearest parent <div> that contains a specific text string (e.g., "I am the best"), use the :contains() filter correctly (note: it's case-sensitive):

$('.clickme').on('mouseup', function(event) {
  // Matches the nearest parent div containing the text "I am the best"
  var description = $(this).closest('div:contains("I am the best")').attr('class');
  console.log("Description " + description);
});

Key Takeaways

  • Always use valid selector syntax: don't nest filters like :contains() inside attribute selectors.
  • Prefer class selectors (.feature) over attribute contains selectors when targeting elements with a specific class—it's more efficient and avoids accidental matches (e.g., a class named "featured" would be matched by [class*="feature"] but not by .feature).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 12:17:32