4

I'm trying to target an element that could have one of many classes. Isn't there an easier way to write the following example? I haven't been able to find a reference, but it seems there should be a more efficient option.

.myTable1 a, .myTable2 a, .myTable3 a, .myTable4 a
{
    text-decoration: underline;
}
JSW189
  • 6,139
  • 11
  • 41
  • 71
Dmase05
  • 1,049
  • 14
  • 17

4 Answers4

5

Try -

table[class^=myTable] a {
    text-decoration: underline;
}
Zoltan Toth
  • 46,038
  • 11
  • 115
  • 133
  • 1
    This would definitely not be more efficient (performance-wise) than the selector list he has above, though I guess it would be less code. – JasonWyatt Oct 16 '12 at 18:14
  • 1
    @JasonWyatt Agree, but I think the "efficiency" here is not about the actual selector performance, but an *"easier way to write the following example"* – Zoltan Toth Oct 16 '12 at 18:17
4

If you're talking about computational efficiency (i.e. browser performance), then I suggest sticking with what you already have. Otherwise...

If you know the class attribute always starts with the substring myTable, you can just use an attribute selector:

[class^="myTable"] a
{
    text-decoration: underline;
}

If you can't guarantee that you need something that's a little more complex:

[class^="myTable"] a, [class*=" myTable"] a
{
    text-decoration: underline;
}

An explanation is offered here. If you find this syntax arcane, then I'll suggest again going with what you already have as it's the simplest.

Alternatively, modify your HTML to include a common class that you can select by. This will let you simplify your CSS even more from what you already have.

Community
  • 1
  • 1
BoltClock
  • 665,005
  • 155
  • 1,345
  • 1,328
2

No, there is not an easier way in plain CSS.

However if your many classes are all similar, you can do fuzzy matching like this *[class^="myTable"] { ... }.

tuff
  • 4,615
  • 4
  • 24
  • 40
1

You could use multiple classes in the tables that need underlined links.

HTML:

<table class="myTable1 ul_table">...</table>
<table class="myTable2 ul_table">...</table>
<table class="myTable3 ul_table">...</table>
<table class="myTable4 ul_table">...</table>

CSS:

.ul_table a {
    text-decoration: underline;
}
JSW189
  • 6,139
  • 11
  • 41
  • 71
  • This is probably the better approach to my overall problem. Thank you. For the sake of allowing the question itself to be answered, a solution like this is probably more acceptable. `[class^=myTable]` – Dmase05 Oct 16 '12 at 18:57