Reputation: 359
I have a bunch of divs on a page (bg_1, bg_5, bg_112 etc.) that I'd like to assign the style 'display:inline-block'.
However, I have other divs called bg_1_log, bg_5_log, bg_112_log etc..) that I do not want to assign this style to.
I have tried:
$('[id^=bg_]').attr('style','display:inline-block');
This works, but of course that assigns the style to all divs that start with 'bg_', including bg_112_log...
How can I "assign a style to all divs that are just bg_+number?
I'm using jQuery so either that or JS would be fine.
Upvotes: 0
Views: 53
Reputation: 85573
You could use the selector using not and attribute contains selector like:
$('[id^=bg_]').not('[id*=_log]')
Or, you can also use regex as @zfrisch suggested but here's an improved version (Selector not only limitted to div):
$('*').filter(function() { return this.id.match(/bg_\d$/) })
Or, even like:
$('*').attr('id').match(/bg_\d$/)
Upvotes: 2
Reputation: 1
If you don't want to select the elements whose id ends with _log
then you can use following code:
$('[id^=bg_]').not('[id$=_log]').attr('style','display:inline-block');
Upvotes: 0
Reputation: 8670
You can use JQuery's .filter
method
$('div')
.filter(function() {
return this.id.match(/bg_\d$/);
})
.css("backgroundColor", "green");
div:after {
content: "test";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="bg_1"></div>
<div id="bg_2"></div>
<div id="bg_3"></div>
<div id="bg_4"></div>
<div id="bg_5"></div>
<div id="bg_6"></div>
<div id="bg_1_log"></div>
<div id="bg_2_log"></div>
<div id="bg_3_log"></div>
<div id="bg_4_log"></div>
<div id="bg_5_log"></div>
<div id="bg_6_log"></div>
Or as another answer pointed out .not
Upvotes: 0