Kees C. Bakker
Kees C. Bakker

Reputation: 33391

Wanted: jQuery selector with variable part in the middle

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.

Upvotes: 8

Views: 1540

Answers (2)

Tatu Ulmanen
Tatu Ulmanen

Reputation: 124778

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.

Upvotes: 14

lonesomeday
lonesomeday

Reputation: 237905

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".

Upvotes: 7

Related Questions