Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery exclude elements with certain class in selector

Tags:

jquery

People also ask

How to exclude selector in jQuery?

To exclude first and second element from jQuery, use the slice() method.

What is not() in jQuery?

The not() is an inbuilt function in jQuery which is just opposite to the filter() method. This function will return all the element which is not matched with the selected element with the particular “id” or “class”. Syntax: $(selector).not(A) The selector is the selected element which is not to be selected.


You can use the .not() method:

$(".content_box a").not(".button")

Alternatively, you can also use the :not() selector:

$(".content_box a:not('.button')")

There is little difference between the two approaches, except .not() is more readable (especially when chained) and :not() is very marginally faster. See this Stack Overflow answer for more info on the differences.


use this..

$(".content_box a:not('.button')")


To add some info that helped me today, a jQuery object/this can also be passed in to the .not() selector.

$(document).ready(function(){
    $(".navitem").click(function(){
        $(".navitem").removeClass("active");
        $(".navitem").not($(this)).addClass("active");
    });
});
.navitem
{
    width: 100px;
    background: red;
    color: white;
    display: inline-block;
    position: relative;
    text-align: center;
}
.navitem.active
{
    background:green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="navitem">Home</div>
<div class="navitem">About</div>
<div class="navitem">Pricing</div>

The above example can be simplified, but wanted to show the usage of this in the not() selector.