Jquery on click select element if it is not in a specific class

I am trying to do this, but so far no luck, does anyone know how to select an element when pressed but not include the elements in a specific div like .boxall the content inside thisdiv .box

small update: thanks for the answers, but if I use :notor hasClass, it does not guarantee that the elements inside this foowill not be selected. eg:

<div class=foo>this won't be selected <span>this will</span></div>

+5
source share
3 answers

You can use the method hasClass():

$('a').click(function() {
    if (!(this).hasClass('foo')) {
        // the clicked element doesn't have the foo class        
    }
    return false;
});
+8
source

You can also use the: not () selector.

$("#mydiv:not(.box)").click(function(){
    //do something
});

, , <li> , :

$("#mydiv:not(.box)>li").click(function(){
    //do something
});

click() <li> , .box.

+5

Assuming you're looking for anchors, this should work ...

$(":not(.box) a").click(function() {
  // your code here
});

However, I would suggest re-splitting your markup to make it easier. For example, you can explicitly place a class with the ability to click / notclickable for each element.

+1
source

All Articles