11

I have a listener for click events from which I need to exclude some elements.

Right now my list is growing, so I'm looking for a better way to "bundle" multiple elements in a selector.

This is what I have:

$(document).on('click tap', function(event) {               
    if ($(event.target).closest('div:jqmData(panel="popover")').length > 0 ||
        $(event.target).closest('div.pop_menuBox').length > 0 ||
        $(event.target).closest('.toggle_popover').length > 0 ) ||
        $(event.target).closest('.ui-selectmenu').length > 0 {
          return; 
    }
    // do stuff
});

Is there a better way to exclude these elements?

Thanks for help!

CAbbott
  • 8,078
  • 4
  • 31
  • 38
frequent
  • 27,643
  • 59
  • 181
  • 333

3 Answers3

30

You can specify CSS selectors, which means: you can use the comma to specify two or more selectors:

if($(event.target).closest('div:jqmData(panel="popover"), div.pop_menuBox, .toggle_popover, .ui-selectmenu').length > 0) {
    return; 
}
ckruse
  • 9,642
  • 1
  • 25
  • 25
7

Use a comma.

if ($(event.target)
     .closest('div:jqmData(panel="popover"), div.pop_menuBox, .toggle_popover, .ui-selectmenu').length > 0) {
     return; 
}
Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
2

According to the jquery documentation you can provide more than one selector for closest: http://api.jquery.com/closest/

T. Junghans
  • 11,385
  • 7
  • 52
  • 75
  • yes, I read this too. I was a little unsure what "This signature (only!) is deprecated as of jQuery 1.7. This method is primarily meant to be used internally or by plugin authors." on the Jquery page is supposed to mean? What's "signature"? – frequent Mar 21 '12 at 12:58
  • Thanks for pointing that out. Does it work for you? I'm also curious as to why jQuery puts it's selectors in an array in the example: ` var close = $("li:first").closest(["ul", "body"]);` – T. Junghans Mar 21 '12 at 13:06
  • Ok. Just tried it. If I do a regular selector with comma it works. I assume the array thing is no longer supported. Will test that later on – frequent Mar 21 '12 at 13:17