• jQuery Video Tutorials

jQuery :not() Selector



The :not() Selector in jQuery is used to select all elements that do not match a given selector. This selector can be used with any jQuery selector to select everything except the specified element in a group.

Syntax

Following is the syntax of jQuery :not() Selector −

$(":not(selector)")

Parameters

Here is the description of the above syntax −

  • The :not(selector) specifies the element to not select.

Example 1

In the following example, we are using the jQuery :not() Selector to select all the <p> elements that do not have the class "exclude" −

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $("p:not(.exclude)").css("background-color", "yellow");
        });
    </script>
</head>
<body>
    <p>This paragraph will be blue.</p>
    <p class="exclude">This paragraph will not be blue.</p>
    <p>This paragraph will be blue too.</p>
</body>
</html>

After executing the above program, the selected elements will be highlighted with yellow background color.

Example 2

In this example, we are selecting all the <div> elements that do not have the ID "exclude" −

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            // Select all <div> elements that do not have the ID 'exclude' and set their background color to yellow
            $("div:not(#exclude)").css("background-color", "yellow");
        });
    </script>
</head>
<body>
    <div>This div will have a yellow background.</div>
    <div id="exclude">This div will not have a yellow background.</div>
    <div>This div will have a yellow background too.</div>
</body>
</html>

The <div> elements that do not have the ID "exclude" will be highlighted with yellow background color.

jquery_ref_selectors.htm
Advertisements