最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Exclusive CSS selector - Stack Overflow

programmeradmin4浏览0评论

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>

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')

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

Any experience on such scenario?

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>

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')

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

Any experience on such scenario?

Share Improve this question edited Sep 28, 2018 at 14:34 Temani Afif 275k28 gold badges365 silver badges486 bronze badges asked Sep 28, 2018 at 14:11 Alberto De CaroAlberto De Caro 5,2039 gold badges50 silver badges76 bronze badges 0
Add a ment  | 

3 Answers 3

Reset to default 9

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>

Simply pay attention to extra spaces:

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>

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>

Apart from Temanis answer you can use the not selector in this case

document.querySelectorAll('li.a:not(.b)')

You can use the :not() pseudo, that's exactly what you need for this job.

https://developer.mozilla/en-US/docs/Web/CSS/:not

So all you have to do is

document.querySelector(".a:not(.b)")

But also consider using jQuery, like

$(".someclass").not(".another")

Stansard querySelector is faster, jQ is more readable.

发布评论

评论列表(0)

  1. 暂无评论