Adam
Adam

Reputation: 1459

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.

Upvotes: 0

Views: 1461

Answers (3)

Kyle
Kyle

Reputation: 1019

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

Upvotes: 0

Adil
Adil

Reputation: 148110

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({
})

Upvotes: 6

Andy Ecca
Andy Ecca

Reputation: 1969

Try

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

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

});

Upvotes: 0

Related Questions