The first variant will do the following:
- Find all anchor tags in the page
- Only leave the ones with ancestor
div.product
- Only leave the ones with ancestor
div.gallery
The second one
- Find elements with class
.gallery and tag div
- Search for
div.product in their descendants
- Search for anchor tags in their descendants
So the first one will search for elements from right to left, while the second one will search them from left to right.
Which is faster depends on your site structure but the first one is the recommended way, because browsers match CSS selector the same way.
If you want to increase speed make sure that the rightmost selector is as specific as possible.
e.g.: in this case you can add a special class for your anchor tags like .gallery-link and then your query will become a simple a.gallery-link which in IE will invoke a getElementsByTagName function for the anchor tags then they will be filtered by their class name. Notice that because you don't have to traverel up the DOM tree your query becomes significantly faster. The cost is a bit more complex markup. For costly queries it may worth it.