问题
I am looking for some kind of CSS selector that will only select certain cells from a table that only have these two specific classes and nothing else. Here is an example for a bit more clarity.
So in this table i want to select cells A and D for styling from the row but the only distinguishable way to select them is that they don't have any classes other than .abc and .xyz. So essentially i need to fitler out any cells that have any other classes i.e. .def, .ghi.
<tr>
<td class="abc xyz">A</td>
<td class="abc xyz def">B</td>
<td class="abc xyz ghi">C</td>
<td class="abc xyz">D</td>
</tr>
Now i know i could go about it using the not selector but these classes are injected into table from an external source and new classes could be added and i don't really want to keep adding to an ever growing list of classes to ignore.
td.abc.xyz:not(.def),
td.abc.xyz:not(.ghi) {
/* Style to apply */
}
So if anyone could point me in the right direction to anything that could help, it would be greatly appreciated.
回答1:
You can consider attribute selector but pay attention to whitespaces and order:
[class="abc xyz"],
[class="xyz abc"] {
color:red;
}
<table>
<tr>
<td class="abc xyz">A</td>
<td class="abc xyz def">B</td>
<td class="abc xyz ghi">C</td>
<td class="abc xyz">D</td>
<td class="xyz abc">D</td>
<td class="abc xyz ">this will fail</td>
</tr>
</table>
If you can add some JS you can avoid the whitespace issue using trim
var td=document.querySelectorAll('td');
for(var i=0;i<td.length;i++)
td[i].className=td[i].className.trim();
[class="abc xyz"],
[class="xyz abc"] {
color:red;
}
<table>
<tr>
<td class="abc xyz">A</td>
<td class="abc xyz def">B</td>
<td class="abc xyz ghi">C</td>
<td class="abc xyz">D</td>
<td class="xyz abc">D</td>
<td class="abc xyz ">this will be good</td>
</tr>
</table>
回答2:
[class="abc xyz"], [class="xyz abc"] { … }
来源:https://stackoverflow.com/questions/53913539/css-selector-for-only-two-classes-and-no-others