Can I create a selector with multiple elements using Jquery closest()
Asked Answered
G

3

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!

Godman answered 21/3, 2012 at 12:52 Comment(3)
can you update the HTML on which jquery is working?Viceroy
Can't you just give each element you want to check the same class?Divulge
not sure what you mean? I'm using Jquery 1.7.1 (and Jquery Mobile)Godman
C
32

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; 
}
Condensed answered 21/3, 2012 at 12:55 Comment(0)
P
7

Use a comma.

if ($(event.target)
     .closest('div:jqmData(panel="popover"), div.pop_menuBox, .toggle_popover, .ui-selectmenu').length > 0) {
     return; 
}
Phytogeography answered 21/3, 2012 at 12:55 Comment(0)
G
2

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

Gary answered 21/3, 2012 at 12:55 Comment(3)
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"?Godman
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"]);`Gary
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 onGodman

© 2022 - 2024 — McMap. All rights reserved.