Exclusive CSS selector

后端 未结 3 1853
夕颜
夕颜 2020-12-07 03:53

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:

相关标签:
3条回答
  • 2020-12-07 04:25

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

    document.querySelectorAll('li.a:not(.b)')
    
    0 讨论(0)
  • 2020-12-07 04:34

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

    https://developer.mozilla.org/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 讨论(0)
  • 2020-12-07 04:41

    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>

    0 讨论(0)
提交回复
热议问题