tags:

views:

46

answers:

5

I have a few divs created dynamically in Javascript.I was wondering if it is possible to style them all at once.

#somediv {
    background-color: #F2F5FC;
    border-style:solid;
    border-bottom:thin dotted #33ccff;
}

#somediv2 {
    background-color: #F2F5FC;
    border-style:solid;
    border-bottom:thin dotted #33ccff;
}

...and so on (this can be even 50 divs)

I would like to change this to something like:

 #somediv* {
    background-color: #F2F5FC;
    border-style:solid;
    border-bottom:thin dotted #33ccff;
}
A: 
#somediv, #somediv2 {
    background-color: #F2F5FC;
    border-style:solid;
    border-bottom:thin dotted #33ccff;
}
rpiontek
Yeah, but what if I have 50 divs?
Vafello
Then as others have suggested, use a class, or type a lot of commas.
rpiontek
@Vafello, then you can use -depending on your audience- CSS's `starts-with` selector (see my answer), although a common class would be so much more functional and easy to use.
David Thomas
+4  A: 

Give your dynamically created div's a class, then style the class. Or maybe if you're inserting your new divs into a container you could just select based on that:

<div id='stuff_goes_here'>
  <!-- ... dynamic divs will go here ... -->
</div>

and then:

#stuff_goes_here div {
  /* ... styles ... */
}
thenduks
How come I didn't think of this. Genius:)
Vafello
+4  A: 

If they are going to be styled exactly the same, use a class, look here for the difference:

.divClass {
    background-color: #F2F5FC;
    border-style:solid;
    border-bottom:thin dotted #33ccff;
}

Then your divs are like this:

<div id="somediv" class="divClass"></div>
<div id="somediv2" class="divClass"></div>

Just edit your script to include the class attribute, by far the easiest solution...and this is exactly what classes are for :)

Nick Craver
A: 

I'd personally suggest using a class, since that's what they're for; you can, though, do it as you want to:

div[id^=somediv]
{
/* css styles */
}

Using the CSS starts-with selector (http://reference.sitepoint.com/css/css3attributeselectors), although it relies on CSS 3 (I think) implementation in your user/audience.

David Thomas
+1  A: 

This is what the class attribute was created to handle. Give all of your divs the same class and you can say something like:

.divclass {
    background-color: #F2F5FC;
    border-style:solid;
    border-bottom:thin dotted #33ccff;
}

But if you REALLY need to do what you asked, you can use a new form of selector. The following will match all IDs that start with 'somediv', but this won't work on older browsers:

[id^=somediv] {
    background-color: #F2F5FC;
    border-style:solid;
    border-bottom:thin dotted #33ccff;
}
swestrup