Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery selector for links to images which tolerates query strings

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?

like image 687
leggo-my-eggo Avatar asked Dec 30 '25 20:12

leggo-my-eggo


2 Answers

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

like image 85
Rory McCrossan Avatar answered Jan 01 '26 11:01

Rory McCrossan


you could add the . to the expression, as in ".jpg" and then use *=

$('a[href*=".jpg"], a[href*=".jpeg"]')
like image 39
mindandmedia Avatar answered Jan 01 '26 10:01

mindandmedia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!