如何用jQuery选择所有没有指定类别的元素

如何用jQuery选择所有没有指定类别的元素

所有不符合给定的选择器的元素都可以用jQuery( “:not(selector)” )选择。例如,第一个例子选择了所有未激活的<li>元素。

例子1:这个例子选择了不包含active类的<li>元素。

<!DOCTYPE html>
<html>
      
<head>
    <title>
        How to select all elements without
        a given class using jQuery ?
    </title>
      
    <meta charset="utf-8">
      
    <script src=
        "https://code.jquery.com/jquery-1.10.2.js">
    </script>
</head>
  
<body>
    <h1 style="color:green">GeeksforGeeks</h1>
      
    <b>
        Select all elements without a<br>
        given class using jQuery
    </b>
      
    <ul>
        <li class="active">element 1</li>
        <li>element 2</li>
        <li>element 3</li>
        <li>element 4</li>
    </ul>
      
    <script>
        $("li:not(.active)").css(
                "background-color", "yellow" );
    </script>
</body>
  
</html>

输出:
如何用jQuery选择所有没有指定类别的元素?

它也可以使用.not(selector)来完成。

例子2:这个例子选择了 不包含类绿或ID<div>元素。

<!DOCTYPE html>
<html>
  
<head>
    <meta charset="utf-8">
      
    <script src=
        "https://code.jquery.com/jquery-1.10.2.js">
    </script>
      
    <style>
        div {
            width: 50px;
            height: 50px;
            margin: 10px;
            float: left;
            border: 2px solid black;
        }
        .green {
            background: #8f8;
        }
        .orange {
            background: orange;
        }
        #blue {
            background: #99f;
        }
    </style>
</head>
  
<body>
    <h1 style="color:green">GeeksforGeeks</h1>
      
    <b>
        Select all elements without a
        given class using jQuery
    </b>
    <br><br>
  
    <div></div>
    <div id="blue"></div>
    <div></div>
    <div class="green"></div>
    <div class="green"></div>
    <div class="orange"></div>
    <div></div>
      
    <script>
        $("div").not(".green, #blue")
            .css("border-color", "red");
    </script>
</body>
  
</html>

输出:
如何用jQuery选择所有没有指定类别的元素?

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程