Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 368
Kees C. Bakker Avatar asked May 10 '11 11:05

Kees C. Bakker


People also ask

Can I put variable in jQuery selector?

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.

What is $$ in jQuery?

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

Which jQuery selector is fastest?

ID and Element selector are the fastest selectors in jQuery.


2 Answers

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.

like image 82
Tatu Ulmanen Avatar answered Nov 13 '22 04:11

Tatu Ulmanen


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

like image 43
lonesomeday Avatar answered Nov 13 '22 06:11

lonesomeday