Daniel Santos Daniel Santos - 10 months ago 38
HTML Question

How select elements using jquery based on its id sufix and prefix?

I would like to select elements with this id pattern:

<div id="prefix_0_sufix"></div>
<div id="prefix_1_sufix"></div>
<div id="prefix_2_sufix"></div>
... and so on ...

How can I get those elements with jquery selectors?


You can use the 'attribute starts with' and 'attribute ends with' selectors:


You should note however, that it would be much more semantic and faster to use a common class. If you need to store data with the element, use a data attribute on the element instead.

<div class="foo" data-bar="0"></div>
<div class="foo" data-bar="1"></div>
<div class="foo" data-bar="2"></div>

From there you can use filter() to get a specific element from the set:

var $secondDiv = $('.foo').filter(function() {
    return $(this).data('bar') == 1;

Or if the elements are ordinal, you could just use their index and not add the data attribute at all:

var $secondDiv = $('.foo:eq(1)');