1

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
  • 37,241
  • 25
  • 195
  • 267
Daniel Santos
  • 14,328
  • 21
  • 91
  • 174

2 Answers2

4

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
  • 331,213
  • 40
  • 305
  • 339
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