jQuery Select multiple div elements by ID using startswith common string
I want to set the same css for all of these div elements:
<div id="Some_id_1"></div>
<div id="Some_id_2"></div>
<di开发者_如何学编程v id="Some_id_3"></div>
How can I do that? thanks.
You should be able to use the jQuery Attribute Starts With Selector:
Usage:
$('[attribute^="value"]')
Example, fitting your needs:
$('div[id^="Some_id_"]').each(function(){
$(this).css('property','value');
});
This would be useful for setting these properties dynamically, however if you are just setting them in a static sense, I would recommend just applying a class="your_class"
to all of your divs.
A Working Demo can be found here :
Demo
Make them all members of a class, then use a class selector.
<div class="some_class" id="Some_id_1"></div>
<div class="some_class" id="Some_id_2"></div>
<div class="some_class" id="Some_id_3"></div>
.some_class {
line-height: 1.1;
}
If possible, give your div
a class:
<div id="Some_id_1" class="newClass"></div>
<div id="Some_id_2" class="newClass"></div>
<div id="Some_id_3" class="newClass"></div>
and then select the class and modify the css using css():
$(".newClass").css("color","red");
...
Not knowing your code, I'll also throw out addClass() which suits some applications better.
$("div").addClass("newClass");
The above example will add a class to ANY div
, so you'll have to play with the selector that makes sense for your project, and then just have some existing css:
.newClass { color: red }
To use the same style to all elements with the same id put it this
.yourClass {
line-height: 1.1;
}
$('[id^="Some_id_"]').each(function(){
$(this).addClass("yourClass");
});
精彩评论