简体   繁体   中英

How can I target multiple css selectors in jquery

I am tying to apply some jQuery behaviour to two elements with their own css classes.

I am selecting the two classes like this...

$(".product-contain, .page-id-31").find("a:has(img)").fancybox({

However the script only works on the 2nd selector. I have tried various ways but cannot think of a proper way to do it, and I do not really wish to duplicate the code just for the other selector.

What is the correct way of applying the script to the above two selectors?

Thanks in advance.

Use each() to call with every element returned by selector, currently fancybox() is only called with the element at zero index returned by the selector.

$(".product-contain, .page-id-31").find("a:has(img)").each(function(){
      $(this).fancybox({
})

Try

$.each( [".product-contain", ".page-id-31",.....] , function(i, value){ 

     var el = $(value); 
     el.find("a:has(img)").fancybox({options});

});

Comma separation is the correct way to apply multiple selectors. The find function will attempt to match on all descendants of the context its applied to.

Your selector can be rewritten as: '.classA a.classC, .classB a.classC' if selector matches your intentions then your filtering is correct.

Find will NOT match the context elements themselves.

Also, as noted, ensure that the function being applied applies to the whole set of results and not just the first. FancyBox will only apply to the first element in the set. In this case you may apply the .each function to loop over all elements in the set and apply fancyBox

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM