Tutorial :How do I select an image based on its path/url?



Question:

I'm tying to select images based on their URLs, but for some reason it's not playing ball:

Ultimately I'm after something like:

var imgs = $("img[@src='images/object.png']:not(:hidden)");  

But even with something simple like:

$("img[@src='images/object.png']");  

This error is thrown: "TypeError: Object doesn't support this property or method".

If I omit the @ from the query:

$("img[src='images/object.png']");  

I get no items returned. I've copied and pasted the path directly from the generated html at runtime and it still refuses to return any items. If I replace the src selector with an id selector, it returns the items.

This is the image tag generated at runtime:

<img id="ctl00_ContentPlaceHolder1_object_1" src="images/object.png" style="height:16px;width:16px;border-width:0px;visibility:visible;display:inline;margin-right:3px;" />  

I'm running jQuery 1.4.2 and I've checked all the documentation and all appears to be coded correctly. I'm assuming this isn't a bug, but a misinterpretation on my part. Can anyone she any light on this?

Cheers


Solution:1

Don't use the @ and be sure to include the full query too. If there is one.

$("img[src='/images/marketing/logo.png?1277792289']")[0]  

You can do substring matching as well

$("img[src*='logo']")[0]  

And the :not selector is in the wrong place. It should not be in the attribute brackets.

$("img[src*='logo']:not(:visible)")[0]  


Solution:2

This used to be a bug in jQuery and apparently it still is.

Check out the following tickets:

Essentially, what you have will work if you use the attributeEndsWith ($) or attributeContains (*) selectors because jQuery is not comparing your string against exactly what you put into the image src attribute, but against the full url path (ie, http:// ..... /images/object.png)


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »