Consider the following HTML:
<div id="Kees_1_test">test 1</div>
<div id="Kees_12_test">test 2</div>
<div id="Kees_335_test">test 3</div>
I would like a selector that selects the divs that look like $('div[id=Kees_{any number}_test]')
. How can I achieve this?
Note: the ID's are generated by Asp.Net.
Yes, it is possible to pass a variable into a jQuery attribute-contains selector. The [attribute*=value] selector is used to select each element with a specific attribute and a value containing a string.
$ is another, which is just an alias to jQuery . $$ is not provided by jQuery. It's provided by other libraries, such as Mootools or Prototype.
ID and Element selector are the fastest selectors in jQuery.
Try this:
$('div[id^=Kees_][id$=_test]')
That selector selects all elements that have ids that start with Kees_
and end with _test
.
As lonesomeday suggested, you can use .filter()
to ensure that the middle part contains only numbers. You can combine .filter()
with the example above:
$('div[id^=Kees_][id$=_test]').filter(function() {
return /^Kees_\d+_test$/.test(this.id);
});
That should about as good as it gets. Note that I added ^$
to the regex, this will return false on id's such as Kees_123_test_foo
also but Kees_123_test
passes.
The best solution would be to give all your divs a class and use a class selector:
<div id="Kees_1_test" class="Kees_test">test 1</div>
<div id="Kees_12_test" class="Kees_test">test 2</div>
<div id="Kees_335_test" class="Kees_test">test 3</div>
Selector:
$('div.Kees_test');
If this isn't possible, the most legible way would be to use filter
:
$('div[id^="Kees_"]').filter(function() {
return /Kees_\d+_test/.test(this.id);
});
The \d+
means "select one or more numbers".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With