0

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.

3 Answers 3

6

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({
})
Sign up to request clarification or add additional context in comments.

Comments

0

Try

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

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

});

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.