4

I read this tutorial on using regular expressions with CSS selectors and am trying to extrapolate: Is there a CSS shorthand to do the following? I want to select all div's with class of "foo" that have either an additional class of "a", "b", "c", or "d".

    .foo.a,
    .foo.b,
    .foo.c,
    .foo.d {
       /* stuff */
    }

something like:

.foo[class~='a','b','c','d'] {} ?

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
HandiworkNYC.com
  • 10,914
  • 25
  • 92
  • 154

3 Answers3

7

It's not possible, currently (with the Selectors 3 recommendation). There isn't a full-fledged regex grammar for CSS, nor is there a way to crunch down parts of multiple selector lists.

Selectors 4 proposes a new :matches() pseudo-class based on Mozilla's original :any() implementation (see this answer for a bit of history):

.foo:matches(.a, .b, .c, .d)

Of course, don't expect browser support for this yet. I might even forget to update this answer when that time comes but... we'll see.

Community
  • 1
  • 1
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
0

Maybe .foo[class~='a'][class~='b'][class~='c'][class~='d'] ?

Dejan Marjanović
  • 19,244
  • 7
  • 52
  • 66
0

No, your first way of writing it is the correct way. You can only search for one match at time with an attribute selector so the closest thing that's a mixture of your two methods is:

.foo[class~="a"],
.foo[class~="b"],
.foo[class~="c"],
.foo[class~="d"] {
   /* stuff */
}

Which really isn't shorthand or anything :P The best way to select by classes is just the ordinary way with a .className. Attribute selectors are only really helpful for selecting other attributes, or if you have a class that begins with a certain word and are using css3. For example you could use something like:

.foo[class^="mah-class"]{ }

Which would match mah-class-a mah-class-b mah-classAHHH... etc

Paul
  • 139,544
  • 27
  • 275
  • 264
  • You should probably be using `class~=` in your 2nd example. Using `class^=` means that the selector is picky about the order of CSS classes, so in the following HTML it would match the first, but not the 2nd. `

    hi

    there

    `
    – metavida Aug 01 '11 at 01:43