Reputation: 2269
<span id="aaa_1_bbb">aaa</span>
<span id="aaa_2_bbb">aaa</span>
<span id="aaa_3_bbb">aaa</span>
<span id="aaa_4_bbb">aaa</span>
<span id="aaa_5_bbb">aaa</span>
<span id="aaa_6_bbb">aaa</span>
<span id="bbb_1_bbb">aaa</span>
<span id="ccc_1_bbb">aaa</span>
<span id="ddd_1_bbb">aaa</span>
<span id="aaa_1_xxx">aaa</span>
$('span[id="aaa_*_bbb"]').css('background-color', 'red');
how must i modify this jQuery? i would like that add css (background-color:red) only for aaa_*_bbb ID. * = numbers
LIVE: http://jsfiddle.net/HB3xf/2/
Upvotes: 1
Views: 748
Reputation: 437504
As the HTML stands, you can use a combination of the attribute starts with and attribute ends with selectors:
$('span[id^="aaa_"]').filter('[id$="_bbb"]').css('background-color', 'red');
However, if the HTML is under your control you should consider adding a class
to these elements, or an id
or class
to their parent, so that you can select them in a more straightforward manner.
Upvotes: 8
Reputation: 8091
I think you need to use this: http://james.padolsey.com/javascript/regex-selector-for-jquery/
Upvotes: 1
Reputation: 9487
You could use .filter
$('span').filter(function () { return /aaa_\d+_bbb/.test(this.id); }).css('background-color', 'red');
Upvotes: 2
Reputation: 4785
The better option would be to set a specific class on those elements, like
<span id="aaa_1_bbb" class="aaabbb">aaa</span>
<span id="aaa_2_bbb" class="aaabbb">aaa</span>
<span id="aaa_3_bbb" class="aaabbb">aaa</span>
<span id="aaa_4_bbb" class="aaabbb">aaa</span>
<span id="aaa_5_bbb" class="aaabbb">aaa</span>
<span id="aaa_6_bbb" class="aaabbb">aaa</span>
<span id="bbb_1_bbb">aaa</span>
<span id="ccc_1_bbb">aaa</span>
<span id="ddd_1_bbb">aaa</span>
Then, you can just do $('span.aaabbb').css('background-color', 'red');
Upvotes: 0
Reputation: 7223
You could do something like:
$('span').each(function() {
var span_id = $(this).attr('id');
if (span_id.substring(0, 3) == "aaa" && span_id.substring(span_id.length - 3, span_id.length) == "bbb") {
$(this).css('background-color', 'red');
}
});
It takes every span element and checks whether or not the first 3 characters are "aaa" and the last 3 are "bbb" and assigns the CSS if this is the case.
Upvotes: 1