0

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?

Cœur
  • 34,719
  • 24
  • 185
  • 251
Daniel Santos
  • 11,626
  • 18
  • 77
  • 158

2 Answers2

3

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

$('div[id^="prefix_"][id$="_sufix"]');

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)');
Rory McCrossan
  • 319,460
  • 37
  • 290
  • 318
0
$('div[id^="prefix"]').filter(
    function(){
        return this.id.match('suffix');
    }).css('background-color','#0f0');

jQuery Select # id with word as prefix and counter as suffix

Community
  • 1
  • 1
Ben Bodan
  • 81
  • 3