Reputation: 481
How can I select all DOM elements except for a given element and its descendants with CSS or jQuery?
Say the given element is #test
$('#test *')
will return all #test descendants
--but--
$('* :not(#test))')
OR $('* :not(#test *))')
OR $('*').not('#test')
OR $('*').not('#test *')
do not work!
EDIT:
I want to trigger a click event when clicking anywhere on the page but the #test
area.
Upvotes: 2
Views: 451
Reputation: 723618
I want to trigger a click event when clicking anywhere on the page but the
#test
area.
Then you don't need to bind click to every element... just bind to the document and check if it's $('#test, #test *')
that's being hit and if so, abort the click handler:
$(document).on('click', function(e) {
if ($(e.target).is('#test, #test *')) {
return;
}
// Do stuff
});
Upvotes: 3
Reputation: 12197
In your click event check if the click was within #test
: http://jsfiddle.net/QDNCS/
$(document).click(function(e) {
if (!$('#test')[0].contains(e.target)) {
alert('Yay!');
}
});
Upvotes: 1
Reputation: 12113
You can combine the answers from @The System Restart and @topp to get the requested behavior:
$(document).on('click', function (e) {
if ($(this).is('#test, #test *')) {
return;
}
}
Note I haven't tested this code.
Upvotes: 0
Reputation: 1000
I don't know the exact jQuery code for this, but this jQuery script seems to be what you are looking for.
http://benalman.com/projects/jquery-outside-events-plugin/
Hope this helps
Upvotes: 0
Reputation: 150
The System Restart was close:
$('*').not('#test, #test *')
Nonetheless I wouldn't bind an event to that selector -- it could select too many element and make your site work sluggish. If it happens consider using jquery's live()
instead.
Upvotes: 0