CSS selector for only two classes and no others

爱⌒轻易说出口 提交于 2021-02-05 06:05:37

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!