1
<div>
<fieldset id='dynamicTargetId'>
<legend>test</legend>
</fieldset>
</div>

What's the best way using jQuery to get the fieldset that contains the word Target. The Id will be a composite that always contains the word Target.

nem035
  • 34,790
  • 6
  • 87
  • 99
Rod
  • 14,529
  • 31
  • 118
  • 230

2 Answers2

2

Use the attribute contains selector on the id attribute. For example:

$("fieldset[id*='Target']");
Dave
  • 10,748
  • 3
  • 43
  • 54
2

You could use the CSS attribute selectors:

​$("fieldset[id*=Target]")

In general, [att*=str] matches any attribute value that contains str anywhere within it.

Here is an example:

var test = $('fieldset[id*=Target]');
$('#count').text(test.length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<fieldset id='dynamicTargetId'>
<legend>test</legend>
</fieldset>
  <fieldset id='anotherTargetId'>
<legend>test</legend>
</fieldset>
  <fieldset id='TargetId'>
<legend>test</legend>
</fieldset>
</div>
<p>
  Found <span id="count"></span> fieldset elements containing 'Target'
</p>

If you need to match attributes that contain values at a certain position (beginning or end), you can use something like:

[att^=str]     // attribute value starting with str

[att$=str]     // attribute value ends with str

More details about different attribute selectors

Other possible ways of performing the matching you need

Community
  • 1
  • 1
nem035
  • 34,790
  • 6
  • 87
  • 99