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?
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
divand test whether a link was clicked or not (event delegation):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
clickevent handler to thedivto be able to detect clicks on thedivitself (my tests with using the delegate selector only failed):Here,
handleris the actual event handler you want to execute. By using an extra function, you don’t have to repeat the code.