xsl
xsl

Reputation: 17406

"Select all, excluding" selector in JQuery

I have a DIV that contains many child elements like e.g. other DIVs, SPANs and links.

Is it possible to specify in JQuery selector that I want to call a function whenever an element of this DIV (including the DIV itself) is clicked, with the exception of all links (a), where this function should not be called?

Upvotes: 3

Views: 1811

Answers (4)

Felix Kling
Felix Kling

Reputation: 816334

Instead of selecting all and excluding some elements and bind event handlers to each of them, the easier way (imo) would be to attach the event handler just to the div and test whether a link was clicked or not (event delegation):

$('#yourDiv').click(function(event) {
    if(event.target.nodeName !== 'A') {
        // do your stuff
    }
});

This would only work if the links don't have any other elements as children.

More robust might be using .delegate [docs] and the :not [docs] pseudo selector:

$('#yourDiv').delegate(':not(a)', 'click', function(event) { // do your stuff });

Update: Apparently, you have to add another click event handler to the div to be able to detect clicks on the div itself (my tests with using the delegate selector only failed):

$('#yourDiv')
 .delegate(':not(a)', 'click', handler)
 .click(function(event) {
     if(event.target === this) {  // only if the `div` was clicked
         handler.apply(this, arguments);
     }
 });

Here, handler is the actual event handler you want to execute. By using an extra function, you don't have to repeat the code.

Upvotes: 3

AshHeskes
AshHeskes

Reputation: 2324

You can use the jQuery not() method to achieve what you are looking for.

e.g.

$('div, div *').not('a').click(function(){
    //handle click  
}); 

alternately you could use the :not() selector

e.g.

$('div, div *:not(a)').click(function(){
    //handle click  
}); 

But I personally find the first method more readable and prettier.

Upvotes: 2

Shef
Shef

Reputation: 45589

$('div#div_id, div#div_id *:not(a)').click(function(){
    // do whatever you like here
});

Demo

Upvotes: 2

Darin Dimitrov
Darin Dimitrov

Reputation: 1038720

You could use the the .not() method to exclude elements.

Upvotes: 1

Related Questions