Cezary Wojcik
Cezary Wojcik

Reputation: 21845

Excluding an element from jQuery selection

I'm trying to get a .click() event to work on a div.content except if clicked on something with a specific class, say, .noclick. Example html:

<div class="content">
    <a href="#" class="noclick">
</div>

Doing this doesn't work because the <a> tag is not technically in the selection:

$('.content').not('.noclick').click(function(){/*blah*/});

How can I get the click function to work if I click anywhere on .content except something with class .noclick?

Upvotes: 0

Views: 76

Answers (4)

user2264587
user2264587

Reputation: 474

$('.content').
on('click', '.noclick', function(){return false;}).
click(function(){alert("click")})

cancels clicks on '.noclick', yet fires clicks elsewhere

http://jsfiddle.net/FshCn/

Upvotes: 0

Ram
Ram

Reputation: 144659

$('.content').click(function(event) {
   // ...
}).find('.noclick').click(function(event) {
   event.stopPropagation();
});

Upvotes: 3

Paul
Paul

Reputation: 141839

$('.content').click(function(e){
    if(!$(e.target).is('.noclick')){
        // Handle click event
    }
});

Upvotes: 0

Blender
Blender

Reputation: 298106

You'd have to exclude them from within the callback:

$('.content').click(function(e) {
    if ($(e.target).hasClass('noclick')) return;
});

Or stop the event from leaving those elements:

$('.noclick').click(function(e) {
    e.stopPropagation();
});

I would go with the second one. You can just drop it and your current code (minus the .not()) will work.

Upvotes: 3

Related Questions