158

I want to setup a click event trigger in jQuery for certain anchor tags.

I want to open certain links in a new tab while ignoring ones with a certain class (before you ask I cannot put classes on the links I am trying to catch as they come from a CMS).

I want to exclude links with class "button" OR "generic_link"

I have tried:

$(".content_box a[class!=button]").click(function (e) {
    e.preventDefault();     
    window.open($(this).attr('href'));
});

But that doesn't seem to work, also how do I do an OR statement to include "generic_link" in the exclusion?

3 Answers 3

317

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.

3
  • 2
    So I could do: $(".content_box a").not(".button").not(".generic_link").click(function (e)...?
    – Titan
    Jun 10, 2010 at 14:18
  • 1
    Worked perfectly, even when using .each().
    – cfx
    Jun 5, 2013 at 21:11
  • It seems that there is a bug when using .text() - the text of the element removed using say .not is still in the text.
    – Netsi1964
    Feb 12, 2015 at 10:28
29

use this..

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

4

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.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.