CSS选择器仅适用于两个类,没有其他选择器 [英] CSS selector for only two classes and no others

查看:49
本文介绍了CSS选择器仅适用于两个类,没有其他选择器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找某种CSS选择器,该选择器仅从具有这两个特定类的表中选择某些单元格,而没有其他选择.这是一个更加清晰的示例.

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.

因此在此表中,我想从行中选择单元格A和D进行样式设置,但是选择它们的唯一可区分方法是它们除了.abc和.xyz之外没有其他任何类.所以从本质上讲,我需要筛选出具有其他任何类(即.def,.ghi)的单元格.

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>

现在我知道我可以使用not选择器来解决这个问题,但是这些类是从外部源注入到表中的,可以添加新的类,而我真的不想一直添加到不断增长的类列表中忽略.

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.

推荐答案

您可以考虑属性选择器,但要注意空格和顺序:

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>

如果可以添加一些JS,则可以使用 trim

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>

这篇关于CSS选择器仅适用于两个类,没有其他选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆