How to Select Element That Does Not have Specific Class

前端 未结 5 1926
别跟我提以往
别跟我提以往 2020-11-27 14:38

I\'m wondering how to select an element that does not have a specific class using JavaScript, not jQuery.

For example, I have this list:

相关标签:
5条回答
  • 2020-11-27 14:48

    You can try the :not() selector

    var completeTask = document.querySelector("li:not(.completed):not(.selected)");
    

    http://jsfiddle.net/UM3j5/

    0 讨论(0)
  • 2020-11-27 14:49
    document.querySelectorAll('[wf-body=details] input:not(.switch):not(.btn)').forEach(function(e){
        // do whatever you want. with 'e' as element :P
    });
    
    0 讨论(0)
  • 2020-11-27 14:51

    To select the <li> that has not completed nor selected class:

    document.querySelector("li:not(.completed):not(.selected)");
    

    Fiddle

    http://jsfiddle.net/Z8djF/

    0 讨论(0)
  • 2020-11-27 15:02

    This selects the second LI element.

    document.querySelector("li:not([class])")
    

    or

    document.querySelector("li:not(.completed):not(.selected)")
    

    Example:

    // select li which doesn't have a 'class' attribute...
    console.log(document.querySelector("li:not([class])"))
    
    // select li which doesn't have a '.completed' and a '.selected' class...
    console.log(document.querySelector("li:not(.completed):not(.selected)"))
     <ul id="tasks">
        <li class="completed selected">One Task</li>
        <li>Two Task</li>
      </ul>

    0 讨论(0)
  • 2020-11-27 15:11

    Try getting an array of the parent's children instead:

    var completeTask = document.querySelector("#tasks").childNodes;
    

    Then loop/search them as necessary.

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