I'm looking for a jQuery selector to find all links to images, which is simple enough with say,
$('a[href$="jpg"], a[href$="jpeg"], a[href$="png"], a[href$="gif"]')
But this breaks if my link has a query string appended to it, like this:
<a href="http://example.com/image1.jpg?1737892">link</a>
Is there a way to select all image links like the above, but which will still work if the image link has a query string at the end of it?
The reason this breaks is because the $ part of the selector means it's only looking for jpg at the end of the href. Use the contains selector (*) instead, and include the dot of the extension:
$('a[href*=".jpg"], a[href*="jpeg"], a[href*=".png"], a[href*=".gif"]')
Note though, that this means it would match the following urls too:
http://mysite.com/fakelink.jpg.aspx
http://mysite.com/page.php?param=image.jpg
So you're not 100% guaranteed to be selecting a link to an image, even though this eventuality is unlikely.
Example fiddle
you could add the . to the expression, as in ".jpg" and then use *=
$('a[href*=".jpg"], a[href*=".jpeg"]')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With