eomeroff
eomeroff

Reputation: 9915

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>
    <div id="Some_id_3"></div>

How can I do that? thanks.

Upvotes: 3

Views: 6277

Answers (4)

Borja
Borja

Reputation: 3610

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");
});

Upvotes: 0

themerlinproject
themerlinproject

Reputation: 3582

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 }

Upvotes: 0

Rion Williams
Rion Williams

Reputation: 76547

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

Upvotes: 8

Quentin
Quentin

Reputation: 943547

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;
}

Upvotes: 0

Related Questions