61

I have <div id='mydiv'> and I need to select all pre and div elements that are children of #mydiv.

I could do it this way:

div#mydiv > pre, div#mydiv > div

but, can it be done so that #mydiv is referenced only once?

div#mydiv > pre, div

will select all divs on the page regardless if they're children of #mydiv, so the comma isn't a way to do it. Maybe there's another kind of syntax I don't know about?

the Tin Man
  • 155,156
  • 41
  • 207
  • 295
rsk82
  • 26,257
  • 48
  • 141
  • 229

4 Answers4

59

You'll have to reference #mydiv twice...

#mydiv > pre, #mydiv > div

I removed the extraneous div element selector as the ID is specific enough.

BoltClock
  • 665,005
  • 155
  • 1,345
  • 1,328
Fosco
  • 37,365
  • 6
  • 84
  • 100
  • 1
    agree with removing the div qualifier, but I don't see jQuery mentioned in the question or tags - maybe just write it as CSS? – clairesuzy May 31 '11 at 19:49
9

As far as I know, there is no shorthand for selector grouping.

See "Selector Grouping".

Although, with LESS, it is possible in the "Nested Rules" section.

the Tin Man
  • 155,156
  • 41
  • 207
  • 295
Jawad
  • 8,408
  • 10
  • 38
  • 42
7

You can actually group selectors with :is().

So in your case you would use it like this:

div#mydiv > :is(pre, div) {
     // CSS
}

Here is the documentation https://developer.mozilla.org/en-US/docs/Web/CSS/:is

7

The only way to reference the id only once is to use it with the * selector:

#mydiv > * {

which will apply to all elements that are children of that div.

Depending on what styles you plan to apply this might be workable (I typically use this to zero-out margins, padding and border styles), but it's still probably best to do it the first way because it makes it easier to make exceptions/changes later down the road.

the Tin Man
  • 155,156
  • 41
  • 207
  • 295
East of Nowhere
  • 1,316
  • 4
  • 18
  • 27