独家CSS选择器 [英] Exclusive CSS selector

查看:86
本文介绍了独家CSS选择器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在一个页面上,其中列表中的所选项目的特征是没有给定的类.类似于以下内容:

I am working on a page where the selected item among a list is characterized by NOT having a given class. Something like the following:

<ul>
  <li class="a">not selected</li>
  <li class="a b">selected</li>
  <li class="a">not selected</li>
</ul>

我想定义一个CSS选择器来获取只有a类的页面中的li节点. 不足为奇的是,以下语句是不够的:

I would like to defined a CSS selector to grab the li node in the page having ONLY the a class. Unsurprisingly the following statement is not enough:

document.querySelectorAll('li.a')

因为它返回所有具有 a 类的 li 节点.

Because it returns ALL the li nodes having the a class.

在这种情况下有经验吗?

Any experience on such scenario?

推荐答案

在这种情况下,您可以考虑使用属性选择器,如下所示:

In such case you may consider attribute selector like this:

console.log(document.querySelectorAll('li[class="a"]').length)

li[class="a"] {
  color:red;
}

<ul>
  <li class="a">Select me</li>
  <li class="a b c d more classes">Don't select me</li>
  <li class="a b">Don't select me</li>
  <li class="a">Select me</li>
</ul>

只需注意多余的空格:

console.log(document.querySelectorAll('li[class="a"]').length)

li[class="a"] {
  color:red;
}

<ul>
  <li class="a ">Pay attention to this one !!</li>
  <li class="a b">Don't select me</li>
  <li class="a">Select me</li>
</ul>

但是由于您使用的是JS,因此可以使用

But since you are using JS you can use trim() to get rid of the extra spaces:

var elem=document.querySelectorAll('li');
for(var i=0;i<elem.length;i++)
  elem[i].className=elem[i].className.trim();

console.log(document.querySelectorAll('li[class="a"]').length)

li[class="a"] {
  color:red;
}

<ul>
  <li class="a ">Pay attention to this one !!</li>
  <li class="a b">Don't select me</li>
  <li class="a">Select me</li>
</ul>

这篇关于独家CSS选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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