Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
479 views
in Technique[技术] by (71.8m points)

javascript - Exclusive CSS selector

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...