amateur
amateur

Reputation: 44605

Finding images on page that have a specific filename with jquery

I need to do a check on a page to check if certain images have loaded ie. not returned 404. If they arent available I want to replace the image with a default images.

I am aware I can assign an onerror handler to the images.

Firstly I need to use a selector to find all the images that have a source which contains the following image name -> /folder/Product_1234_P.jpg OR /folder/Product_9876_Q.gif

Any ideas how I can create a high performance selector that I can use to find such images so that I can check if the images loaded, if not replace the image name with: Product_Default_P.jpg or Product_Default_Q.gif

Any help or advice would be great.

Upvotes: 3

Views: 2550

Answers (3)

AndreKR
AndreKR

Reputation: 33658

I guess you mean something like

$("img[src^=/folder/Product_][src$=_P.jpg]")

i.e. "Find all img with a src starting with "/folder/Product_" and ending with "_P.jpg".

Upvotes: 1

Jason McCreary
Jason McCreary

Reputation: 72961

$('img[src*="substring"]')

It's an attribute selector. Check it out http://api.jquery.com/attribute-contains-selector/

Upvotes: 1

karim79
karim79

Reputation: 342625

You can use the image's error handler and the attribute contains selector like so:

$("img[src*=Product]").error(function() {
    $(this).attr('src', 'notfound.jpeg');
});

Upvotes: 4

Related Questions