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?
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:
$('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)');
$('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